Skip to content

oarepo_config

oarepo_config

Helper functions for writing a clean, high-level invenio.cfg.

Instead of hand-assembling dozens of Flask/Invenio config constants, invenio.cfg calls a small number of configure_*() functions from this package. Each one computes a group of related settings and writes them directly into invenio.cfg's own configuration, as if you had set them by hand:

import oarepo_config as config
from invenio_i18n import (
    lazy_gettext as _,
)

config.initialize_i18n()

config.configure_generic_parameters(
    languages=(("cs", _("Czech")),),
)

config.configure_ui(
    code="myrepo",
    name=_("My repository"),
    description=_(
        "Description of my repository"
    ),
)

config.configure_communities()
config.configure_cron()
config.configure_stats()

# Feel free to add/override plain CONFIG_VARIABLE = value assignments
# below, or use config.configure_vocabulary(...), config.add_model(...),
# config.register_workflow(...), etc. for further options.

See the project's README for the full list of available functions, the order they should be called in, and the environment variables they read.

Modules:

Name Description
ark

Configuration for ARK persistent identifiers (oarepo-ark).

base

Base configuration utilities for oarepo-config.

collections

Configuration for collections.

communities

Configuration for communities.

cron

Configuration for periodic (scheduled) background tasks.

datastreams

Configuration for datastreams.

detail_sidebar

Configuration of the boxes in the record detail page sidebar.

einfra

Configuration for oarepo-oidc-einfra module.

files

Configuration for record files and upload quotas.

generic_parameters

Generic configuration parameters for oarepo-config.

i18n

Configuration for i18n.

jobs

Configuration for the Jobs feature.

llm

Configuration for oarepo-checks.

models

Configuration for models.

oai

Configuration for OAI-PMH.

rdm_defaults

InvenioRDM flavour defaults that only make sense for a deployed repository.

requests

Requests permission policy for oarepo-config.

stats

Configuration for invenio-stats module.

ui

Configuration for the repository UI.

vocabulary

Configuration for vocabulary.

workflows

Configuration for workflows.

CSP dataclass

Content Security Policy configuration.

Source code in oarepo_config/ui.py
@dataclasses.dataclass
class CSP:
    """Content Security Policy configuration."""

    default_src: list[str] = dataclasses.field(default_factory=list)
    """Fallback for any directive below that is left unset."""

    script_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for JavaScript."""

    script_src_elem: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for `<script>` elements. Falls back to `script_src`."""

    script_src_attr: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for inline event handler attributes. Falls back to `script_src`."""

    style_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for CSS."""

    style_src_elem: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for `<style>` elements. Falls back to `style_src`."""

    style_src_attr: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for inline style attributes. Falls back to `style_src`."""

    img_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for images."""

    font_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for fonts."""

    connect_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for fetch/XHR/WebSocket/EventSource calls (e.g. REST API endpoints)."""

    object_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for `<object>`, `<embed>` and `<applet>` plugins."""

    media_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for `<audio>`, `<video>` and `<embed>` media."""

    frame_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for nested browsing contexts (`<iframe>`)."""

    frame_ancestors: list[str] = dataclasses.field(default_factory=list)
    """Sources allowed to embed this page; the modern replacement for `X-Frame-Options`."""

    child_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for nested browsing contexts and workers."""

    worker_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for Web Workers."""

    manifest_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for the application manifest."""

    prefetch_src: list[str] = dataclasses.field(default_factory=list)
    """Valid sources that may be prefetched."""

    form_action: list[str] = dataclasses.field(default_factory=list)
    """Valid targets for `<form>` submissions."""

    base_uri: list[str] = dataclasses.field(default_factory=list)
    """Valid sources for the document's `<base>` element."""

    report_to: list[str] = dataclasses.field(default_factory=list)
    """`Report-To` group name(s) to send CSP reports to; the modern replacement for `report_uri`."""

    report_uri: str | None = None
    """URL to send CSP violation reports to."""

    report_only: bool = False
    """Report violations without enforcing the policy. Requires `report_uri`."""

    #: Fields that map to Talisman's standalone CSP options rather than to a
    #: directive inside the `content_security_policy` dict.
    _NON_DIRECTIVE_FIELDS: ClassVar[frozenset[str]] = frozenset({"report_uri", "report_only"})

    #: Directives that CSP does not let `default-src` stand in for.
    _NO_DEFAULT_SRC: ClassVar[frozenset[str]] = frozenset({"base-uri", "form-action", "frame-ancestors", "report-to"})

    #: Directives that CSP resolves through a more specific directive before
    #: it ever considers `default-src`.
    _FALLBACK_PARENT: ClassVar[dict[str, str]] = {
        "script-src-elem": "script-src",
        "script-src-attr": "script-src",
        "style-src-elem": "style-src",
        "style-src-attr": "style-src",
        "worker-src": "child-src",
        "frame-src": "child-src",
    }

    def apply_defaults(self, headers: dict[str, Any]) -> dict[str, Any]:
        """Resolve this policy against the `content_security_policy` already in *headers*.

        Directives set here are merged with the sources already configured for
        them (or, lacking those, with the sources of the directive they'd fall
        back to, e.g. `default-src` for `connect_src`), so that setting one
        directive doesn't silently drop defaults the app still needs. Unset
        directives keep the configured value as-is. Same for `report_uri`,
        `report_only`.

        The result replaces the CSP keys in *headers* rather than merging into
        them: `headers.update(csp.apply_defaults(headers))`.

        Raises:
            ValueError: If report-only mode ends up enabled without any
                `report_uri`, which Flask-Talisman rejects.

        """
        existing = self._existing_policy(headers)
        resolved = self._resolve_policy(existing)

        options: dict[str, Any] = {}
        if resolved:
            options["content_security_policy"] = resolved

        report_uri = self.report_uri or headers.get("content_security_policy_report_uri")
        report_only = self.report_only or bool(headers.get("content_security_policy_report_only"))

        if report_only and not report_uri:
            raise ValueError(
                "report_only requires a report_uri, set on the CSP or already configured in APP_DEFAULT_SECURE_HEADERS."
            )
        if report_uri:
            options["content_security_policy_report_uri"] = report_uri
        if report_only:
            options["content_security_policy_report_only"] = True

        return options

    def _resolve_policy(self, existing: dict[str, list[str]]) -> dict[str, list[str]]:
        """Combine the configured sources with the ones set on this policy."""
        resolved: dict[str, list[str]] = {}
        for field in dataclasses.fields(self):
            if field.name in self._NON_DIRECTIVE_FIELDS:
                continue
            directive = field.name.replace("_", "-")
            configured = existing.get(directive, [])
            own = getattr(self, field.name)
            if own:
                # an explicit directive overrides the fallback it would
                # otherwise inherit, so bring those sources back into it
                defaults = configured or self._inherited_sources(directive, existing)
                sources = list(dict.fromkeys([*own, *defaults]))
            else:
                sources = configured
            if sources:
                resolved[directive] = sources

        # keep directives Talisman understands but this class does not model,
        # including the source-less ones such as 'upgrade-insecure-requests'
        for directive, sources in existing.items():
            resolved.setdefault(directive, list(sources))

        return resolved

    def _inherited_sources(self, directive: str, existing: dict[str, list[str]]) -> list[str]:
        """Return the sources of the first directive *directive* falls back to."""
        if directive in self._NO_DEFAULT_SRC:
            return []
        seen = {directive}
        current = self._FALLBACK_PARENT.get(directive, "default-src")
        while current not in seen:
            seen.add(current)
            if existing.get(current):
                return existing[current]
            current = self._FALLBACK_PARENT.get(current, "default-src")
        return []

    @staticmethod
    def _existing_policy(headers: dict[str, Any]) -> dict[str, list[str]]:
        """Read the configured policy from *headers*, normalised to source lists."""
        policy = headers.get("content_security_policy") or {}
        if isinstance(policy, str):
            raise TypeError("only dict policies are supported, got str")
        return {
            directive: sources.split() if isinstance(sources, str) else list(sources)
            for directive, sources in policy.items()
        }

default_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Fallback for any directive below that is left unset.

script_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for JavaScript.

script_src_elem: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for <script> elements. Falls back to script_src.

script_src_attr: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for inline event handler attributes. Falls back to script_src.

style_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for CSS.

style_src_elem: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for <style> elements. Falls back to style_src.

style_src_attr: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for inline style attributes. Falls back to style_src.

img_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for images.

font_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for fonts.

connect_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for fetch/XHR/WebSocket/EventSource calls (e.g. REST API endpoints).

object_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for <object>, <embed> and <applet> plugins.

media_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for <audio>, <video> and <embed> media.

frame_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for nested browsing contexts (<iframe>).

frame_ancestors: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Sources allowed to embed this page; the modern replacement for X-Frame-Options.

child_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for nested browsing contexts and workers.

worker_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for Web Workers.

manifest_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for the application manifest.

prefetch_src: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources that may be prefetched.

form_action: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid targets for <form> submissions.

base_uri: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Valid sources for the document's <base> element.

report_to: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Report-To group name(s) to send CSP reports to; the modern replacement for report_uri.

report_uri: str | None = None class-attribute instance-attribute

URL to send CSP violation reports to.

report_only: bool = False class-attribute instance-attribute

Report violations without enforcing the policy. Requires report_uri.

apply_defaults(headers: dict[str, Any]) -> dict[str, Any]

Resolve this policy against the content_security_policy already in headers.

Directives set here are merged with the sources already configured for them (or, lacking those, with the sources of the directive they'd fall back to, e.g. default-src for connect_src), so that setting one directive doesn't silently drop defaults the app still needs. Unset directives keep the configured value as-is. Same for report_uri, report_only.

The result replaces the CSP keys in headers rather than merging into them: headers.update(csp.apply_defaults(headers)).

Raises:

Type Description
ValueError

If report-only mode ends up enabled without any report_uri, which Flask-Talisman rejects.

Source code in oarepo_config/ui.py
def apply_defaults(self, headers: dict[str, Any]) -> dict[str, Any]:
    """Resolve this policy against the `content_security_policy` already in *headers*.

    Directives set here are merged with the sources already configured for
    them (or, lacking those, with the sources of the directive they'd fall
    back to, e.g. `default-src` for `connect_src`), so that setting one
    directive doesn't silently drop defaults the app still needs. Unset
    directives keep the configured value as-is. Same for `report_uri`,
    `report_only`.

    The result replaces the CSP keys in *headers* rather than merging into
    them: `headers.update(csp.apply_defaults(headers))`.

    Raises:
        ValueError: If report-only mode ends up enabled without any
            `report_uri`, which Flask-Talisman rejects.

    """
    existing = self._existing_policy(headers)
    resolved = self._resolve_policy(existing)

    options: dict[str, Any] = {}
    if resolved:
        options["content_security_policy"] = resolved

    report_uri = self.report_uri or headers.get("content_security_policy_report_uri")
    report_only = self.report_only or bool(headers.get("content_security_policy_report_only"))

    if report_only and not report_uri:
        raise ValueError(
            "report_only requires a report_uri, set on the CSP or already configured in APP_DEFAULT_SECURE_HEADERS."
        )
    if report_uri:
        options["content_security_policy_report_uri"] = report_uri
    if report_only:
        options["content_security_policy_report_only"] = True

    return options

CommunityWorkflow dataclass

Bases: BaseWorkflowSettings

Workflow configuration for deposits inside communities.

Source code in oarepo_config/workflows/simplified/community.py
@dataclasses.dataclass
class CommunityWorkflow(BaseWorkflowSettings):
    """Workflow configuration for deposits inside communities."""

    draft_creation_community_roles: list[str] = dataclasses.field(
        default_factory=lambda: ["submitter", "curator", "owner"]
    )
    """Restrict draft creation to community members with at least one of these roles.

    If not specified (empty list), any member of the community can create a
    draft.  Used in addition to the site-wide
    `draft_creation_roles` /
    `draft_creation_needs` restrictions.
    """

    read_restricted_community_roles: list[str] = dataclasses.field(default_factory=lambda: ["curator", "owner"])
    """Community roles that may read restricted (published) records without requesting access.

    If empty, only the record owner can read the content after publishing. By default allowing curators
    and community owners to access restricted records.

    Note:
        Community roles are used instead of
        `RecordCommunitiesAction`
        so that each workflow can have independent read/draft/manage permissions.
    """

    read_draft_community_roles: list[str] = dataclasses.field(default_factory=list)
    """Community roles that may read draft records without requesting access.

    If empty, only the record owner can read the content of a draft.  Curators
    can always read draft records when the record is submitted for review.

    Note:
        Community roles are used instead of
        `RecordCommunitiesAction`
        so that each workflow can have independent read/draft/manage permissions.
    """

    record_manage_community_roles: list[str] = dataclasses.field(default_factory=lambda: ["curator", "owner"])
    """Community roles that may manage (edit, delete, publish) records.

    If empty, only the record owner can manage the record. By default allowing curators
    and community owners to manage all records.

    Note:
        Community roles are used instead of
        `RecordCommunitiesAction`
        so that each workflow can have independent read/draft/manage permissions.
    """

    community_curator_roles: list[str] = dataclasses.field(default_factory=lambda: ["curator"])
    """Community roles that allow users to review and curate records."""

    # --- permission policy ----------------------------------------------------

    def _build_permission_policy(self) -> type[BasePermissionPolicy]:
        class PermissionPolicy(BooleanPermissionPolicyMixin, self.base_permission_policy):  # type: ignore[name-defined]
            """A permission policy for the workflow."""

            can_create = self._build_record_create_generators()
            can_read = self.base_permission_policy.can_read + self._build_record_view_permissions()
            can_rdm_manage = self._build_record_rdm_manage_generators(self.base_permission_policy.can_rdm_manage)  # type: ignore[attr-defined]
            can_rdm_view = self._build_record_rdm_view_permissions(self.base_permission_policy.can_rdm_view)  # type: ignore[attr-defined]
            can_rdm_preview = self._build_record_rdm_preview_generators(self.base_permission_policy.can_rdm_preview)  # type: ignore[attr-defined]
            can_publish = (*self.base_permission_policy.can_publish, RequestActive())  # type: ignore[attr-defined]

        return PermissionPolicy

    def _build_record_create_generators(self) -> tuple[Generator, ...]:
        """Extend base create generators with community membership constraints.

        Calls `_build_record_create_generators` to
        resolve site-wide role- and need-based restrictions, then appends an
        `InAnyCommunity`
        generator for each role listed in `draft_creation_community_roles`.

        Returns:
            A tuple of permission generators for the `can_create` policy action.

        """
        create_generators = list(super()._build_record_create_generators())
        for role in self.draft_creation_community_roles:
            create_generators += [InAnyCommunity(PrimaryCommunityRole(role))]
        return tuple(create_generators)

    # --- RDM permission helpers -----------------------------------------------

    def _replace_communities_action_with_roles(
        self,
        original_permissions: list[Generator],
        community_roles: list[str],
    ) -> list[Generator]:
        """Replace `RecordCommunitiesAction` with explicit community-role generators.

        Filters *original_permissions* to remove any
        `RecordCommunitiesAction`
        instance (which grants access to *all* community members), then appends a
        `CommunityRole`
        generator for each role in *community_roles*.

        This lets each workflow define fine-grained, role-scoped access instead of
        the blanket community-wide access granted by
        `RecordCommunitiesAction`.

        Args:
            original_permissions: The existing generator list from the base
                permission policy (e.g. `can_rdm_view`).
            community_roles: Community role names to grant access to.

        Returns:
            An updated generator list.

        """
        result = [gen for gen in original_permissions if not isinstance(gen, RecordCommunitiesAction)]
        result.extend(CommunityRole(role) for role in community_roles)
        return result

    def _build_record_rdm_view_permissions(self, original_rdm_permissions: list[Generator]) -> list[Generator]:
        """Build `can_rdm_view` generators for this workflow.

        Replaces `RecordCommunitiesAction` with
        `read_restricted_community_roles`-scoped generators so that only
        the listed community roles (rather than all community members) can read
        restricted records.

        Args:
            original_rdm_permissions: The existing `can_rdm_view` generators
                from the base permission policy.

        Returns:
            Updated generator list.

        """
        return self._replace_communities_action_with_roles(
            original_rdm_permissions, self.read_restricted_community_roles
        )

    def _build_record_rdm_preview_generators(self, original_rdm_permissions: list[Generator]) -> list[Generator]:
        """Build `can_rdm_preview` generators for this workflow.

        Replaces `RecordCommunitiesAction` with
        `read_draft_community_roles`-scoped generators so that only the
        listed community roles (rather than all community members) can preview
        draft records.

        Args:
            original_rdm_permissions: The existing `can_rdm_preview` generators
                from the base permission policy.

        Returns:
            Updated generator list.

        """
        return self._replace_communities_action_with_roles(original_rdm_permissions, self.read_draft_community_roles)

    def _build_record_rdm_manage_generators(self, original_rdm_permissions: list[Generator]) -> list[Generator]:
        """Build `can_rdm_manage` generators for this workflow.

        Replaces `RecordCommunitiesAction` with
        `record_manage_community_roles`-scoped generators so that only
        the listed community roles (rather than all community members) can
        manage records.

        Args:
            original_rdm_permissions: The existing `can_rdm_manage` generators
                from the base permission policy.

        Returns:
            Updated generator list.

        """
        return self._replace_communities_action_with_roles(original_rdm_permissions, self.record_manage_community_roles)

    # --- request policy -------------------------------------------------------

    def _build_request_policy(self) -> type[WorkflowRequestPolicy]:
        curator_generators: list[PrimaryCommunityRole] = [
            PrimaryCommunityRole(role) for role in self.community_curator_roles
        ]

        requests = {
            # File modification requests let record owners unlock a published
            # record's files (grace-period feature). Created and accepted by
            # invenio's file_modification service (owner submits, system accepts),
            # so no reviewer and no record state transition.
            FileModification.type_id: WorkflowRequest(
                requesters=[RecordOwners()],
                recipients=[RecordOwnersForRecipients()],
                transitions=WorkflowTransitions(),
            ),
            # Quota increase requests let record owners raise a draft's storage
            # quota from their additional allowance. Created and accepted by
            # invenio's quota_increase service (owner submits, system accepts),
            # so no reviewer and no record state transition.
            QuotaIncrease.type_id: WorkflowRequest(
                requesters=[RecordOwners()],
                recipients=[RecordOwnersForRecipients()],
                transitions=WorkflowTransitions(),
            ),
            CommunitySubmission.type_id: WorkflowRequest(
                requesters=[
                    IfNewRecord(
                        then_=self._build_record_create_generators(),
                        else_=[
                            # Note: this permission check can be called from /review url, that is
                            # inside review service's create method. The problem is that review
                            # service does not pass the original record - it fills the "record"
                            # parameter with a community. That's why we can not use IfInState
                            # and similar permission generators that depend on the record.
                            *[
                                IfRDMRecordPassed(
                                    # the user has called the requests' create method directly
                                    then_=[RequireAll(RecordOwners(), PrimaryCommunityRole(role))],
                                    # the user went through the review flow which did not pass the record
                                    else_=[PrimaryCommunityRole(role)],
                                )
                                for role in self.draft_creation_community_roles
                            ],
                            *curator_generators,
                        ],
                    )
                ],
                recipients=curator_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="draft",
                    cancelled="draft",
                ),
            ),
            PublishChangedMetadataRequestType.type_id: WorkflowRequest(
                requesters=[
                    IfInState(
                        ["draft", "revision_requested"],
                        [
                            RecordOwners(),
                            *curator_generators,
                        ],
                    )
                ],
                recipients=curator_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="revision_requested",
                    cancelled="draft",
                ),
            ),
            PublishNewVersionRequestType.type_id: WorkflowRequest(
                requesters=[
                    IfInState(
                        ["draft", "revision_requested"],
                        [
                            RecordOwners(),
                            *curator_generators,
                        ],
                    )
                ],
                recipients=curator_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="revision_requested",
                    cancelled="draft",
                ),
            ),
            # note: we need to patch https://github.com/inveniosoftware/invenio-rdm-records/blob/master/invenio_rdm_records/services/access/service.py#L784,
            # this will not work without the patch
            UserAccessRequest.type_id: WorkflowRequest(
                requesters=[AuthenticatedUser()],
                recipients=curator_generators,
            ),
        }

        return self._create_request_policy("CommunityReviewRequestPolicy", requests)

draft_creation_community_roles: list[str] = dataclasses.field(default_factory=lambda: ['submitter', 'curator', 'owner']) class-attribute instance-attribute

Restrict draft creation to community members with at least one of these roles.

If not specified (empty list), any member of the community can create a draft. Used in addition to the site-wide draft_creation_roles / draft_creation_needs restrictions.

read_restricted_community_roles: list[str] = dataclasses.field(default_factory=lambda: ['curator', 'owner']) class-attribute instance-attribute

Community roles that may read restricted (published) records without requesting access.

If empty, only the record owner can read the content after publishing. By default allowing curators and community owners to access restricted records.

Note

Community roles are used instead of RecordCommunitiesAction so that each workflow can have independent read/draft/manage permissions.

read_draft_community_roles: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Community roles that may read draft records without requesting access.

If empty, only the record owner can read the content of a draft. Curators can always read draft records when the record is submitted for review.

Note

Community roles are used instead of RecordCommunitiesAction so that each workflow can have independent read/draft/manage permissions.

record_manage_community_roles: list[str] = dataclasses.field(default_factory=lambda: ['curator', 'owner']) class-attribute instance-attribute

Community roles that may manage (edit, delete, publish) records.

If empty, only the record owner can manage the record. By default allowing curators and community owners to manage all records.

Note

Community roles are used instead of RecordCommunitiesAction so that each workflow can have independent read/draft/manage permissions.

community_curator_roles: list[str] = dataclasses.field(default_factory=lambda: ['curator']) class-attribute instance-attribute

Community roles that allow users to review and curate records.

IndividualWorkflow dataclass

Bases: BaseWorkflowSettings

Workflow configuration for deposits outside of communities.

Source code in oarepo_config/workflows/simplified/individual.py
@dataclasses.dataclass
class IndividualWorkflow(BaseWorkflowSettings):
    """Workflow configuration for deposits outside of communities."""

    code: str = "individual"
    """Unique code identifier for this workflow."""

    label: LazyString = _("Individual Submission Workflow")  # noqa: RUF009
    """Human-readable label for this workflow."""

    authenticated_draft_creation: bool = True
    """Allow authenticated users to create drafts in this workflow.

    Overrides the base-class default of `False`; any authenticated user can
    create a draft unless more-specific role or need restrictions are configured
    via `draft_creation_roles` or
    `draft_creation_needs`.
    """

    publish_without_review: bool = False
    """Allow draft owners to publish without submitting a review request.

    When enabled, draft owners can publish directly, subject to
    `publish_without_review_states`.
    """

    publish_without_review_roles: list[str] = dataclasses.field(default_factory=list)
    """Roles that allow a draft owner to publish without a review request.

    Users must still be owners of the draft record. If the list is non-empty,
    `publish_without_review` is ignored.
    """

    publish_without_review_needs: list[str] = dataclasses.field(default_factory=list)
    """Permission needs that allow a draft owner to publish without a review request.

    Users must still be owners of the draft record. If the list is non-empty,
    `publish_without_review` is ignored.
    """

    publish_without_review_states: list[str] = dataclasses.field(default_factory=lambda: ["draft"])
    """Record workflow states in which publication without review is allowed."""

    review_required: bool = False
    """Require a review request before publication.

    If `publish_without_review` is `False` and `review_required`
    is `False`, records can only be published through a community workflow.
    """

    reviewer_roles: list[str] = dataclasses.field(default_factory=list)
    """Roles that allow users to review and curate records.

    Users with these roles are also granted read access to draft records.
    """

    reviewer_needs: list[str] = dataclasses.field(default_factory=list)
    """Permission needs that allow users to review and curate records.

    Users with these needs are also granted read access to draft records.
    """

    self_review_enabled: bool = False
    """Allow the record owner to approve their own review request.

    Normally, submitting a record for review prevents the owner from approving it
    themselves. When set to `True`, the review request is still created on
    submission, but the owner is permitted to accept it.

    This is primarily useful when `invenio-checks` is active: checks are tied
    to an open request, so the request must exist even when no external reviewer
    is needed. With this option the owner can see and act on the check results
    without waiting for a curator.

    Has no effect when `publish_without_review` is `True`, because in
    that case user can bypass the review request and publish the record directly.
    """

    def _build_permission_policy(self) -> type[BasePermissionPolicy]:
        class PermissionPolicy(BooleanPermissionPolicyMixin, self.base_permission_policy):  # type: ignore[unsupported-base]
            """A permission policy for the workflow."""

            can_create = self._build_record_create_generators()
            can_publish = (
                *add_if_in_state(
                    self.publish_without_review_states,
                    self._build_record_publish_generators(),
                ),
                IfInState("submitted", then_=[RequestActive()]),
            )
            can_read = self.base_permission_policy.can_read + self._build_record_view_permissions()

        return PermissionPolicy

    def _build_record_publish_generators(self) -> tuple[Generator, ...]:
        """Build generators that control who may publish a draft without a review request.

        Applies the following priority order:

        1. **Role-based** - `publish_without_review_roles`: owners who also
           hold any of these roles may publish directly.
        2. **Need-based** - `publish_without_review_needs`: owners who also
           possess any of these permission needs may publish directly.
        3. **Owner fallback** - when neither (1) nor (2) are set and
           `publish_without_review` is `True`, the draft owner may publish
           directly.

        Note:
            `SystemProcess` is added automatically by the base policy; it does
            not need to be included here.

        Returns:
            A tuple of permission generators for the `can_publish` policy action.

        """
        publish_generators: list[Generator] = []
        if self.publish_without_review_roles:
            publish_generators += [
                RequireAll(RecordOwners(), UserWithRole(role_name)) for role_name in self.publish_without_review_roles
            ]
        if self.publish_without_review_needs:
            publish_generators += [
                RequireAll(RecordOwners(), HasActionNeed(action)) for action in self.publish_without_review_needs
            ]
        if not publish_generators and self.publish_without_review:
            publish_generators = [RecordOwners()]
        return tuple(publish_generators)

    def _build_request_policy(self) -> type[WorkflowRequestPolicy]:
        # File modification requests let record owners unlock a published record's
        # files (grace-period feature). Available regardless of review, since it is
        # created and accepted by invenio's file_modification service (owner submits,
        # system accepts) -- no reviewer and no record state transition.
        base_requests = {
            FileModification.type_id: WorkflowRequest(
                requesters=[RecordOwners()],
                recipients=[RecordOwnersForRecipients()],
                transitions=WorkflowTransitions(),
            ),
            # Quota increase requests let record owners raise a draft's storage
            # quota from their additional allowance. Created and accepted by
            # invenio's quota_increase service (owner submits, system accepts),
            # so no reviewer and no record state transition.
            QuotaIncrease.type_id: WorkflowRequest(
                requesters=[RecordOwners()],
                recipients=[RecordOwnersForRecipients()],
                transitions=WorkflowTransitions(),
            ),
        }

        if not self.review_required:
            return self._create_request_policy("IndividualRequestPolicy", base_requests)

        reviewer_generators: list[Generator] = []
        if self.reviewer_roles:
            reviewer_generators = [UserWithRole(role) for role in self.reviewer_roles]
        if self.reviewer_needs:
            reviewer_generators.extend([HasActionNeed(need) for need in self.reviewer_needs])
        if self.self_review_enabled:
            reviewer_generators.extend(self.record_owners_with_correct_roles(RecordOwnersForRecipients()))  # type: ignore[arg-type]
        if not self.publish_after_review:
            raise NotImplementedError(
                "Disabling publish_after_review is not supported in this version, "
                "please ask the maintainers to enable it"
            )
        requestors = [*reviewer_generators]
        if not self.self_review_enabled:
            requestors.extend(self.record_owners_with_correct_roles(RecordOwners()))  # type: ignore[arg-type]

        requests = {
            **base_requests,
            PublishDraftRequestType.type_id: WorkflowRequest(
                requesters=[
                    IfInState(
                        ["draft", "revision_requested"],
                        requestors,
                    )
                ],
                recipients=reviewer_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="revision_requested",
                    cancelled="draft",
                ),
                events=WorkflowEvents(
                    {CommentEventType.type_id or "C": WorkflowEvent(submitters=[*requestors, *reviewer_generators])}
                ),
            ),
            PublishChangedMetadataRequestType.type_id: WorkflowRequest(
                requesters=[
                    IfInState(
                        ["draft", "revision_requested"],
                        requestors,
                    )
                ],
                recipients=reviewer_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="revision_requested",
                    cancelled="draft",
                ),
            ),
            PublishNewVersionRequestType.type_id: WorkflowRequest(
                requesters=[
                    IfInState(
                        ["draft", "revision_requested"],
                        requestors,
                    )
                ],
                recipients=reviewer_generators,
                transitions=WorkflowTransitions(
                    submitted="submitted",
                    accepted="published",
                    declined="revision_requested",
                    cancelled="draft",
                ),
            ),
            UserAccessRequest.type_id: WorkflowRequest(
                requesters=[AuthenticatedUser()],
                recipients=[RecordOwnersForRecipients()],
            ),
        }

        return self._create_request_policy("GlobalReviewRequestPolicy", requests)

    def record_owners_with_correct_roles(self, record_owner_generator: RecordOwners) -> list[Generator]:
        """Return the record owner generator with the correct roles/needs."""
        generators: list[Generator] = []
        if self.draft_creation_roles:
            generators += [
                RequireAll(record_owner_generator, UserWithRole(role_name)) for role_name in self.draft_creation_roles
            ]
        if self.draft_creation_needs:
            generators += [RequireAll(RecordOwners(), HasActionNeed(action)) for action in self.draft_creation_needs]
        if not generators:
            generators = [record_owner_generator]
        return generators

code: str = 'individual' class-attribute instance-attribute

Unique code identifier for this workflow.

label: LazyString = _('Individual Submission Workflow') class-attribute instance-attribute

Human-readable label for this workflow.

authenticated_draft_creation: bool = True class-attribute instance-attribute

Allow authenticated users to create drafts in this workflow.

Overrides the base-class default of False; any authenticated user can create a draft unless more-specific role or need restrictions are configured via draft_creation_roles or draft_creation_needs.

publish_without_review: bool = False class-attribute instance-attribute

Allow draft owners to publish without submitting a review request.

When enabled, draft owners can publish directly, subject to publish_without_review_states.

publish_without_review_roles: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Roles that allow a draft owner to publish without a review request.

Users must still be owners of the draft record. If the list is non-empty, publish_without_review is ignored.

publish_without_review_needs: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Permission needs that allow a draft owner to publish without a review request.

Users must still be owners of the draft record. If the list is non-empty, publish_without_review is ignored.

publish_without_review_states: list[str] = dataclasses.field(default_factory=lambda: ['draft']) class-attribute instance-attribute

Record workflow states in which publication without review is allowed.

review_required: bool = False class-attribute instance-attribute

Require a review request before publication.

If publish_without_review is False and review_required is False, records can only be published through a community workflow.

reviewer_roles: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Roles that allow users to review and curate records.

Users with these roles are also granted read access to draft records.

reviewer_needs: list[str] = dataclasses.field(default_factory=list) class-attribute instance-attribute

Permission needs that allow users to review and curate records.

Users with these needs are also granted read access to draft records.

self_review_enabled: bool = False class-attribute instance-attribute

Allow the record owner to approve their own review request.

Normally, submitting a record for review prevents the owner from approving it themselves. When set to True, the review request is still created on submission, but the owner is permitted to accept it.

This is primarily useful when invenio-checks is active: checks are tied to an open request, so the request must exist even when no external reviewer is needed. With this option the owner can see and act on the check results without waiting for a curator.

Has no effect when publish_without_review is True, because in that case user can bypass the review request and publish the record directly.

record_owners_with_correct_roles(record_owner_generator: RecordOwners) -> list[Generator]

Return the record owner generator with the correct roles/needs.

Source code in oarepo_config/workflows/simplified/individual.py
def record_owners_with_correct_roles(self, record_owner_generator: RecordOwners) -> list[Generator]:
    """Return the record owner generator with the correct roles/needs."""
    generators: list[Generator] = []
    if self.draft_creation_roles:
        generators += [
            RequireAll(record_owner_generator, UserWithRole(role_name)) for role_name in self.draft_creation_roles
        ]
    if self.draft_creation_needs:
        generators += [RequireAll(RecordOwners(), HasActionNeed(action)) for action in self.draft_creation_needs]
    if not generators:
        generators = [record_owner_generator]
    return generators

configure_ark(*, default_shoulder: str, shoulders: dict[str, str] | None = None, naan: str = '99999', handlers: dict[str, type | str] | None = None, default_handler: type | str | None = None, public_resolver: str | None = None, support: dict[str, str] | None = None, show_in_sidebar: bool = True) -> None

Give every record published as public an ARK (Archival Resource Key).

Requires the optional oarepo-ark package. If this function is not called, the package is installed but inert: no ARKs are minted and the /ark:... resolver answers 404.

Must be called after configure_ui, because it appends the ARK box to the detail page sidebar that configure_ui sets; calling it earlier raises an error (unless show_in_sidebar is False).

Parameters:

Name Type Description Default
default_shoulder str

The shoulder used for all models, e.g. "r1" (consonants followed by one digit). Required.

required
shoulders dict[str, str] | None

Per-model shoulder overrides, keyed by the model's service id (the model name, or its base_name).

None
naan str

Your NAAN from https://arks.org/. Defaults to the test NAAN "99999". Can be overridden per environment by the INVENIO_ARK_NAAN environment variable.

'99999'
handlers dict[str, type | str] | None

Per-model handler class (or its import string), keyed by the model's service id.

None
default_handler type | str | None

Handler class (or its import string) of all other models. Defaults to oarepo-ark's RDMRecordHandler.

None
public_resolver str | None

Resolver used in citable ARK URLs. Defaults to https://n2t.net/; leave as is.

None
support dict[str, str] | None

The erc-support persistence statement of ?info. Defaults to the site name, Permanent: Stable Content: and the site URL; leave as is.

None
show_in_sidebar bool

Add the ark box (oarepo_ark/ark_identifier.html) to the detail page sidebar, after the licenses box. Defaults to True. Use configure_detail_sidebar to place it elsewhere.

True

Invenio configuration variables set:

  • ARK_NAAN, ARK_DEFAULT_SHOULDER, ARK_SHOULDERS, ARK_HANDLERS - from the arguments above.
  • ARK_DEFAULT_HANDLER, ARK_PUBLIC_RESOLVER, ARK_SUPPORT - only if the corresponding argument is given.
  • APP_RDM_DETAIL_SIDE_BAR_TEMPLATES - the ark box is added if show_in_sidebar is True.
Example
config.configure_ui(...)

config.configure_ark(
    naan="12345",
    default_shoulder="r1",
    shoulders={"theses": "t1"},
)
Source code in oarepo_config/ark.py
def configure_ark(  # noqa: PLR0913
    *,
    default_shoulder: str,
    shoulders: dict[str, str] | None = None,
    naan: str = "99999",
    handlers: dict[str, type | str] | None = None,
    default_handler: type | str | None = None,
    public_resolver: str | None = None,
    support: dict[str, str] | None = None,
    show_in_sidebar: bool = True,
) -> None:
    """Give every record published as public an ARK (Archival Resource Key).

    Requires the optional `oarepo-ark` package. If this function is not
    called, the package is installed but inert: no ARKs are minted and the
    `/ark:...` resolver answers 404.

    Must be called *after* [`configure_ui`][oarepo_config.configure_ui], because it
    appends the ARK box to the detail page sidebar that `configure_ui` sets; calling it
    earlier raises an error (unless `show_in_sidebar` is `False`).

    Args:
        default_shoulder: The shoulder used for all models, e.g. `"r1"`
            (consonants followed by one digit). Required.
        shoulders: Per-model shoulder overrides, keyed by the model's
            service id (the model name, or its `base_name`).
        naan: Your NAAN from https://arks.org/. Defaults to the test NAAN
            `"99999"`. Can be overridden per environment by the
            `INVENIO_ARK_NAAN` environment variable.
        handlers: Per-model handler class (or its import string), keyed by
            the model's service id.
        default_handler: Handler class (or its import string) of all other
            models. Defaults to oarepo-ark's `RDMRecordHandler`.
        public_resolver: Resolver used in citable ARK URLs. Defaults to
            `https://n2t.net/`; leave as is.
        support: The `erc-support` persistence statement of `?info`.
            Defaults to the site name, `Permanent: Stable Content:` and
            the site URL; leave as is.
        show_in_sidebar: Add the `ark` box (`oarepo_ark/ark_identifier.html`)
            to the detail page sidebar, after the `licenses` box. Defaults to
            `True`. Use [`configure_detail_sidebar`][oarepo_config.configure_detail_sidebar]
            to place it elsewhere.

    Invenio configuration variables set:

    * `ARK_NAAN`, `ARK_DEFAULT_SHOULDER`, `ARK_SHOULDERS`,
      `ARK_HANDLERS` - from the arguments above.
    * `ARK_DEFAULT_HANDLER`, `ARK_PUBLIC_RESOLVER`, `ARK_SUPPORT` -
      only if the corresponding argument is given.
    * `APP_RDM_DETAIL_SIDE_BAR_TEMPLATES` - the `ark` box is added if
      `show_in_sidebar` is `True`.

    Example:
        ```python
        config.configure_ui(...)

        config.configure_ark(
            naan="12345",
            default_shoulder="r1",
            shoulders={"theses": "t1"},
        )
        ```

    """
    try:
        import oarepo_ark  # noqa: F401
    except ImportError:
        raise ImportError("Please add oarepo-ark to your dependencies") from None

    constants: dict[str, Any] = {
        "ARK_NAAN": naan,
        "ARK_DEFAULT_SHOULDER": default_shoulder,
        "ARK_SHOULDERS": dict(shoulders or {}),
        "ARK_HANDLERS": dict(handlers or {}),
    }
    if default_handler is not None:
        constants["ARK_DEFAULT_HANDLER"] = default_handler
    if public_resolver is not None:
        constants["ARK_PUBLIC_RESOLVER"] = public_resolver
    if support is not None:
        constants["ARK_SUPPORT"] = support

    if show_in_sidebar:
        sidebar = get_constant_from_caller("APP_RDM_DETAIL_SIDE_BAR_TEMPLATES")
        if sidebar is None:
            raise ValueError(
                "APP_RDM_DETAIL_SIDE_BAR_TEMPLATES must be set, please configure UI before configuring ARK "
                "(or pass show_in_sidebar=False)."
            )
        # boxes registered via configure_detail_sidebar for the global sidebar (key None)
        known = get_constant_from_caller("_OAREPO_CONFIG_DETAIL_SIDEBAR_TEMPLATES", {}).get(None, {})
        # after the licenses (rights) box, or at the end if the sidebar has none
        licenses = {DETAIL_SIDEBAR_TEMPLATES["licenses"], known.get("licenses")}
        has_licenses = any(path in sidebar for path in licenses if path)
        constants["APP_RDM_DETAIL_SIDE_BAR_TEMPLATES"] = update_detail_sidebar(
            sidebar,
            known=known,
            templates={"ark": DETAIL_SIDEBAR_TEMPLATES["ark"]},
            move=["ark after licenses"] if has_licenses else None,
        )

    set_constants_in_caller(constants)

configure_datastreams(readers: dict[str, Any] | None = None, writers: dict[str, Any] | None = None, transformers: dict[str, Any] | None = None) -> None

Register custom sources for importing vocabularies (fixtures) into the repository.

Vocabularies (controlled lists such as languages, resource types or licenses) can be loaded from files or external services using "datastreams" - a reader that fetches/reads the raw data, an optional transformer that converts it, and a writer that stores it. Invenio already ships with a set of built-in readers/writers/ transformers; use this function only if you need to add your own (for example, a reader that pulls a vocabulary from a custom REST API).

Parameters:

Name Type Description Default
readers dict[str, Any] | None

Extra readers to make available, as a mapping of a short name to either an import path string ("my_package.readers:MyReader") or the class/object itself.

None
writers dict[str, Any] | None

Extra writers to make available, in the same format as readers.

None
transformers dict[str, Any] | None

Extra transformers to make available, in the same format as readers.

None

Any readers/writers/transformers already registered (for example by configure_generic_parameters) are kept; the ones passed here are added on top.

Invenio configuration variables set:

  • VOCABULARIES_DATASTREAM_READERS - only if readers is given; merged with any existing value.
  • VOCABULARIES_DATASTREAM_WRITERS - only if writers is given; merged with any existing value.
  • VOCABULARIES_DATASTREAM_TRANSFORMERS - only if transformers is given; merged with any existing value.
Example
config.configure_datastreams(
    readers={
        "myreader": "my_package:MyReader"
    },
    writers={
        "mywriter": "my_package:MyWriter"
    },
)
Source code in oarepo_config/datastreams.py
def configure_datastreams(
    readers: dict[str, Any] | None = None,
    writers: dict[str, Any] | None = None,
    transformers: dict[str, Any] | None = None,
) -> None:
    """Register custom sources for importing vocabularies (fixtures) into the repository.

    Vocabularies (controlled lists such as languages, resource types or
    licenses) can be loaded from files or external services using
    "datastreams" - a reader that fetches/reads the raw data, an
    optional transformer that converts it, and a writer that stores it.
    Invenio already ships with a set of built-in readers/writers/
    transformers; use this function only if you need to add your own
    (for example, a reader that pulls a vocabulary from a custom REST
    API).

    Args:
        readers: Extra readers to make available, as a mapping of a
            short name to either an import path string
            (`"my_package.readers:MyReader"`) or the class/object
            itself.
        writers: Extra writers to make available, in the same format as
            `readers`.
        transformers: Extra transformers to make available, in the same
            format as `readers`.

    Any readers/writers/transformers already registered (for example by
    [`configure_generic_parameters`][oarepo_config.configure_generic_parameters]) are kept; the ones passed here
    are added on top.

    Invenio configuration variables set:

    * `VOCABULARIES_DATASTREAM_READERS` - only if `readers` is
      given; merged with any existing value.
    * `VOCABULARIES_DATASTREAM_WRITERS` - only if `writers` is
      given; merged with any existing value.
    * `VOCABULARIES_DATASTREAM_TRANSFORMERS` - only if
      `transformers` is given; merged with any existing value.

    Example:
        ```python
        config.configure_datastreams(
            readers={
                "myreader": "my_package:MyReader"
            },
            writers={
                "mywriter": "my_package:MyWriter"
            },
        )
        ```

    """
    # can't move into a function cause of constant_from_caller methods
    if readers:
        objs = {k: obj_or_import_string(v) for k, v in readers.items()}
        VOCABULARIES_DATASTREAM_READERS = merge_with_caller("VOCABULARIES_DATASTREAM_READERS", objs)

    if writers:
        objs = {k: obj_or_import_string(v) for k, v in writers.items()}
        VOCABULARIES_DATASTREAM_WRITERS = merge_with_caller("VOCABULARIES_DATASTREAM_WRITERS", objs)

    if transformers:
        objs = {k: obj_or_import_string(v) for k, v in transformers.items()}
        VOCABULARIES_DATASTREAM_TRANSFORMERS = merge_with_caller("VOCABULARIES_DATASTREAM_TRANSFORMERS", objs)
    set_constants_in_caller(locals())

configure_detail_sidebar(*, templates: dict[str, str] | None = None, order: list[str] | None = None, move: list[str] | None = None, remove: list[str] | None = None, model: str | None = None) -> None

Change the boxes shown in the sidebar of the record detail page.

The boxes are referred to by symbolic names (see DETAIL_SIDEBAR_TEMPLATES): manage_menu, versions, external_resources, communities, keywords_subjects, details, locations, licenses, citations, export, technical_metadata, metrics and ark (added by configure_ark). A box registered via templates is referred to by its new name.

The changes are applied to the current sidebar, in this order: templates, order, move, remove. Must be called after configure_ui and any other configure_* function that adds a box (e.g. configure_ark). Can be called multiple times.

Parameters:

Name Type Description Default
templates dict[str, str] | None

Box name -> template. An existing box gets the new template in place; a new box is appended at the end.

None
order list[str] | None

The new order of the boxes. "..." stands for all the boxes not listed, in their current order; without it, the boxes not listed are removed.

None
move list[str] | None

Moves applied one after another, each one of "<box> before <box>", "<box> after <box>", "<box> first" or "<box> last".

None
remove list[str] | None

Boxes to remove.

None
model str | None

Change only the sidebar of this model (the model name). Its sidebar starts as a copy of the global one.

None

Invenio configuration variables set:

  • APP_RDM_DETAIL_SIDE_BAR_TEMPLATES - without model.
  • OAREPO_UI_SIDEBAR_TEMPLATES[model] - with model.
  • _OAREPO_CONFIG_DETAIL_SIDEBAR_TEMPLATES - internal: the boxes registered via templates, per sidebar (model name, None for the global one), so that later calls know their names.
Example
config.configure_ui(...)

config.configure_detail_sidebar(
    templates={
        "locations": "datasets/record_detail/side_bar/locations.html",
        "licenses": "datarepo/records/details/side_bar/licenses.html",
    },
    move=["locations after details"],
)
Source code in oarepo_config/detail_sidebar.py
def configure_detail_sidebar(
    *,
    templates: dict[str, str] | None = None,
    order: list[str] | None = None,
    move: list[str] | None = None,
    remove: list[str] | None = None,
    model: str | None = None,
) -> None:
    """Change the boxes shown in the sidebar of the record detail page.

    The boxes are referred to by symbolic names (see
    [`DETAIL_SIDEBAR_TEMPLATES`][oarepo_config.detail_sidebar.DETAIL_SIDEBAR_TEMPLATES]):
    `manage_menu`, `versions`, `external_resources`, `communities`,
    `keywords_subjects`, `details`, `locations`, `licenses`,
    `citations`, `export`, `technical_metadata`, `metrics` and `ark`
    (added by [`configure_ark`][oarepo_config.configure_ark]). A box
    registered via `templates` is referred to by its new name.

    The changes are applied to the current sidebar, in this order:
    `templates`, `order`, `move`, `remove`. Must be called *after*
    [`configure_ui`][oarepo_config.configure_ui] and any other `configure_*`
    function that adds a box (e.g. [`configure_ark`][oarepo_config.configure_ark]).
    Can be called multiple times.

    Args:
        templates: Box name -> template. An existing box gets the new
            template in place; a new box is appended at the end.
        order: The new order of the boxes. `"..."` stands for all the
            boxes not listed, in their current order; without it, the boxes
            not listed are removed.
        move: Moves applied one after another, each one of
            `"<box> before <box>"`, `"<box> after <box>"`,
            `"<box> first"` or `"<box> last"`.
        remove: Boxes to remove.
        model: Change only the sidebar of this model (the model name). Its
            sidebar starts as a copy of the global one.

    Invenio configuration variables set:

    * `APP_RDM_DETAIL_SIDE_BAR_TEMPLATES` - without `model`.
    * `OAREPO_UI_SIDEBAR_TEMPLATES[model]` - with `model`.
    * `_OAREPO_CONFIG_DETAIL_SIDEBAR_TEMPLATES` - internal: the boxes registered via
      `templates`, per sidebar (model name, `None` for the global one),
      so that later calls know their names.

    Example:
        ```python
        config.configure_ui(...)

        config.configure_detail_sidebar(
            templates={
                "locations": "datasets/record_detail/side_bar/locations.html",
                "licenses": "datarepo/records/details/side_bar/licenses.html",
            },
            move=["locations after details"],
        )
        ```

    """
    sidebar = get_constant_from_caller("APP_RDM_DETAIL_SIDE_BAR_TEMPLATES")
    if sidebar is None:
        raise ValueError(
            "APP_RDM_DETAIL_SIDE_BAR_TEMPLATES must be set, please configure UI before configuring the sidebar."
        )
    # names registered by earlier calls, per sidebar (None is the global one)
    registered = dict(get_constant_from_caller("_OAREPO_CONFIG_DETAIL_SIDEBAR_TEMPLATES", {}))
    model_sidebars = dict(get_constant_from_caller("OAREPO_UI_SIDEBAR_TEMPLATES", {}))
    known = registered.get(None, {})
    if model is not None and model in model_sidebars:
        sidebar = model_sidebars[model]
        known = registered.get(model, {})

    # known must not contain this call's templates yet: the current sidebar is named by the
    # earlier registrations, so that a re-registered box is replaced, not added twice
    sidebar = update_detail_sidebar(sidebar, known=known, templates=templates, order=order, move=move, remove=remove)
    registered[model] = {**known, **(templates or {})}

    constants: dict[str, object] = {"_OAREPO_CONFIG_DETAIL_SIDEBAR_TEMPLATES": registered}
    if model is None:
        constants["APP_RDM_DETAIL_SIDE_BAR_TEMPLATES"] = sidebar
    else:
        model_sidebars[model] = sidebar
        constants["OAREPO_UI_SIDEBAR_TEMPLATES"] = model_sidebars
    set_constants_in_caller(constants)

configure_einfra_oidc(entitlements_parser: EntitlementsParser | None = None) -> None

Set up "Log in with e-INFRA" (CESNET/Perun) for the repository.

Parameters:

Name Type Description Default
entitlements_parser EntitlementsParser | None

A callable that parses the user's entitlements.

None

This enables single sign-on through the CESNET e-INFRA identity provider, so users can log in with their e-INFRA/Perun account instead of (or in addition to) a local username and password. It also makes user profile information (name, e-mail, ...) read-only locally, since it is then managed by e-INFRA instead.

Requires the optional oarepo-oidc-einfra package to be installed - if it is missing, this function prints a message and stops the application from starting.

Whether e-INFRA login is actually turned on is controlled by the INVENIO_REMOTE_AUTH_ENABLED setting (true/yes/1 to enable it, anything else - including leaving it unset - disables it). When enabled, the client credentials INVENIO_EINFRA_CONSUMER_KEY and INVENIO_EINFRA_CONSUMER_SECRET must also be provided (see the deployment's variables/.env configuration).

Invenio configuration variables set:

  • OAUTHCLIENT_REMOTE_APPS - always updated (merged with any existing value); gets an "e-infra" entry only when e-INFRA login is enabled.
  • EINFRA - only when e-INFRA login is enabled; the e-INFRA client credentials and endpoint configuration.
  • USERPROFILES_READ_ONLY - only when e-INFRA login is enabled; forced to True.
Example
config.configure_einfra_oidc()

Make sure to set INVENIO_REMOTE_AUTH_ENABLED=true and provide INVENIO_EINFRA_CONSUMER_KEY and INVENIO_EINFRA_CONSUMER_SECRET in your deployment's variables or environment.

Source code in oarepo_config/einfra.py
def configure_einfra_oidc(entitlements_parser: EntitlementsParser | None = None) -> None:
    """Set up "Log in with e-INFRA" (CESNET/Perun) for the repository.

    Args:
        entitlements_parser: A callable that parses the user's entitlements.

    This enables single sign-on through the CESNET e-INFRA identity
    provider, so users can log in with their e-INFRA/Perun account
    instead of (or in addition to) a local username and password. It
    also makes user profile information (name, e-mail, ...) read-only
    locally, since it is then managed by e-INFRA instead.

    Requires the optional `oarepo-oidc-einfra` package to be
    installed - if it is missing, this function prints a message and
    stops the application from starting.

    Whether e-INFRA login is actually turned on is controlled by the
    `INVENIO_REMOTE_AUTH_ENABLED` setting (`true`/`yes`/`1` to
    enable it, anything else - including leaving it unset - disables
    it). When enabled, the client credentials
    `INVENIO_EINFRA_CONSUMER_KEY` and `INVENIO_EINFRA_CONSUMER_SECRET`
    must also be provided (see the deployment's `variables`/`.env`
    configuration).

    Invenio configuration variables set:

    * `OAUTHCLIENT_REMOTE_APPS` - always updated (merged with any
      existing value); gets an `"e-infra"` entry only when e-INFRA
      login is enabled.
    * `EINFRA` - only when e-INFRA login is enabled; the e-INFRA
      client credentials and endpoint configuration.
    * `USERPROFILES_READ_ONLY` - only when e-INFRA login is enabled;
      forced to `True`.

    Example:
        ```python
        config.configure_einfra_oidc()
        ```

    Make sure to set `INVENIO_REMOTE_AUTH_ENABLED=true` and provide
    `INVENIO_EINFRA_CONSUMER_KEY` and `INVENIO_EINFRA_CONSUMER_SECRET`
    in your deployment's `variables` or environment.

    """
    try:
        from oarepo_oidc_einfra import EINFRA_LOGIN_APP
        from oarepo_oidc_einfra import config as oarepo_einfra_config
    except ImportError:
        print("Please install oarepo-oidc-einfra to use E-INFRA OIDC login.")  # noqa: T201
        sys.exit(1)

    env = load_configuration_variables()
    if os.environ.get("INVENIO_REMOTE_AUTH_ENABLED", "no").lower() in (
        "true",
        "yes",
        "1",
    ):
        OAUTHCLIENT_REMOTE_APPS = merge_with_caller("OAUTHCLIENT_REMOTE_APPS", {"e-infra": EINFRA_LOGIN_APP})
        # needed for disconnect
        EINFRA = dict(
            consumer_key=env.INVENIO_EINFRA_CONSUMER_KEY,
            consumer_secret=env.INVENIO_EINFRA_CONSUMER_SECRET,
            **{
                k[len("EINFRA_") :].lower(): getattr(oarepo_einfra_config, k)
                for k in dir(oarepo_einfra_config)
                if k.startswith("EINFRA_")
            },
        )
        # do not allow users to change profile info, we take this from EINFRA
        USERPROFILES_READ_ONLY = True
    else:
        OAUTHCLIENT_REMOTE_APPS = merge_with_caller("OAUTHCLIENT_REMOTE_APPS", {})

    if entitlements_parser is not None:
        EINFRA_ENTITLEMENTS_PARSER = entitlements_parser

    set_constants_in_caller(locals())

configure_files(max_file_size: int = 1 * 10 ** 9, max_files_count: int = 100, max_total_size: int = 5 * 10 ** 9, allow_metadata_only_records: bool = True, allow_empty_files: bool | None = None, file_modification_grace_period: timedelta = timedelta(days=45), allow_immediate_file_modification: bool = True, allow_immediate_quota_increase: bool = True, max_additional_quota_size: int = 0, allow_archive_download: bool = True, max_archive_download_size: int | None = None) -> None

Set up file upload quotas and file-related toggles.

Controls how many files users may attach to a record deposition, how large each individual file may be, the total storage budget for the deposition, whether a deposition can be published without any files at all, and whether uploaded files may have zero bytes.

Parameters:

Name Type Description Default
max_file_size int

Maximum size of a single uploaded file in bytes. Defaults to 1 GB (1 * 10**9).

1 * 10 ** 9
max_files_count int

Maximum number of files allowed per record deposition. Defaults to 100.

100
max_total_size int

Maximum combined size of all files in a single record deposition, in bytes. Defaults to 5 GB (5 * 10**9).

5 * 10 ** 9
allow_metadata_only_records bool

When False, users must upload at least one file before they can publish a record deposition. When True (the default), metadata-only records are allowed.

True
allow_empty_files bool | None

When False, zero-byte files are rejected. When True, they are allowed. Defaults to the value of allow_metadata_only_records so that requiring files also prevents users from satisfying the requirement with an empty file.

None
file_modification_grace_period timedelta

Grace period after a record is published during which its files can still be modified without creating a new version. Checked at publish time. Defaults to 45 days (timedelta(days=45)).

timedelta(days=45)
allow_immediate_file_modification bool

When True (the default), record owners may unlock and edit their published files themselves within file_modification_grace_period, while admins and system processes may do so at any time. When False, the default Invenio policy (admin-only) is left in place.

True
allow_immediate_quota_increase bool

When True (the default), users may immediately raise a draft's storage quota from their additional allowance (this surfaces the "Manage storage" UI in the file uploader); admins may do so for any record. When False, immediate quota increases stay disabled.

True
max_additional_quota_size int

Additional quota users/admins may grant on top of the default record quota. Defaults to 0.

0
allow_archive_download bool

Whether all files of a record can be downloaded at once as a single ZIP archive ("Download all"). The archive is assembled on the fly by a web worker, which stays busy for the whole download. Defaults to True.

True
max_archive_download_size int | None

Largest total size of a record's files, in bytes, for which the "Download all" archive is still offered; larger records only offer per-file downloads. None (the default, same as upstream InvenioRDM) means no limit - set one if your repository accepts large files (Zenodo uses 300 MB, 300 * 10**6).

None

Invenio configuration variables set:

  • RDM_FILES_DEFAULT_MAX_FILE_SIZE - backend limit on the size of a single file.
  • RDM_FILES_DEFAULT_QUOTA_SIZE - backend limit on the total size of all files in a record deposition.
  • RDM_RECORDS_MAX_FILES_COUNT - backend limit on the number of files per record.
  • RDM_ALLOW_METADATA_ONLY_RECORDS - whether metadata-only records are allowed.
  • RECORDS_RESOURCES_ALLOW_EMPTY_FILES - whether zero-byte files may be uploaded.
  • RDM_FILE_MODIFICATION_PERIOD - time window after record creation during which modified files may be published.
  • RDM_IMMEDIATE_FILE_MODIFICATION_ENABLED - whether published files may be edited immediately; set to allow_immediate_file_modification.
  • RDM_IMMEDIATE_FILE_MODIFICATION_POLICIES - ordered list of policies deciding who may edit published files immediately (only set when allow_immediate_file_modification is True).
  • RDM_IMMEDIATE_QUOTA_INCREASE_ENABLED - whether users may immediately raise a draft's quota; set to allow_immediate_quota_increase.
  • RDM_IMMEDIATE_QUOTA_INCREASE_POLICIES - ordered list of policies deciding who may raise a draft's quota (only set when allow_immediate_quota_increase is True).
  • APP_RDM_DEPOSIT_FORM_QUOTA - deposit-form UI quota object with maxFiles and maxStorage.
  • FILES_REST_DEFAULT_MAX_FILE_SIZE and FILES_REST_DEFAULT_QUOTA_SIZE - fallback variables used by the lower-level file storage layer.
  • RDM_FILES_DEFAULT_MAX_ADDITIONAL_QUOTA_SIZE - the max_additional_quota_size above.
  • RDM_ARCHIVE_DOWNLOAD_ENABLED - whether the "Download all" archive is available.
  • RECORDS_RESOURCES_ARCHIVE_DOWNLOAD_MAX_SIZE - total size limit for the "Download all" archive.
Example
# Use the default file quotas and toggles. All parameters below
# match the helper's built-in defaults and are shown explicitly
# for reference; they can be omitted when calling the helper.
config.configure_files(
    max_file_size=1 * 10**9,
    max_files_count=100,
    max_total_size=5 * 10**9,
    allow_metadata_only_records=True,
)
Source code in oarepo_config/files.py
def configure_files(  # noqa: PLR0913, PLR0917
    max_file_size: int = 1 * 10**9,
    max_files_count: int = 100,
    max_total_size: int = 5 * 10**9,
    allow_metadata_only_records: bool = True,
    allow_empty_files: bool | None = None,
    file_modification_grace_period: timedelta = timedelta(days=45),
    allow_immediate_file_modification: bool = True,
    allow_immediate_quota_increase: bool = True,
    max_additional_quota_size: int = 0,
    allow_archive_download: bool = True,
    max_archive_download_size: int | None = None,
) -> None:
    """Set up file upload quotas and file-related toggles.

    Controls how many files users may attach to a record deposition, how
    large each individual file may be, the total storage budget for the
    deposition, whether a deposition can be published without any files
    at all, and whether uploaded files may have zero bytes.

    Args:
        max_file_size: Maximum size of a single uploaded file in bytes.
            Defaults to 1 GB (`1 * 10**9`).
        max_files_count: Maximum number of files allowed per record
            deposition. Defaults to `100`.
        max_total_size: Maximum combined size of all files in a single
            record deposition, in bytes. Defaults to 5 GB
            (`5 * 10**9`).
        allow_metadata_only_records: When `False`, users must upload
            at least one file before they can publish a record
            deposition. When `True` (the default), metadata-only
            records are allowed.
        allow_empty_files: When `False`, zero-byte files are rejected.
            When `True`, they are allowed. Defaults to the value of
            `allow_metadata_only_records` so that requiring files also
            prevents users from satisfying the requirement with an empty
            file.
        file_modification_grace_period: Grace period after a record is
            published during which its files can still be modified without
            creating a new version. Checked at publish time. Defaults to
            45 days (`timedelta(days=45)`).
        allow_immediate_file_modification: When `True` (the default),
            record owners may unlock and edit their published files
            themselves within `file_modification_grace_period`, while
            admins and system processes may do so at any time. When
            `False`, the default Invenio policy (admin-only) is left in
            place.
        allow_immediate_quota_increase: When `True` (the default), users
            may immediately raise a draft's storage quota from their
            additional allowance (this surfaces the "Manage storage" UI in
            the file uploader); admins may do so for any record. When
            `False`, immediate quota increases stay disabled.
        max_additional_quota_size: Additional quota users/admins may grant
            on top of the default record quota. Defaults to 0.
        allow_archive_download: Whether all files of a record can be
            downloaded at once as a single ZIP archive ("Download all").
            The archive is assembled on the fly by a web worker, which
            stays busy for the whole download. Defaults to `True`.
        max_archive_download_size: Largest total size of a record's files,
            in bytes, for which the "Download all" archive is still
            offered; larger records only offer per-file downloads. `None`
            (the default, same as upstream InvenioRDM) means no limit - set
            one if your repository accepts large files (Zenodo uses
            300 MB, `300 * 10**6`).

    Invenio configuration variables set:

    * `RDM_FILES_DEFAULT_MAX_FILE_SIZE` - backend limit on the size of
      a single file.
    * `RDM_FILES_DEFAULT_QUOTA_SIZE` - backend limit on the total size
      of all files in a record deposition.
    * `RDM_RECORDS_MAX_FILES_COUNT` - backend limit on the number of
      files per record.
    * `RDM_ALLOW_METADATA_ONLY_RECORDS` - whether metadata-only
      records are allowed.
    * `RECORDS_RESOURCES_ALLOW_EMPTY_FILES` - whether zero-byte files
      may be uploaded.
    * `RDM_FILE_MODIFICATION_PERIOD` - time window after record
      creation during which modified files may be published.
    * `RDM_IMMEDIATE_FILE_MODIFICATION_ENABLED` - whether published
      files may be edited immediately; set to
      `allow_immediate_file_modification`.
    * `RDM_IMMEDIATE_FILE_MODIFICATION_POLICIES` - ordered list of
      policies deciding who may edit published files immediately (only
      set when `allow_immediate_file_modification` is `True`).
    * `RDM_IMMEDIATE_QUOTA_INCREASE_ENABLED` - whether users may
      immediately raise a draft's quota; set to
      `allow_immediate_quota_increase`.
    * `RDM_IMMEDIATE_QUOTA_INCREASE_POLICIES` - ordered list of policies
      deciding who may raise a draft's quota (only set when
      `allow_immediate_quota_increase` is `True`).
    * `APP_RDM_DEPOSIT_FORM_QUOTA` - deposit-form UI quota object with
      `maxFiles` and `maxStorage`.
    * `FILES_REST_DEFAULT_MAX_FILE_SIZE` and
      `FILES_REST_DEFAULT_QUOTA_SIZE` - fallback variables used by
      the lower-level file storage layer.
    * `RDM_FILES_DEFAULT_MAX_ADDITIONAL_QUOTA_SIZE` - the
      `max_additional_quota_size` above.
    * `RDM_ARCHIVE_DOWNLOAD_ENABLED` - whether the "Download all"
      archive is available.
    * `RECORDS_RESOURCES_ARCHIVE_DOWNLOAD_MAX_SIZE` - total size limit
      for the "Download all" archive.

    Example:
        ```python
        # Use the default file quotas and toggles. All parameters below
        # match the helper's built-in defaults and are shown explicitly
        # for reference; they can be omitted when calling the helper.
        config.configure_files(
            max_file_size=1 * 10**9,
            max_files_count=100,
            max_total_size=5 * 10**9,
            allow_metadata_only_records=True,
        )
        ```

    """
    RDM_FILES_DEFAULT_MAX_FILE_SIZE = max_file_size
    FILES_REST_DEFAULT_MAX_FILE_SIZE = max_file_size

    RDM_FILES_DEFAULT_QUOTA_SIZE = max_total_size
    FILES_REST_DEFAULT_QUOTA_SIZE = max_total_size

    RDM_RECORDS_MAX_FILES_COUNT = max_files_count

    RDM_FILES_DEFAULT_MAX_ADDITIONAL_QUOTA_SIZE = max_additional_quota_size

    APP_RDM_DEPOSIT_FORM_QUOTA = {
        "maxFiles": max_files_count,
        "maxStorage": max_total_size,
    }

    RDM_ALLOW_METADATA_ONLY_RECORDS = allow_metadata_only_records
    RECORDS_RESOURCES_ALLOW_EMPTY_FILES = (
        allow_empty_files if allow_empty_files is not None else allow_metadata_only_records
    )

    RDM_ARCHIVE_DOWNLOAD_ENABLED = allow_archive_download
    RECORDS_RESOURCES_ARCHIVE_DOWNLOAD_MAX_SIZE = max_archive_download_size

    RDM_FILE_MODIFICATION_PERIOD = file_modification_grace_period

    RDM_IMMEDIATE_FILE_MODIFICATION_ENABLED = allow_immediate_file_modification
    if allow_immediate_file_modification:
        # Let record owners unlock/edit their published files themselves within
        # the grace period; admins/system may do so at any time. Policies are
        # evaluated in order, most to least specific.
        RDM_IMMEDIATE_FILE_MODIFICATION_POLICIES = [
            FileModificationGracePeriodPolicy(grace_period=file_modification_grace_period),
            FileModificationAdminPolicy(),
        ]

    RDM_IMMEDIATE_QUOTA_INCREASE_ENABLED = allow_immediate_quota_increase
    if allow_immediate_quota_increase:
        # Let users raise a draft's quota from their additional allowance
        # immediately (surfaces the "Manage storage" UI); admins for any record.
        RDM_IMMEDIATE_QUOTA_INCREASE_POLICIES = [
            QuotaIncreasePolicy(),
            QuotaIncreaseAdminPolicy(),
        ]

    set_constants_in_caller(locals())

configure_jobs(permission_policy: str | type | None = None, logging_level: str | None = None) -> None

Set up the "Jobs" feature (manually or automatically run administrative tasks).

Invenio-jobs lets administrators run and monitor maintenance tasks (such as re-indexing or fixing up data) from the admin panel, and view their logs. This decides who is allowed to view those job logs and how detailed the logs are.

Parameters:

Name Type Description Default
permission_policy str | type | None

Who is allowed to view job logs. By default, only administrators can. Pass your own permission policy class (or its import path as a string) to change this.

None
logging_level str | None

How detailed the job logs should be, e.g. "DEBUG", "INFO" (the default), "WARNING".

None

Invenio configuration variables set:

  • APP_LOGS_PERMISSION_POLICY - the permission_policy above.
  • JOBS_LOGGING_LEVEL - the logging_level above.
Example
config.configure_jobs()
# or with custom settings:
config.configure_jobs(
    permission_policy="my_package:policies:MyJobPolicy",
    logging_level="DEBUG",
)
Source code in oarepo_config/jobs.py
def configure_jobs(
    permission_policy: str | type | None = None,
    logging_level: str | None = None,
) -> None:
    """Set up the "Jobs" feature (manually or automatically run administrative tasks).

    Invenio-jobs lets administrators run and monitor maintenance tasks
    (such as re-indexing or fixing up data) from the admin panel, and
    view their logs. This decides who is allowed to view those job logs
    and how detailed the logs are.

    Args:
        permission_policy: Who is allowed to view job logs. By default,
            only administrators can. Pass your own permission policy
            class (or its import path as a string) to change this.
        logging_level: How detailed the job logs should be, e.g.
            `"DEBUG"`, `"INFO"` (the default), `"WARNING"`.

    Invenio configuration variables set:

    * `APP_LOGS_PERMISSION_POLICY` - the `permission_policy` above.
    * `JOBS_LOGGING_LEVEL` - the `logging_level` above.

    Example:
        ```python
        config.configure_jobs()
        # or with custom settings:
        config.configure_jobs(
            permission_policy="my_package:policies:MyJobPolicy",
            logging_level="DEBUG",
        )
        ```

    """
    from invenio_jobs.services.permissions import (
        JobLogsPermissionPolicy as InvenioJobLogsPermissionPolicy,
    )
    from oarepo_runtime.services.generators import AdministrationWithQueryFilter

    class JobLogsPermissionPolicy(InvenioJobLogsPermissionPolicy):
        """Permission policy for job logs."""

        can_read: tuple[Generator, ...] = (AdministrationWithQueryFilter(),)

    # invenio-jobs configuration
    APP_LOGS_PERMISSION_POLICY = obj_or_import_string(
        permission_policy,
        default=JobLogsPermissionPolicy,
    )
    JOBS_LOGGING_LEVEL = logging_level or "INFO"
    set_constants_in_caller(locals())

initialize_glitchtip(dsn: str | None = None, deployment_version: str | None = None) -> None

Set up automatic error reporting to Glitchtip/Sentry.

Requires the optional oarepo-glitchtip package; without it, calling this raises an ImportError explaining that the package needs to be installed first.

Parameters:

Name Type Description Default
dsn str | None

The Glitchtip/Sentry project URL (DSN) errors should be sent to.

None
deployment_version str | None

A label identifying this deployment (e.g. a git commit or release tag), included with reported errors so they can be traced back to a specific version.

None

Invenio configuration variables set: implemented entirely in the separate oarepo-glitchtip package, so the exact set of variables it writes is documented there, not here.

Source code in oarepo_config/__init__.py
def initialize_glitchtip(dsn: str | None = None, deployment_version: str | None = None) -> None:  # noqa: ARG001
    """Set up automatic error reporting to Glitchtip/Sentry.

    Requires the optional `oarepo-glitchtip` package; without it,
    calling this raises an `ImportError` explaining that the
    package needs to be installed first.

    Args:
        dsn: The Glitchtip/Sentry project URL (DSN) errors should be
            sent to.
        deployment_version: A label identifying this deployment
            (e.g. a git commit or release tag), included with
            reported errors so they can be traced back to a
            specific version.

    Invenio configuration variables set: implemented entirely in
    the separate `oarepo-glitchtip` package, so the exact set of
    variables it writes is documented there, not here.

    """
    raise ImportError("oarepo-glitchtip is not installed")

load_configuration_variables() -> DictWithGetAttr cached

Read the deployment's configuration values (INVENIO_... variables).

Collects configuration values set by the deployment, from multiple places, each one able to override the previous (lowest to highest priority):

  1. a variables file next to invenio.cfg (the instance directory);
  2. a variables file in the current working directory;
  3. a .env file in the current working directory;
  4. any .json/.yaml/.yml files under the directory named by the INVENIO_CONFIG_PATH environment variable, if set;
  5. the actual process environment variables (always wins).

Values such as "True"/"False" or JSON snippets are converted to real Python types (booleans, numbers, lists, dicts) where possible. The result can be accessed both as a dictionary and via attribute access (e.g. env.INVENIO_SECRET_KEY); accessing a variable that was never set raises AttributeError.

Source code in oarepo_config/base.py
@functools.lru_cache(maxsize=1)
def load_configuration_variables() -> DictWithGetAttr:
    """Read the deployment's configuration values (`INVENIO_...` variables).

    Collects configuration values set by the deployment, from multiple
    places, each one able to override the previous (lowest to highest
    priority):

    1. a `variables` file next to `invenio.cfg` (the instance
       directory);
    2. a `variables` file in the current working directory;
    3. a `.env` file in the current working directory;
    4. any `.json`/`.yaml`/`.yml` files under the directory named
       by the `INVENIO_CONFIG_PATH` environment variable, if set;
    5. the actual process environment variables (always wins).

    Values such as `"True"`/`"False"` or JSON snippets are converted
    to real Python types (booleans, numbers, lists, dicts) where
    possible. The result can be accessed both as a dictionary and via
    attribute access (e.g. `env.INVENIO_SECRET_KEY`); accessing a
    variable that was never set raises `AttributeError`.
    """
    env = Config(Path(__file__).parent)
    # lowest priority are variables
    bundled_env = Path(get_invenio_cfg_path()).parent / "variables"
    if bundled_env.exists():
        vals = dotenv_values(str(bundled_env))
        env.from_mapping(vals)

    env.update(load_configuration_overrides())

    # transform values from strings to their actual types
    for k, v in list(env.items()):
        env[k] = transform_value(v)
        setattr(env, k, transform_value(v))

    return DictWithGetAttr(**env)

override_configuration(env: dict[str, Any] | None = None) -> None

Apply ad-hoc configuration overrides from the environment, without writing Python code.

Lets a deployment set (or override) any Invenio configuration value directly from the variables/.env files or the process environment, by prefixing its name with INVENIO_. For example, setting INVENIO_RDM_ARCHIVE_DOWNLOAD_ENABLED=false in the deployment's configuration will set the RDM_ARCHIVE_DOWNLOAD_ENABLED setting to False, without needing to change invenio.cfg.

This is not applied automatically - call it explicitly from invenio.cfg, typically as the very last step, so that these overrides win over anything set by the configure_*() functions above it.

Parameters:

Name Type Description Default
env dict[str, Any] | None

Normally left unset, in which case the values loaded from variables/.env/the process environment are used.

None
Source code in oarepo_config/base.py
def override_configuration(env: dict[str, Any] | None = None) -> None:
    """Apply ad-hoc configuration overrides from the environment, without writing Python code.

    Lets a deployment set (or override) any Invenio configuration value
    directly from the `variables`/`.env` files or the process
    environment, by prefixing its name with `INVENIO_`. For example,
    setting `INVENIO_RDM_ARCHIVE_DOWNLOAD_ENABLED=false` in the
    deployment's configuration will set the `RDM_ARCHIVE_DOWNLOAD_ENABLED`
    setting to `False`, without needing to change `invenio.cfg`.

    This is not applied automatically - call it explicitly from
    `invenio.cfg`, typically as the very last step, so that these
    overrides win over anything set by the `configure_*()` functions
    above it.

    Args:
        env: Normally left unset, in which case the values loaded from
            `variables`/`.env`/the process environment are used.

    """
    if env is None:
        env = load_configuration_overrides()
    constants_to_override: dict[str, Any] = {}
    for key, v in env.items():
        if key.startswith("INVENIO_"):
            key_suffix = key[8:]
            constants_to_override[key_suffix] = v
    set_constants_in_caller(constants_to_override)

configure_collections(communities_collections_enabled: bool = True, max_depth: int = 2) -> None

Configure collections feature.

Collections and are curated, browsable subsets of a community's records. They are saved searches. Each collection stores a search query, and its records are whatever that query matches. A record is never added to a collection by hand.

Source code in oarepo_config/collections.py
def configure_collections(
    communities_collections_enabled: bool = True,
    max_depth: int = 2,
) -> None:
    """Configure collections feature.

    Collections and are curated, browsable subsets of a community's records.
    They are saved searches. Each collection stores a search query, and its records are whatever that query matches.
    A record is never added to a collection by hand.
    """
    COMMUNITIES_COLLECTIONS_ENABLED = communities_collections_enabled
    COLLECTIONS_MAX_DEPTH = max_depth
    set_constants_in_caller(locals())

configure_communities(communities_roles: list | None = None) -> None

Set up the configuration for communities.

Communities let you organize records into collections with their own managers and settings. This function configures who can do what in each community (the roles), how records are submitted to communities, and other community-related settings.

Parameters:

Name Type Description Default
communities_roles list | None

Custom role definitions for communities. If not provided, defaults to owner/curator/member roles. If omitted, three default roles are used: "owner" (can manage the community and its members), "curator" (can review/curate submitted records) and "member" (can only view). Pass your own list to replace the defaults, e.g. to add a "submitter" role. Each role dictionary understands the keys name, title, description, is_owner, can_manage, can_curate and can_manage_roles (the names of the roles this role is allowed to add/remove).

None

Invenio configuration variables set:

  • COMMUNITIES_REGISTER_UI_BLUEPRINT - always True; enables the communities UI.
  • COMMUNITIES_PERMISSION_POLICY - the permission policy class for communities.
  • COMMUNITIES_ROLES - the list of available roles in communities.
Example
config.configure_communities()
# or with custom settings:

config.configure_communities(
    communities_roles=[
        dict(
            name="owner",
            title=_("Community owner"),
            is_owner=True,
            can_manage=True,
            can_manage_roles=[
                "owner",
                "curator",
                "member",
                "submitter",
            ],
        ),
        dict(
            name="curator",
            title=_("Curator"),
            can_manage=True,
            can_manage_roles=[
                "member",
                "submitter",
            ],
        ),
        dict(
            name="submitter",
            title=_("Submitter"),
            can_manage=False,
        ),
        dict(
            name="member",
            title=_("Member"),
        ),
    ]
)
Source code in oarepo_config/communities.py
def configure_communities(
    communities_roles: list | None = None,
) -> None:
    """Set up the configuration for communities.

    Communities let you organize records into collections with their own
    managers and settings. This function configures who can do what in
    each community (the roles), how records are submitted to communities,
    and other community-related settings.

    Args:
        communities_roles: Custom role definitions for communities. If not
            provided, defaults to owner/curator/member roles. If omitted, three
            default roles are used: "owner" (can manage the community
            and its members), "curator" (can review/curate submitted
            records) and "member" (can only view). Pass your own list to
            replace the defaults, e.g. to add a "submitter" role. Each
            role dictionary understands the keys `name`, `title`,
            `description`, `is_owner`, `can_manage`,
            `can_curate` and `can_manage_roles` (the names of the
            roles this role is allowed to add/remove).

    Invenio configuration variables set:

    * `COMMUNITIES_REGISTER_UI_BLUEPRINT` - always `True`; enables
      the communities UI.
    * `COMMUNITIES_PERMISSION_POLICY` - the permission policy class for
      communities.
    * `COMMUNITIES_ROLES` - the list of available roles in communities.

    Example:
        ```python
        config.configure_communities()
        # or with custom settings:

        config.configure_communities(
            communities_roles=[
                dict(
                    name="owner",
                    title=_("Community owner"),
                    is_owner=True,
                    can_manage=True,
                    can_manage_roles=[
                        "owner",
                        "curator",
                        "member",
                        "submitter",
                    ],
                ),
                dict(
                    name="curator",
                    title=_("Curator"),
                    can_manage=True,
                    can_manage_roles=[
                        "member",
                        "submitter",
                    ],
                ),
                dict(
                    name="submitter",
                    title=_("Submitter"),
                    can_manage=False,
                ),
                dict(
                    name="member",
                    title=_("Member"),
                ),
            ]
        )
        ```

    """
    COMMUNITIES_REGISTER_UI_BLUEPRINT = True
    COMMUNITIES_PERMISSION_POLICY = DefaultCommunitiesPermissionPolicy
    COMMUNITIES_ROLES = communities_roles or [
        # note: order matters, roles should be sorted by importance
        # from the most important to the least
        {
            "name": "owner",
            "title": _("Community owner"),
            "description": _("Can manage community."),
            "is_owner": True,
            "can_manage": True,
            "can_manage_roles": ["owner", "curator", "member"],
        },
        {
            "name": "curator",
            "title": _("Curator"),
            "description": _("Can curate records."),
            "can_manage": True,
            "can_manage_roles": ["member"],
        },
        {
            "name": "member",
            "title": _("Member"),
            "description": _("Community member with read permissions."),
        },
    ]

    set_constants_in_caller(locals())

configure_cron(file_integrity_check_days: int | None = None, **extra_cron_items: Any) -> None

Set up the periodic (scheduled) background tasks the repository needs.

The repository relies on a number of jobs that must run automatically in the background on a regular basis - for example, cleaning up old sessions, aggregating usage statistics, or clearing caches. This function sets up a sensible set of such jobs out of the box:

  • keeping the search index queues healthy (every 10 seconds)
  • cleaning up expired user sessions and old IP address logs
  • processing and aggregating usage statistics (hourly)
  • clearing the communities cache (daily)
  • removing expired file-access-request tokens (daily)
  • lifting expired embargoes (daily)
  • expiring requests past their expiration date, e.g. community invitations (daily)
  • purging drafts that were discarded more than an hour ago (hourly)
  • deleting job logs older than JOBS_LOGGING_RETENTION_DAYS (daily)
  • refreshing the sitemap (daily)
  • updating the statistics of user e-mail domains (every 4 hours)
  • recounting community collections (hourly) - only if COMMUNITIES_COLLECTIONS_ENABLED was set to True earlier in invenio.cfg

Compared to upstream InvenioRDM, reindex-stats is left out on purpose: OARepo models do not index usage statistics into the record documents, so there is nothing to refresh.

Parameters:

Name Type Description Default
file_integrity_check_days int | None

Turns on periodic fixity checking: every stored file gets its checksum re-computed once per this many days (spread evenly over hourly batches), and a daily e-mail reports the files that are missing or corrupted to APP_RDM_ADMIN_EMAIL_RECIPIENT (INVENIO_APP_RDM_ADMIN_EMAIL_RECIPIENT in the environment). Off (None) by default, because it reads every file back from the storage - on an S3 deployment make sure that this traffic is acceptable, and that the checksums of multipart uploads can be verified, before enabling it. Upstream InvenioRDM uses 14 days, Zenodo 180.

None
**extra_cron_items Any

Additional scheduled jobs to add (or to override, if the name matches one of the built-in jobs above), one keyword per job. Each value follows Celery's "beat schedule" format, e.g.:

config.configure_cron(
    my_job={
        "task": "my_package.tasks.my_task",
        "schedule": timedelta(
            minutes=30
        ),
    },
)
{}

Invenio configuration variables set:

  • CELERY_BEAT_SCHEDULE - merged with any schedule already defined earlier in invenio.cfg; entries from **extra_cron_items win over the built-in defaults listed above when their names collide.
Source code in oarepo_config/cron.py
def configure_cron(file_integrity_check_days: int | None = None, **extra_cron_items: Any) -> None:
    """Set up the periodic (scheduled) background tasks the repository needs.

    The repository relies on a number of jobs that must run automatically
    in the background on a regular basis - for example, cleaning up old
    sessions, aggregating usage statistics, or clearing caches. This
    function sets up a sensible set of such jobs out of the box:

    * keeping the search index queues healthy (every 10 seconds)
    * cleaning up expired user sessions and old IP address logs
    * processing and aggregating usage statistics (hourly)
    * clearing the communities cache (daily)
    * removing expired file-access-request tokens (daily)
    * lifting expired embargoes (daily)
    * expiring requests past their expiration date, e.g. community
      invitations (daily)
    * purging drafts that were discarded more than an hour ago (hourly)
    * deleting job logs older than `JOBS_LOGGING_RETENTION_DAYS` (daily)
    * refreshing the sitemap (daily)
    * updating the statistics of user e-mail domains (every 4 hours)
    * recounting community collections (hourly) - only if
      `COMMUNITIES_COLLECTIONS_ENABLED` was set to `True` earlier in
      `invenio.cfg`

    Compared to upstream InvenioRDM, `reindex-stats` is left out on
    purpose: OARepo models do not index usage statistics into the record
    documents, so there is nothing to refresh.

    Args:
        file_integrity_check_days: Turns on periodic fixity checking: every
            stored file gets its checksum re-computed once per this many
            days (spread evenly over hourly batches), and a daily e-mail
            reports the files that are missing or corrupted to
            `APP_RDM_ADMIN_EMAIL_RECIPIENT`
            (`INVENIO_APP_RDM_ADMIN_EMAIL_RECIPIENT` in the environment).
            Off (`None`) by default, because it reads every file back from
            the storage - on an S3 deployment make sure that this traffic
            is acceptable, and that the checksums of multipart uploads can
            be verified, before enabling it. Upstream InvenioRDM uses 14
            days, Zenodo 180.
        **extra_cron_items: Additional scheduled jobs to add (or to
            override, if the name matches one of the built-in jobs
            above), one keyword per job. Each value follows Celery's
            "beat schedule" format, e.g.:

            ```python
            config.configure_cron(
                my_job={
                    "task": "my_package.tasks.my_task",
                    "schedule": timedelta(
                        minutes=30
                    ),
                },
            )
            ```

    Invenio configuration variables set:

    * `CELERY_BEAT_SCHEDULE` - merged with any schedule already
      defined earlier in `invenio.cfg`; entries from
      `**extra_cron_items` win over the built-in defaults listed
      above when their names collide.

    """
    collections_enabled = bool(get_constant_from_caller("COMMUNITIES_COLLECTIONS_ENABLED", default=False))

    CELERY_BEAT_SCHEDULE = merge_with_caller(
        "CELERY_BEAT_SCHEDULE",
        {
            "indexer": {
                "task": "invenio_records_resources.tasks.manage_indexer_queues",
                "schedule": timedelta(seconds=10),
            },
            "accounts_sessions": {
                "task": "invenio_accounts.tasks.clean_session_table",
                "schedule": timedelta(minutes=60),
            },
            "accounts_ips": {
                "task": "invenio_accounts.tasks.delete_ips",
                "schedule": timedelta(hours=6),
            },
            # indexing of statistics events & aggregations
            "stats-process-events": {
                **StatsEventTask,
                "schedule": crontab(minute="25,55"),  # Every hour at minute 25 and 55
            },
            "stats-aggregate-events": {
                **StatsAggregationTask,
                "schedule": crontab(minute="0"),  # Every hour at minute 0
            },
            # "reindex-stats" (StatsRDMReindexTask) is intentionally not scheduled:
            # OARepo models do not index usage statistics into record documents.
            # Invenio communities provides some caching that has the potential to be never removed,
            # therefore, we need a cronjob to ensure that at least once per day we clear the cache
            "clear-cache": {
                "task": "invenio_communities.tasks.clear_cache",
                "schedule": crontab(minute="0", hour="1"),  # Every day at 01:00 UTC
            },
            "clean-access-request-tokens": {
                "task": "invenio_rdm_records.requests.access.tasks.clean_expired_request_access_tokens",
                "schedule": crontab(minute="4", hour="0"),
            },
            "lift_embargos": {
                "task": "invenio_rdm_records.services.tasks.update_expired_embargos",
                "schedule": crontab(minute=0, hour=0),
            },
            "expire_requests": {
                "task": "invenio_requests.tasks.check_expired_requests",
                "schedule": crontab(minute=3, hour=0),
            },
            # hard-delete drafts that were discarded (soft-deleted) more than an hour ago
            "draft_resources": {
                "task": "invenio_drafts_resources.services.records.tasks.cleanup_drafts",
                "schedule": timedelta(minutes=60),
            },
            "delete-job-logs": {
                "task": "invenio_jobs.logging.tasks.delete_logs",
                "schedule": crontab(minute=5, hour=0),
            },
            "update_sitemap": {
                "task": "invenio_sitemap.tasks.update_sitemap_cache",
                "schedule": crontab(minute=0, hour=2),
            },
            "update_domain_status": {
                "task": "invenio_accounts.tasks.update_domain_status",
                "schedule": timedelta(hours=4),
            },
            **_collections_cron_items(collections_enabled),
            **_file_integrity_cron_items(file_integrity_check_days),
            **extra_cron_items,
        },
    )

    set_constants_in_caller(locals())

configure_generic_parameters(languages: tuple[tuple[str, str], ...] = (('en', 'English'),), use_path_pid_ids: bool = False) -> None

Set up the core, infrastructure-level configuration of the repository.

This is the main "plumbing" function that should normally be called first, before any of the other configure_* functions. It reads most of its values from the deployment's environment configuration (the variables/.env files or process environment variables, all prefixed with INVENIO_) and uses them to configure:

  • the site's public URLs, and allowed security headers
  • whether local login/registration/password-reset is available
  • the database, search engine (OpenSearch), file storage (S3), cache and message queue (Redis/RabbitMQ) connections
  • translation/locale and file-upload defaults
  • default identifier schemes recognised for names, funders and affiliations (e.g. ORCID, ROR, VEDIDK, Scopus author ID)

  • the InvenioRDM security defaults that upstream ships in invenio_app_rdm.config and that only make sense for a deployed repository (CSRF protection, shared rate limiting, database pool options, permission cache) - see "InvenioRDM flavour defaults" below

Because most values come from the environment, this function will fail to start the application if a required INVENIO_... variable is missing from the deployment's configuration - see the project's README for the full list of variables it expects.

Parameters:

Name Type Description Default
languages tuple[tuple[str, str], ...]

Extra UI languages to offer, as a tuple of (language_code, label) pairs, e.g. (("cs", _("Czech")), ("de", _("German"))). English is always available and does not need to be listed.

(('en', 'English'),)
use_path_pid_ids bool

Set this to True only if your repository uses record identifiers that themselves contain a slash (/); it adjusts the URLs used for managing record access so that such identifiers keep working.

False

Invenio configuration variables set, grouped by area:

Public URLs & security headers * TRUSTED_HOSTS * SITE_UI_URL, SITE_API_URL * APP_DEFAULT_SECURE_HEADERS

Local login & accounts * ACCOUNTS_LOCAL_LOGIN_ENABLED, SECURITY_REGISTERABLE, SECURITY_RECOVERABLE, SECURITY_CHANGEABLE, SECURITY_CONFIRMABLE, SECURITY_LOGIN_WITHOUT_CONFIRMATION * SESSION_COOKIE_SECURE * RATELIMIT_GUEST_USER, RATELIMIT_AUTHENTICATED_USER * OAUTHCLIENT_REMOTE_APPS - starts out empty here; extended by configure_einfra_oidc if used. * ACCOUNTS_LOGIN_VIEW_FUNCTION, OAUTHCLIENT_AUTO_REDIRECT_TO_EXTERNAL_LOGIN

Database * SQLALCHEMY_DATABASE_URI

Translation/locale * BABEL_DEFAULT_LOCALE, BABEL_DEFAULT_TIMEZONE, I18N_LANGUAGES

Files & storage * SEND_FILE_MAX_AGE_DEFAULT, FILES_REST_STORAGE_FACTORY * S3_ENDPOINT_URL, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY * FILES_REST_STORAGE_CLASS_LIST, FILES_REST_DEFAULT_STORAGE_CLASS, FILES_REST_DEFAULT_QUOTA_SIZE * APP_RDM_DEPOSIT_FORM_QUOTA

User profiles * USERPROFILES_READ_ONLY

OAI-PMH * OAISERVER_ID_PREFIX

Search (OpenSearch) * SEARCH_INDEX_PREFIX, SEARCH_HOSTS, SEARCH_CLIENT_CONFIG - set INVENIO_OPENSEARCH_TIMEOUT (seconds) to raise the search request timeout. * VOCABULARIES_SERVICE_CONFIG, VOCABULARIES_RESOURCE_CONFIG - only if the optional oarepo_vocabularies package is installed.

Caches (Redis) * INVENIO_CACHE_TYPE, CACHE_REDIS_URL, ACCOUNTS_SESSION_REDIS_URL, COMMUNITIES_IDENTITIES_CACHE_REDIS_URL

Background jobs (Celery/RabbitMQ) * CELERY_BROKER_URL, BROKER_URL, CELERY_RESULT_BACKEND

JSON schemas * RECORDS_REFRESOLVER_CLS, RECORDS_REFRESOLVER_STORE, JSONSCHEMAS_HOST

Secrets * SECRET_KEY

Records/REST compatibility * DASHBOARD_RECORD_CREATE_URL, RECORD_ROUTES, RECORDS_REST_ENDPOINTS

DataCite/DOIs * DATACITE_TEST_MODE

Mail * MAIL_DEFAULT_SENDER * MAIL_SUPPRESS_SEND - only if INVENIO_MAIL_SUPPRESS_SEND is set in the environment.

Identifier/name/funder/affiliation vocabularies * VOCABULARIES_NAMES_SCHEMES, VOCABULARIES_FUNDER_SCHEMES, VOCABULARIES_AFFILIATION_SCHEMES - merged with any existing value. * APP_RDM_IDENTIFIER_SCHEMES_UI * VOCABULARIES_DATASTREAM_READERS, VOCABULARIES_DATASTREAM_WRITERS, VOCABULARIES_DATASTREAM_TRANSFORMERS - seeded from invenio-app-rdm's defaults, merged with any existing value; see configure_datastreams to add your own.

Miscellaneous * ROR_CLIENT_ID, SESSION_COOKIE_DOMAIN, COLLECT_STORAGE

InvenioRDM flavour defaults Upstream InvenioRDM applies these through invenio_app_rdm.config, which OARepo does not load. The inert ones are defaults of every OARepo application (see oarepo.initial_rdm_config and oarepo_rdm.initial_config); the ones below switch on enforcement or depend on the deployment, so they are applied here. Each of them can be overridden by a plain assignment later in invenio.cfg.

* `REST_CSRF_ENABLED` - CSRF protection of the REST API for
  browser-session requests (API-token requests are exempt).
* `ACCESS_CACHE` - caches resolved action permissions.
* `RATELIMIT_STORAGE_URI` - rate limiting counters shared by
  all web processes in Redis instead of per-process memory.
  Taken from `INVENIO_RATELIMIT_STORAGE_URI`, or built from the
  Redis connection and `INVENIO_REDIS_RATELIMIT_DB` (default
  `4`).
* `ACCOUNTS_LOGIN_RATELIMIT`,
  `ACCOUNTS_FORGOT_PASSWORD_EMAIL_RATELIMIT`,
  `ACCOUNTS_SEND_CONFIRMATION_RATELIMIT`
* `SQLALCHEMY_ENGINE_OPTIONS` - connection pool recycling and
  timeout, UTC session time zone, host name as the connection's
  `application_name`. `INVENIO_PGBOUNCER_ENABLED=True` disables
  pooling in the application; `INVENIO_SQLALCHEMY_ENGINE_OPTIONS`
  (a JSON object) is merged over the result.
* `APP_RDM_ADMIN_EMAIL_RECIPIENT` - recipient of the file
  integrity report, from
  `INVENIO_APP_RDM_ADMIN_EMAIL_RECIPIENT`.

In addition, if use_path_pid_ids is True, this patches the url_prefix of RDMParentRecordLinksResourceConfig, RDMParentGrantsResourceConfig, RDMGrantUserAccessResourceConfig and RDMGrantGroupAccessResourceConfig directly - this is a class attribute change, not a new invenio.cfg variable.

Example
config.configure_generic_parameters(
    languages=(
        ("cs", _("Czech")),
        ("de", _("German")),
    ),
)
Source code in oarepo_config/generic_parameters.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
def configure_generic_parameters(  # noqa PLR0915
    languages: tuple[tuple[str, str], ...] = (("en", "English"),),
    use_path_pid_ids: bool = False,
) -> None:
    """Set up the core, infrastructure-level configuration of the repository.

    This is the main "plumbing" function that should normally be called
    first, before any of the other `configure_*` functions. It reads
    most of its values from the deployment's environment configuration
    (the `variables`/`.env` files or process environment variables,
    all prefixed with `INVENIO_`) and uses them to configure:

    * the site's public URLs, and allowed security headers
    * whether local login/registration/password-reset is available
    * the database, search engine (OpenSearch), file storage (S3),
      cache and message queue (Redis/RabbitMQ) connections
    * translation/locale and file-upload defaults
    * default identifier schemes recognised for names, funders and
      affiliations (e.g. ORCID, ROR, VEDIDK, Scopus author ID)

    * the InvenioRDM security defaults that upstream ships in
      `invenio_app_rdm.config` and that only make sense for a deployed
      repository (CSRF protection, shared rate limiting, database pool
      options, permission cache) - see "InvenioRDM flavour defaults"
      below

    Because most values come from the environment, this function will
    fail to start the application if a required `INVENIO_...` variable
    is missing from the deployment's configuration - see the project's
    README for the full list of variables it expects.

    Args:
        languages: Extra UI languages to offer, as a tuple of
            `(language_code, label)` pairs, e.g.
            `(("cs", _("Czech")), ("de", _("German")))`. English is
            always available and does not need to be listed.
        use_path_pid_ids: Set this to `True` only if your repository
            uses record identifiers that themselves contain a slash
            (`/`); it adjusts the URLs used for managing record access
            so that such identifiers keep working.

    Invenio configuration variables set, grouped by area:

    Public URLs & security headers
        * `TRUSTED_HOSTS`
        * `SITE_UI_URL`, `SITE_API_URL`
        * `APP_DEFAULT_SECURE_HEADERS`

    Local login & accounts
        * `ACCOUNTS_LOCAL_LOGIN_ENABLED`, `SECURITY_REGISTERABLE`,
          `SECURITY_RECOVERABLE`, `SECURITY_CHANGEABLE`,
          `SECURITY_CONFIRMABLE`,
          `SECURITY_LOGIN_WITHOUT_CONFIRMATION`
        * `SESSION_COOKIE_SECURE`
        * `RATELIMIT_GUEST_USER`, `RATELIMIT_AUTHENTICATED_USER`
        * `OAUTHCLIENT_REMOTE_APPS` - starts out empty here; extended
          by [`configure_einfra_oidc`][oarepo_config.configure_einfra_oidc] if used.
        * `ACCOUNTS_LOGIN_VIEW_FUNCTION`,
          `OAUTHCLIENT_AUTO_REDIRECT_TO_EXTERNAL_LOGIN`

    Database
        * `SQLALCHEMY_DATABASE_URI`

    Translation/locale
        * `BABEL_DEFAULT_LOCALE`, `BABEL_DEFAULT_TIMEZONE`,
          `I18N_LANGUAGES`

    Files & storage
        * `SEND_FILE_MAX_AGE_DEFAULT`, `FILES_REST_STORAGE_FACTORY`
        * `S3_ENDPOINT_URL`, `S3_ACCESS_KEY_ID`,
          `S3_SECRET_ACCESS_KEY`
        * `FILES_REST_STORAGE_CLASS_LIST`,
          `FILES_REST_DEFAULT_STORAGE_CLASS`,
          `FILES_REST_DEFAULT_QUOTA_SIZE`
        * `APP_RDM_DEPOSIT_FORM_QUOTA`

    User profiles
        * `USERPROFILES_READ_ONLY`

    OAI-PMH
        * `OAISERVER_ID_PREFIX`

    Search (OpenSearch)
        * `SEARCH_INDEX_PREFIX`, `SEARCH_HOSTS`,
          `SEARCH_CLIENT_CONFIG` - set `INVENIO_OPENSEARCH_TIMEOUT`
          (seconds) to raise the search request timeout.
        * `VOCABULARIES_SERVICE_CONFIG`,
          `VOCABULARIES_RESOURCE_CONFIG` - only if the optional
          `oarepo_vocabularies` package is installed.

    Caches (Redis)
        * `INVENIO_CACHE_TYPE`, `CACHE_REDIS_URL`,
          `ACCOUNTS_SESSION_REDIS_URL`,
          `COMMUNITIES_IDENTITIES_CACHE_REDIS_URL`

    Background jobs (Celery/RabbitMQ)
        * `CELERY_BROKER_URL`, `BROKER_URL`,
          `CELERY_RESULT_BACKEND`

    JSON schemas
        * `RECORDS_REFRESOLVER_CLS`, `RECORDS_REFRESOLVER_STORE`,
          `JSONSCHEMAS_HOST`

    Secrets
        * `SECRET_KEY`

    Records/REST compatibility
        * `DASHBOARD_RECORD_CREATE_URL`, `RECORD_ROUTES`,
          `RECORDS_REST_ENDPOINTS`

    DataCite/DOIs
        * `DATACITE_TEST_MODE`

    Mail
        * `MAIL_DEFAULT_SENDER`
        * `MAIL_SUPPRESS_SEND` - only if `INVENIO_MAIL_SUPPRESS_SEND`
          is set in the environment.

    Identifier/name/funder/affiliation vocabularies
        * `VOCABULARIES_NAMES_SCHEMES`, `VOCABULARIES_FUNDER_SCHEMES`,
          `VOCABULARIES_AFFILIATION_SCHEMES` - merged with any
          existing value.
        * `APP_RDM_IDENTIFIER_SCHEMES_UI`
        * `VOCABULARIES_DATASTREAM_READERS`,
          `VOCABULARIES_DATASTREAM_WRITERS`,
          `VOCABULARIES_DATASTREAM_TRANSFORMERS` - seeded from
          `invenio-app-rdm`'s defaults, merged with any existing
          value; see [`configure_datastreams`][oarepo_config.configure_datastreams] to add your own.

    Miscellaneous
        * `ROR_CLIENT_ID`, `SESSION_COOKIE_DOMAIN`,
          `COLLECT_STORAGE`

    InvenioRDM flavour defaults
        Upstream InvenioRDM applies these through
        `invenio_app_rdm.config`, which OARepo does not load. The inert
        ones are defaults of every OARepo application (see
        `oarepo.initial_rdm_config` and `oarepo_rdm.initial_config`);
        the ones below switch on enforcement or depend on the
        deployment, so they are applied here. Each of them can be
        overridden by a plain assignment later in `invenio.cfg`.

        * `REST_CSRF_ENABLED` - CSRF protection of the REST API for
          browser-session requests (API-token requests are exempt).
        * `ACCESS_CACHE` - caches resolved action permissions.
        * `RATELIMIT_STORAGE_URI` - rate limiting counters shared by
          all web processes in Redis instead of per-process memory.
          Taken from `INVENIO_RATELIMIT_STORAGE_URI`, or built from the
          Redis connection and `INVENIO_REDIS_RATELIMIT_DB` (default
          `4`).
        * `ACCOUNTS_LOGIN_RATELIMIT`,
          `ACCOUNTS_FORGOT_PASSWORD_EMAIL_RATELIMIT`,
          `ACCOUNTS_SEND_CONFIRMATION_RATELIMIT`
        * `SQLALCHEMY_ENGINE_OPTIONS` - connection pool recycling and
          timeout, UTC session time zone, host name as the connection's
          `application_name`. `INVENIO_PGBOUNCER_ENABLED=True` disables
          pooling in the application; `INVENIO_SQLALCHEMY_ENGINE_OPTIONS`
          (a JSON object) is merged over the result.
        * `APP_RDM_ADMIN_EMAIL_RECIPIENT` - recipient of the file
          integrity report, from
          `INVENIO_APP_RDM_ADMIN_EMAIL_RECIPIENT`.

    In addition, if `use_path_pid_ids` is `True`, this patches the
    `url_prefix` of `RDMParentRecordLinksResourceConfig`,
    `RDMParentGrantsResourceConfig`, `RDMGrantUserAccessResourceConfig`
    and `RDMGrantGroupAccessResourceConfig` directly - this is a class
    attribute change, not a new `invenio.cfg` variable.

    Example:
        ```python
        config.configure_generic_parameters(
            languages=(
                ("cs", _("Czech")),
                ("de", _("German")),
            ),
        )
        ```

    """
    # see https://inveniordm.docs.cern.ch/install/configuration/ for the meaning
    # of the variables here

    env = load_configuration_variables()
    configure_global_logging()

    # generic
    trusted_hosts = env.get("INVENIO_TRUSTED_HOSTS", None)
    if isinstance(trusted_hosts, str):
        trusted_hosts = ast.literal_eval(trusted_hosts)
    TRUSTED_HOSTS = trusted_hosts or ["0.0.0.0", "localhost", "127.0.0.1"]  # noqa S104
    SITE_UI_URL = env.get("INVENIO_SITE_UI_URL", None) or f"https://{env.INVENIO_UI_HOST}:{env.INVENIO_UI_PORT}"
    SITE_API_URL = env.get("INVENIO_SITE_API_URL", None) or f"https://{env.INVENIO_API_HOST}:{env.INVENIO_API_PORT}/api"

    # security
    APP_DEFAULT_SECURE_HEADERS: dict[str, Any] = {
        "content_security_policy": {
            "default-src": [
                "'self'",
                "fonts.googleapis.com",  # for fonts
                "*.gstatic.com",  # for fonts
                "data:",  # for fonts
                "'unsafe-inline'",  # for inline scripts and styles
                "blob:",  # for pdf preview
                # Add your own policies here (e.g. analytics)
            ],
            "script-src": [
                "'self'",
                "blob:",
                "'wasm-unsafe-eval'",  # for WASM-based workers and file uploads
                # Multipart file uploads use a Web Worker running `hash-wasm` to compute content checksums
                # (e.g., MD5) of uploaded parts. This requires both 'blob:' and 'wasm-unsafe-eval'
                # enabled in `script-src`.
            ],
        },
        "content_security_policy_report_only": False,
        "content_security_policy_report_uri": None,
        "force_file_save": False,
        "force_https": True,
        "force_https_permanent": False,
        "frame_options": "sameorigin",
        "frame_options_allow_from": None,
        "session_cookie_http_only": True,
        "session_cookie_secure": True,
        "strict_transport_security": True,
        "strict_transport_security_include_subdomains": True,
        "strict_transport_security_max_age": 31556926,  # One year in seconds
        "strict_transport_security_preload": False,
    }
    # enable local login
    ACCOUNTS_LOCAL_LOGIN_ENABLED = env.INVENIO_ACCOUNTS_LOCAL_LOGIN_ENABLED
    # local login: allow users to register
    SECURITY_REGISTERABLE = env.INVENIO_SECURITY_REGISTERABLE
    # local login: allow users to reset the password
    SECURITY_RECOVERABLE = env.INVENIO_SECURITY_RECOVERABLE
    # local login: allow users to change psw
    SECURITY_CHANGEABLE = env.INVENIO_SECURITY_CHANGEABLE
    # local login: users can confirm e-mail address
    SECURITY_CONFIRMABLE = env.INVENIO_SECURITY_CONFIRMABLE
    # require users to confirm email before being able to login
    SECURITY_LOGIN_WITHOUT_CONFIRMATION = env.INVENIO_SECURITY_LOGIN_WITHOUT_CONFIRMATION
    SESSION_COOKIE_SECURE = True

    # user security settings
    RATELIMIT_GUEST_USER = "5000 per hour;500 per minute"
    RATELIMIT_AUTHENTICATED_USER = "20000 per hour;2000 per minute"
    OAUTHCLIENT_REMOTE_APPS: dict[str, Any] = {}  # configure external login providers
    ACCOUNTS_LOGIN_VIEW_FUNCTION = auto_redirect_login  # autoredirect to external login if enabled

    # database
    SQLALCHEMY_DATABASE_URI = env.get("INVENIO_SQLALCHEMY_DATABASE_URI", None) or (
        "postgresql+psycopg2://"
        f"{env.INVENIO_DATABASE_USER}:{env.INVENIO_DATABASE_PASSWORD}"
        f"@{env.INVENIO_DATABASE_HOST}:{env.INVENIO_DATABASE_PORT}"
        f"/{env.INVENIO_DATABASE_DBNAME}"
    )

    # i18n
    BABEL_DEFAULT_LOCALE = "en"
    BABEL_DEFAULT_TIMEZONE = "Europe/Prague"
    I18N_LANGUAGES = list(languages)

    # files
    SEND_FILE_MAX_AGE_DEFAULT = 300
    FILES_REST_STORAGE_FACTORY = "invenio_s3.s3fs_storage_factory"
    S3_ENDPOINT_URL = env.get("INVENIO_S3_ENDPOINT_URL", None) or (
        f"{env.INVENIO_S3_PROTOCOL}://{env.INVENIO_S3_HOST}:{env.INVENIO_S3_PORT}/"
    )
    S3_ACCESS_KEY_ID = env.INVENIO_S3_ACCESS_KEY
    S3_SECRET_ACCESS_KEY = env.INVENIO_S3_SECRET_KEY
    APP_DEFAULT_SECURE_HEADERS["content_security_policy"]["default-src"].append(S3_ENDPOINT_URL)
    FILES_REST_STORAGE_CLASS_LIST = {
        "L": "Local",
    }
    FILES_REST_DEFAULT_STORAGE_CLASS = "L"

    # user profiles
    USERPROFILES_READ_ONLY = False  # allow users to change profile info (name, email, etc...)

    OAISERVER_ID_PREFIX = LocalProxy(lambda: urlparse(current_app.config["SITE_UI_URL"]).hostname or "")

    # search
    SEARCH_INDEX_PREFIX = env.INVENIO_SEARCH_INDEX_PREFIX
    search_hosts = env.get("INVENIO_SEARCH_HOSTS", None)
    if isinstance(search_hosts, str):
        search_hosts = ast.literal_eval(search_hosts)
    SEARCH_HOSTS = search_hosts or [
        {"host": env.INVENIO_OPENSEARCH_HOST, "port": env.INVENIO_OPENSEARCH_PORT},
    ]
    SEARCH_CLIENT_CONFIG = {
        "use_ssl": env.INVENIO_OPENSEARCH_USE_SSL,
        "verify_certs": env.INVENIO_OPENSEARCH_VERIFY_CERTS,
        "ssl_assert_hostname": env.INVENIO_OPENSEARCH_ASSERT_HOSTNAME,
        "ssl_show_warn": env.INVENIO_OPENSEARCH_SHOW_WARN,
        "ca_certs": env.get("INVENIO_OPENSEARCH_CA_CERTS_PATH", None),
    }
    if env.get("INVENIO_OPENSEARCH_TIMEOUT", None) is not None:
        # request timeout in seconds; the client's own default (10s) applies otherwise
        SEARCH_CLIENT_CONFIG["timeout"] = env.INVENIO_OPENSEARCH_TIMEOUT

    # caches
    INVENIO_CACHE_TYPE = "redis"

    def _redis_url_with_db(redis_url: str, db: str) -> str:
        # swap only the path (db number), keeping scheme/auth/host/port/query intact
        return urlunparse(urlparse(redis_url)._replace(path=f"/{db}"))

    # generic cache
    external_redis_cache_url = env.get("INVENIO_CACHE_REDIS_URL", None)
    CACHE_REDIS_URL = external_redis_cache_url or (
        f"redis://{env.INVENIO_REDIS_HOST}:{env.INVENIO_REDIS_PORT}/{env.INVENIO_REDIS_CACHE_DB}"
    )

    # user session cache
    external_redis_accounts_url = env.get("INVENIO_ACCOUNTS_SESSION_REDIS_URL", None)
    if external_redis_accounts_url is None and external_redis_cache_url is not None:
        # use the same host but replace the db
        external_redis_accounts_url = _redis_url_with_db(external_redis_cache_url, env.INVENIO_REDIS_SESSION_DB)
    ACCOUNTS_SESSION_REDIS_URL = external_redis_accounts_url or (
        f"redis://{env.INVENIO_REDIS_HOST}:{env.INVENIO_REDIS_PORT}/{env.INVENIO_REDIS_SESSION_DB}"
    )

    # communities cache
    external_redis_communities_url = env.get("INVENIO_COMMUNITIES_IDENTITIES_CACHE_REDIS_URL", None)
    if external_redis_communities_url is None and external_redis_cache_url is not None:
        # use the same host but replace the db
        external_redis_communities_url = _redis_url_with_db(
            external_redis_cache_url, env.INVENIO_REDIS_COMMUNITIES_CACHE_DB
        )
    COMMUNITIES_IDENTITIES_CACHE_REDIS_URL = external_redis_communities_url or (
        f"redis://{env.INVENIO_REDIS_HOST}:{env.INVENIO_REDIS_PORT}/{env.INVENIO_REDIS_COMMUNITIES_CACHE_DB}"
    )

    # json schemas for validation
    RECORDS_REFRESOLVER_CLS = "invenio_records.resolver.InvenioRefResolver"
    RECORDS_REFRESOLVER_STORE = "invenio_jsonschemas.proxies.current_refresolver_store"
    JSONSCHEMAS_HOST = SITE_UI_URL

    # vocabularies
    try:
        from oarepo_vocabularies.resources.config import VocabulariesResourceConfig
        from oarepo_vocabularies.services.config import VocabulariesConfig

        VOCABULARIES_SERVICE_CONFIG = VocabulariesConfig
        VOCABULARIES_RESOURCE_CONFIG = VocabulariesResourceConfig
    except ImportError:
        # keep the default Invenio vocabularies config
        pass

    # Redis port redirection
    # ---------------------
    CELERY_BROKER_URL = env.get("INVENIO_CELERY_BROKER_URL", None) or (
        f"amqp://{env.INVENIO_RABBIT_USER}:{env.INVENIO_RABBIT_PASSWORD}"
        f"@{env.INVENIO_RABBIT_HOST}:{env.INVENIO_RABBIT_PORT}/"
    )
    BROKER_URL = CELERY_BROKER_URL
    CELERY_RESULT_BACKEND = env.get("INVENIO_CELERY_RESULT_BACKEND", None) or (
        f"redis://{env.INVENIO_REDIS_HOST}:{env.INVENIO_REDIS_PORT}/{env.INVENIO_REDIS_CELERY_RESULT_DB}"
    )

    # Instance secret key, used to encrypt stuff (for example, access tokens) inside database
    SECRET_KEY = env.INVENIO_SECRET_KEY

    DASHBOARD_RECORD_CREATE_URL = None

    # Do not add default records as we provide our own compatibility layer
    RECORD_ROUTES: dict = {}  # type: ignore[var-annotated]
    RECORDS_REST_ENDPOINTS: dict = {}  # type: ignore[var-annotated]

    # datacite & dois default
    DATACITE_TEST_MODE = True

    MAIL_DEFAULT_SENDER = env.get(
        "INVENIO_MAIL_DEFAULT_SENDER",
        "please-set-invenio_mail_default_sender@test.com",
    )

    if env.get("INVENIO_MAIL_SUPPRESS_SEND", None) is not None:
        MAIL_SUPPRESS_SEND = env.get("INVENIO_MAIL_SUPPRESS_SEND", True)

    # default schemes for identifiers
    from invenio_vocabularies import config as vocab_config
    from oarepo.initial_rdm_config import is_researcher_id, is_scopus_id, is_vedidk

    VOCABULARIES_NAMES_SCHEMES = merge_with_caller(
        "VOCABULARIES_NAMES_SCHEMES",
        {
            **vocab_config.VOCABULARIES_NAMES_SCHEMES,
            "vedidk": {"label": "VEDIDK", "validator": is_vedidk},
            "scopusId": {"label": "Scopus ID", "validator": is_scopus_id},
            "researcherId": {"label": "Researcher ID", "validator": is_researcher_id},
        },
    )

    # adding crossrefFunderId to funder schemes
    VOCABULARIES_FUNDER_SCHEMES = merge_with_caller(
        "VOCABULARIES_FUNDER_SCHEMES",
        {
            **vocab_config.VOCABULARIES_FUNDER_SCHEMES,
            "crossrefFunderId": {
                "label": "CrossrefFunderID",
                "validator": lambda _: True,
            },
        },
    )

    # List of affiliations is curated, validators are not needed.
    VOCABULARIES_AFFILIATION_SCHEMES = merge_with_caller(
        "VOCABULARIES_AFFILIATION_SCHEMES",
        {
            **vocab_config.VOCABULARIES_AFFILIATION_SCHEMES,
            "ico": {"label": "ICO", "validator": lambda _: True},
            "url": {"label": "URL", "validator": lambda _: True},
        },
    )

    from invenio_app_rdm import config as app_rdm_config

    APP_RDM_IDENTIFIER_SCHEMES_UI = {
        "orcid": {
            "url_prefix": "http://orcid.org/",
            "icon": "images/orcid.svg",
            "label": "ORCID",
        },
        "ror": {
            "url_prefix": "https://ror.org/",
            "icon": "images/ror-icon.svg",
            "label": "ROR",
        },
        "gnd": {
            "url_prefix": "http://d-nb.info/gnd/",
            "icon": "images/gnd-icon.svg",
            "label": "GND",
        },
    }

    VOCABULARIES_DATASTREAM_READERS = merge_with_caller(
        "VOCABULARIES_DATASTREAM_READERS",
        app_rdm_config.VOCABULARIES_DATASTREAM_READERS,
    )
    VOCABULARIES_DATASTREAM_WRITERS = merge_with_caller(
        "VOCABULARIES_DATASTREAM_WRITERS",
        app_rdm_config.VOCABULARIES_DATASTREAM_WRITERS,
    )
    VOCABULARIES_DATASTREAM_TRANSFORMERS = merge_with_caller(
        "VOCABULARIES_DATASTREAM_TRANSFORMERS",
        app_rdm_config.VOCABULARIES_DATASTREAM_TRANSFORMERS,
    )

    if use_path_pid_ids:
        from invenio_rdm_records.resources.config import (
            RDMGrantGroupAccessResourceConfig,
            RDMGrantUserAccessResourceConfig,
            RDMParentGrantsResourceConfig,
            RDMParentRecordLinksResourceConfig,
        )

        RDMParentRecordLinksResourceConfig.url_prefix = "/records/<path:pid_value>/access"
        RDMParentGrantsResourceConfig.url_prefix = "/records/<path:pid_value>/access"
        RDMGrantUserAccessResourceConfig.url_prefix = "/records/<path:pid_value>/access"
        RDMGrantGroupAccessResourceConfig.url_prefix = "/records/<path:pid_value>/access"

    OAUTHCLIENT_AUTO_REDIRECT_TO_EXTERNAL_LOGIN = False

    # ROR client id - not used for authentication, just to increase rate limits
    ROR_CLIENT_ID = "3764CLXJ4R9GT9L496QSKU2G3ZWVF71A"
    SESSION_COOKIE_DOMAIN = None
    # Flask-Collect configured to not use symlinks, as they can break the build due to duplicate static assets.
    COLLECT_STORAGE = "flask_collect.storage.file"

    # AUDIT LOGS
    AUDIT_LOGS_ENABLED = True

    import os
    import platform

    if Path("/opt/homebrew/lib").exists() and platform.system() == "Darwin":
        os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = "/opt/homebrew/lib"
    # InvenioRDM flavour defaults; anything set explicitly above wins
    set_constants_in_caller({**rdm_defaults(env), **locals()})

initialize_i18n() -> None

Enable translated validation error messages.

Makes sure that when a user submits invalid data (for example, a required field is missing), the error message shown to them is translated into their chosen language instead of always being shown in English. Takes no parameters; call it once, near the top of invenio.cfg.

Invenio configuration variables set: none - this only patches Marshmallow's error-message machinery in memory.

Example
config.initialize_i18n()
Source code in oarepo_config/i18n.py
def initialize_i18n() -> None:
    """Enable translated validation error messages.

    Makes sure that when a user submits invalid data (for example, a
    required field is missing), the error message shown to them is
    translated into their chosen language instead of always being shown
    in English. Takes no parameters; call it once, near the top of
    `invenio.cfg`.

    Invenio configuration variables set: none - this only patches
    Marshmallow's error-message machinery in memory.

    Example:
        ```python
        config.initialize_i18n()
        ```

    """
    from flask_babel import lazy_gettext as _
    from marshmallow_i18n_messages import add_i18n_to_marshmallow

    add_i18n_to_marshmallow(_)

configure_llm(api_token: str | None = None, *, enabled: bool = True, client_name: str = OAREPO_CHECKS_DEFAULT_CHAT_EINFRA_CLIENT, api_url: str = 'https://llm.ai.e-infra.cz/v1/chat/completions', model: str = 'nrp', fallback_community: str | None = None, as_default: bool = True) -> None

Set up the LLM client(s) used by oarepo-checks' AI-assisted record validation.

oarepo-checks can validate a record's metadata by sending it to a Large Language Model and checking the response (its "llm" check, shown to users as "AI validation") before a record may be published. This registers one such LLM client (built-in support is for chat.ai.e-infra.cz) that the check can use.

Call it once per LLM client/token you want available - each call reads back and extends whatever a previous call already registered (via get_constant_from_caller), it does not replace it. This also means, when calling it more than once, that whichever call has as_default=True last wins as the default client.

Requires the optional oarepo-checks package to be installed; without it, calling this raises an ImportError explaining that the package needs to be installed first.

Parameters:

Name Type Description Default
api_token str | None

Bearer token for the ChatEInfraClient (chat.ai.e-infra.cz). If not given, this call only touches CHECKS_ENABLED/CHECKS_GENERIC_COMMUNITY/the default client marker below, without registering a new client under client_name. Typically read from the deployment's variables/.env/environment via load_configuration_variables, not hardcoded.

None
enabled bool

Set to False to skip configuring the LLM subsystem entirely (nothing else below is set).

True
client_name str

The key this client is registered under in OAREPO_CHECKS_LLM_CLIENTS. Use a different name per call if you are registering more than one client.

OAREPO_CHECKS_DEFAULT_CHAT_EINFRA_CLIENT
api_url str

The ChatEInfraClient API endpoint to send requests to.

'https://llm.ai.e-infra.cz/v1/chat/completions'
model str

The model name the ChatEInfraClient requests.

'nrp'
fallback_community str | None

Slug of the community used for checks that aren't tied to a specific community. If given, overrides whatever a previous call already set; if not given, an already-set value is kept, defaulting to "llm-settings-community" if no call has provided one yet.

None
as_default bool

Mark client_name as the client checks use when they don't request one by name (OAREPO_CHECKS_DEFAULT_LLM_CLIENT).

True

Invenio configuration variables set:

  • CHECKS_ENABLED - the enabled argument above.
  • OAREPO_CHECKS_LLM_CLIENTS - only if enabled; extended (not replaced) with a ChatEInfraClient entry under client_name, only if api_token was given.
  • OAREPO_CHECKS_DEFAULT_LLM_CLIENT - only if enabled and as_default; set to client_name.
  • CHECKS_GENERIC_COMMUNITY - only if enabled; fallback_community if given, else an already-set value, else "llm-settings-community".
Example
env = config.load_configuration_variables()
config.configure_llm(
    api_token=env.get(
        "INVENIO_LLM_API_TOKEN"
    )
)

# registering a second, non-default client:
config.configure_llm(
    api_token=env.get(
        "INVENIO_LLM_BACKUP_API_TOKEN"
    ),
    client_name="chat_einfra_backup",
    as_default=False,
)
Source code in oarepo_config/llm.py
def configure_llm(  # noqa: PLR0913
    api_token: str | None = None,
    *,
    enabled: bool = True,
    client_name: str = OAREPO_CHECKS_DEFAULT_CHAT_EINFRA_CLIENT,
    api_url: str = "https://llm.ai.e-infra.cz/v1/chat/completions",
    model: str = "nrp",
    fallback_community: str | None = None,
    as_default: bool = True,
) -> None:
    """Set up the LLM client(s) used by oarepo-checks' AI-assisted record validation.

    `oarepo-checks` can validate a record's metadata by sending it to a
    Large Language Model and checking the response (its `"llm"` check,
    shown to users as "AI validation") before a record may be published.
    This registers one such LLM client (built-in support is for
    chat.ai.e-infra.cz) that the check can use.

    Call it once per LLM client/token you want available - each call reads
    back and extends whatever a previous call already registered (via
    `get_constant_from_caller`), it does not replace it. This also
    means, when calling it more than once, that **whichever call has
    `as_default=True` last wins** as the default client.

    Requires the optional `oarepo-checks` package to be installed;
    without it, calling this raises an `ImportError` explaining that the
    package needs to be installed first.

    Args:
        api_token: Bearer token for the `ChatEInfraClient`
            (chat.ai.e-infra.cz). If not given, this call only touches
            `CHECKS_ENABLED`/`CHECKS_GENERIC_COMMUNITY`/the default
            client marker below, without registering a new client under
            `client_name`. Typically read from the deployment's
            `variables`/`.env`/environment via
            [`load_configuration_variables`][oarepo_config.load_configuration_variables], not hardcoded.
        enabled: Set to `False` to skip configuring the LLM subsystem
            entirely (nothing else below is set).
        client_name: The key this client is registered under in
            `OAREPO_CHECKS_LLM_CLIENTS`. Use a different name per call
            if you are registering more than one client.
        api_url: The `ChatEInfraClient` API endpoint to send requests to.
        model: The model name the `ChatEInfraClient` requests.
        fallback_community: Slug of the community used for checks that
            aren't tied to a specific community. If given, overrides
            whatever a previous call already set; if not given, an
            already-set value is kept, defaulting to
            `"llm-settings-community"` if no call has provided one yet.
        as_default: Mark `client_name` as the client checks use when
            they don't request one by name (`OAREPO_CHECKS_DEFAULT_LLM_CLIENT`).

    Invenio configuration variables set:

    * `CHECKS_ENABLED` - the `enabled` argument above.
    * `OAREPO_CHECKS_LLM_CLIENTS` - only if `enabled`; extended (not
      replaced) with a `ChatEInfraClient` entry under `client_name`,
      only if `api_token` was given.
    * `OAREPO_CHECKS_DEFAULT_LLM_CLIENT` - only if `enabled` and
      `as_default`; set to `client_name`.
    * `CHECKS_GENERIC_COMMUNITY` - only if `enabled`; `fallback_community`
      if given, else an already-set value, else `"llm-settings-community"`.

    Example:
        ```python
        env = config.load_configuration_variables()
        config.configure_llm(
            api_token=env.get(
                "INVENIO_LLM_API_TOKEN"
            )
        )

        # registering a second, non-default client:
        config.configure_llm(
            api_token=env.get(
                "INVENIO_LLM_BACKUP_API_TOKEN"
            ),
            client_name="chat_einfra_backup",
            as_default=False,
        )
        ```

    """
    try:
        from oarepo_checks.llm_client import ChatEInfraClient
    except ImportError as e:
        raise ImportError("Please install oarepo-checks to use llm configuration") from e

    CHECKS_ENABLED = enabled
    if CHECKS_ENABLED:
        OAREPO_CHECKS_LLM_CLIENTS = dict(get_constant_from_caller("OAREPO_CHECKS_LLM_CLIENTS") or {})

        if as_default:
            OAREPO_CHECKS_DEFAULT_LLM_CLIENT = client_name

        if fallback_community:
            CHECKS_GENERIC_COMMUNITY = fallback_community
        else:
            CHECKS_GENERIC_COMMUNITY = get_constant_from_caller("CHECKS_GENERIC_COMMUNITY") or "llm-settings-community"

        if api_token and client_name not in OAREPO_CHECKS_LLM_CLIENTS:
            OAREPO_CHECKS_LLM_CLIENTS[client_name] = ChatEInfraClient(
                api_token=api_token,
                api_url=api_url,
                model=model,
            )

    set_constants_in_caller(locals())

add_model(model_package_name: str) -> None

Include a data model in the repository's global (cross-model) search.

Repositories can host several different kinds of records (models), e.g. "datasets" and "publications". Call this once per model package to make its records show up in searches that span all models at once (as opposed to searching within just one model). This does not register the model itself (its API endpoints, forms, etc.) - that is normally done separately, by calling that model package's own register() function.

Parameters:

Name Type Description Default
model_package_name str

The Python import path of the generated model package to add, e.g. "datasets" for a model built from a datasets model package. If the package cannot be found or has not been built yet, this is only logged as an error - it does not stop the repository from starting.

required

Invenio configuration variables set:

  • GLOBAL_SEARCH_MODELS - the model's MODEL_DEFINITION is appended to this list; any models already registered (by earlier calls, or by other packages) are kept.
Example
from datasets import datasets_model

datasets_model.register()
config.add_model("datasets")
Source code in oarepo_config/models.py
def add_model(model_package_name: str) -> None:
    """Include a data model in the repository's global (cross-model) search.

    Repositories can host several different kinds of records (models),
    e.g. "datasets" and "publications". Call this once per model package
    to make its records show up in searches that span all models at
    once (as opposed to searching within just one model). This does not
    register the model itself (its API endpoints, forms, etc.) - that is
    normally done separately, by calling that model package's own
    `register()` function.

    Args:
        model_package_name: The Python import path of the generated
            model package to add, e.g. `"datasets"` for a model built
            from a `datasets` model package. If the package cannot be
            found or has not been built yet, this is only logged as an
            error - it does not stop the repository from starting.

    Invenio configuration variables set:

    * `GLOBAL_SEARCH_MODELS` - the model's `MODEL_DEFINITION` is
      appended to this list; any models already registered (by earlier
      calls, or by other packages) are kept.

    Example:
        ```python
        from datasets import datasets_model

        datasets_model.register()
        config.add_model("datasets")
        ```

    """
    from invenio_base.utils import obj_or_import_string

    model = obj_or_import_string(f"runtime_models_{model_package_name}")
    if hasattr(model, "record_error_handlers"):
        RDM_RECORDS_ERROR_HANDLERS = (
            get_constant_from_caller("RDM_RECORDS_ERROR_HANDLERS") | model.record_error_handlers  # type: ignore[reportOptionalMemberAccess]
        )
        set_constants_in_caller({"RDM_RECORDS_ERROR_HANDLERS": RDM_RECORDS_ERROR_HANDLERS})

configure_oai(repository_name: str | None = None, admin_emails: list[str] | tuple[str, ...] | str | None = None, page_size: int = 50, resumption_token_expire_time: int = 120) -> None

Set up OAI-PMH, the protocol other systems use to harvest records from this repository.

OAI-PMH is a standard way for external services (e.g. national aggregators, other repositories) to regularly fetch a list of published records. This announces the repository's name and contact over that protocol, using the values already set via configure_ui, and tunes the paging of list responses.

Unless repository_name is given, this must be called after configure_ui, since it needs the repository name that function sets up; calling it earlier raises an error explaining this.

Parameters:

Name Type Description Default
repository_name str | None

Name announced in the Identify response. Defaults to the (English) name passed to configure_ui; pass it explicitly if harvesters should see a different, e.g. more descriptive, name.

None
admin_emails list[str] | tuple[str, ...] | str | None

E-mail address(es) published as the repository's administrative contact in the Identify response. Defaults to the support_contact passed to configure_ui if that is an e-mail address. Without either, the variable is left alone and invenio-oaiserver keeps announcing its placeholder, info@inveniosoftware.org - a warning is logged.

None
page_size int

Number of records returned per ListRecords / ListIdentifiers / ListSets page. invenio-oaiserver's own default is 10, which makes harvesting a larger repository needlessly slow; this defaults to 50, as on Zenodo.

50
resumption_token_expire_time int

How long, in seconds, a harvester may wait before asking for the next page. Defaults to 120 (invenio-oaiserver's own default is 60).

120

Invenio configuration variables set:

  • OAISERVER_REPOSITORY_NAME - the repository_name above, or a copy of REPOSITORY_NAME (set by configure_ui).
  • OAISERVER_ADMIN_EMAILS - the admin_emails above, if known.
  • OAISERVER_PAGE_SIZE - the page_size above.
  • OAISERVER_RESUMPTION_TOKEN_EXPIRE_TIME - the resumption_token_expire_time above.
Example
config.configure_oai()
# or with an explicit contact:
config.configure_oai(
    admin_emails=[
        "repository@example.com"
    ]
)
Source code in oarepo_config/oai.py
def configure_oai(
    repository_name: str | None = None,
    admin_emails: list[str] | tuple[str, ...] | str | None = None,
    page_size: int = 50,
    resumption_token_expire_time: int = 120,
) -> None:
    """Set up OAI-PMH, the protocol other systems use to harvest records from this repository.

    OAI-PMH is a standard way for external services (e.g. national
    aggregators, other repositories) to regularly fetch a list of
    published records. This announces the repository's name and contact
    over that protocol, using the values already set via
    [`configure_ui`][oarepo_config.configure_ui], and tunes the paging of
    list responses.

    Unless `repository_name` is given, this must be called *after*
    [`configure_ui`][oarepo_config.configure_ui], since it needs the
    repository name that function sets up; calling it earlier raises an
    error explaining this.

    Args:
        repository_name: Name announced in the `Identify` response.
            Defaults to the (English) `name` passed to
            [`configure_ui`][oarepo_config.configure_ui]; pass it
            explicitly if harvesters should see a different, e.g. more
            descriptive, name.
        admin_emails: E-mail address(es) published as the repository's
            administrative contact in the `Identify` response. Defaults to
            the `support_contact` passed to
            [`configure_ui`][oarepo_config.configure_ui] if that is an
            e-mail address. Without either, the variable is left alone and
            invenio-oaiserver keeps announcing its placeholder,
            `info@inveniosoftware.org` - a warning is logged.
        page_size: Number of records returned per `ListRecords` /
            `ListIdentifiers` / `ListSets` page. invenio-oaiserver's own
            default is 10, which makes harvesting a larger repository
            needlessly slow; this defaults to 50, as on Zenodo.
        resumption_token_expire_time: How long, in seconds, a harvester
            may wait before asking for the next page. Defaults to 120
            (invenio-oaiserver's own default is 60).

    Invenio configuration variables set:

    * `OAISERVER_REPOSITORY_NAME` - the `repository_name` above, or a
      copy of `REPOSITORY_NAME` (set by
      [`configure_ui`][oarepo_config.configure_ui]).
    * `OAISERVER_ADMIN_EMAILS` - the `admin_emails` above, if known.
    * `OAISERVER_PAGE_SIZE` - the `page_size` above.
    * `OAISERVER_RESUMPTION_TOKEN_EXPIRE_TIME` - the
      `resumption_token_expire_time` above.

    Example:
        ```python
        config.configure_oai()
        # or with an explicit contact:
        config.configure_oai(
            admin_emails=[
                "repository@example.com"
            ]
        )
        ```

    """
    repo_name = repository_name or get_constant_from_caller("REPOSITORY_NAME")
    if not repo_name:
        raise ValueError(
            "REPOSITORY_NAME must be set, please configure UI before configuring OAI or pass repository_name."
        )
    OAISERVER_REPOSITORY_NAME = str(repo_name)

    if admin_emails is None:
        support_contact = str(get_constant_from_caller("REPOSITORY_SUPPORT_CONTACT") or "").strip()
        if "@" in support_contact and " " not in support_contact:
            admin_emails = [support_contact]
    elif isinstance(admin_emails, str):
        admin_emails = [admin_emails]

    if admin_emails:
        OAISERVER_ADMIN_EMAILS = list(admin_emails)
    else:
        log.warning(
            "No OAI-PMH administrator e-mail configured: pass admin_emails=[...] to configure_oai() "
            "or an e-mail address as support_contact to configure_ui()."
        )

    OAISERVER_PAGE_SIZE = page_size
    OAISERVER_RESUMPTION_TOKEN_EXPIRE_TIME = resumption_token_expire_time

    set_constants_in_caller(locals())

configure_stats(enable: bool = True, count_preview_downloads: bool = True) -> None

Set up usage statistics (record views, downloads, etc.).

Enables the collection and aggregation of usage events, such as how many times a record was viewed or a file was downloaded, so this data can later be shown to users and curators.

Parameters:

Name Type Description Default
enable bool

Set to False to turn off collecting new usage statistics events (for example on a staging/test instance). Defaults to True.

True
count_preview_downloads bool

Whether a file fetched by the in-page file previewer counts as a download. True (the default, same as upstream InvenioRDM) counts it; with False, as on Zenodo, merely opening a record page that previews a file no longer inflates the download numbers.

True

Invenio configuration variables set:

  • STATS_REGISTER_RECEIVERS - the enable argument above.
  • RDM_STATS_EXCLUDE_PREVIEW_FILE_DOWNLOAD_EVENTS - the inverse of count_preview_downloads.
  • STATS_EVENTS, STATS_AGGREGATIONS, STATS_QUERIES, STATS_PERMISSION_FACTORY - always set to invenio-app-rdm's defaults, regardless of enable.
Example
config.configure_stats()
# or on a test instance:
config.configure_stats(enable=False)
Source code in oarepo_config/stats.py
def configure_stats(
    enable: bool = True,
    count_preview_downloads: bool = True,
) -> None:
    """Set up usage statistics (record views, downloads, etc.).

    Enables the collection and aggregation of usage events, such as how
    many times a record was viewed or a file was downloaded, so this
    data can later be shown to users and curators.

    Args:
        enable: Set to `False` to turn off collecting new usage
            statistics events (for example on a staging/test instance).
            Defaults to `True`.
        count_preview_downloads: Whether a file fetched by the in-page
            file previewer counts as a download. `True` (the default,
            same as upstream InvenioRDM) counts it; with `False`, as on
            Zenodo, merely opening a record page that previews a file no
            longer inflates the download numbers.

    Invenio configuration variables set:

    * `STATS_REGISTER_RECEIVERS` - the `enable` argument above.
    * `RDM_STATS_EXCLUDE_PREVIEW_FILE_DOWNLOAD_EVENTS` - the inverse of
      `count_preview_downloads`.
    * `STATS_EVENTS`, `STATS_AGGREGATIONS`, `STATS_QUERIES`,
      `STATS_PERMISSION_FACTORY` - always set to `invenio-app-rdm`'s
      defaults, regardless of `enable`.

    Example:
        ```python
        config.configure_stats()
        # or on a test instance:
        config.configure_stats(enable=False)
        ```

    """
    STATS_REGISTER_RECEIVERS = enable

    from invenio_app_rdm.config import (
        STATS_AGGREGATIONS,
        STATS_EVENTS,
        STATS_PERMISSION_FACTORY,
        STATS_QUERIES,
    )

    set_constants_in_caller(
        {
            "STATS_REGISTER_RECEIVERS": STATS_REGISTER_RECEIVERS,
            "RDM_STATS_EXCLUDE_PREVIEW_FILE_DOWNLOAD_EVENTS": not count_preview_downloads,
            "STATS_EVENTS": STATS_EVENTS,
            "STATS_AGGREGATIONS": STATS_AGGREGATIONS,
            "STATS_QUERIES": STATS_QUERIES,
            "STATS_PERMISSION_FACTORY": STATS_PERMISSION_FACTORY,
        }
    )

configure_ui(code: str = 'myrepo', name: str | Any = 'My Repository', subtitle: str = '', description: str = '', support_contact: str = '', keywords: str = '', use_default_frontpage: bool = False, show_frontpage_intro: bool = True, analytics: str | bool = False, languages: tuple[tuple[str, str], ...] = (('en', 'English'),), csp: CSP | None = None) -> None

Set up the repository's branding, name and general look-and-feel.

Configures what visitors see: the repository's name and description shown in the browser tab/search results/front page, the theme, the page layout templates, and (optionally) analytics tracking.

Parameters:

Name Type Description Default
code str

A short, technical, all-lowercase identifier for this repository (e.g. "myrepo"); used internally to select the repository's own theme files.

'myrepo'
name str | Any

The repository's display name, shown in the browser title and on the front page, e.g. _("My Repository").

'My Repository'
subtitle str

A short subtitle/tagline shown next to the name.

''
description str

A longer description of the repository, used for SEO and on the front page.

''
support_contact str

Contact information (e.g. an e-mail address) shown to users who need help.

''
keywords str

Keywords describing the repository's content, used for SEO.

''
use_default_frontpage bool

Whether to use Invenio's generic front page. Most repositories provide a custom front page, so this defaults to False.

False
show_frontpage_intro bool

Whether to show the introductory text section on the front page.

True
analytics str | bool

Set to "matomo" to enable Matomo web analytics tracking (only takes effect on deployed, non-local instances; requires the Matomo URL/site ID to be configured in the deployment's environment). False (the default) disables analytics.

False
languages tuple[tuple[str, str], ...]

Extra UI languages to offer, as a tuple of (language_code, label) pairs. English is always available and does not need to be listed. This should normally match what was passed to configure_generic_parameters.

(('en', 'English'),)
csp CSP | None

Content Security Policy configuration. Only the sources passed here are recorded; the ones the deployment already allows (set up by configure_generic_parameters) are added on top of them by CSP.apply_defaults.

None

Should be called after configure_generic_parameters (it builds on settings that function prepares) and before configure_oai (which needs the repository name set here).

Example
config.configure_ui(
    code="myrepo",
    name=_("My Repository"),
    description=_(
        "A repository for my data"
    ),
    support_contact="support@example.com",
    csp=CSP(
        # where the UI's JavaScript may fetch data from,
        # e.g. an external REST API
        connect_src=[
            "'self'",
            "https://api.example.com",
        ],
    ),
)

Invenio configuration variables set, grouped by area:

Versioning * DEPLOYMENT_VERSION

Theme & security * APP_THEME * APP_DEFAULT_SECURE_HEADERS - extends the value prepared by configure_generic_parameters.

Page layout templates * INSTANCE_THEME_FILE * BASE_TEMPLATE, ADMINISTRATION_THEME_BASE_TEMPLATE, COVER_TEMPLATE * THEME_CSS_TEMPLATE, THEME_JAVASCRIPT_TEMPLATE * HEADER_TEMPLATE, THEME_HEADER_TEMPLATE, THEME_HEADER_LOGIN_TEMPLATE, THEME_FOOTER_TEMPLATE * THEME_TRACKINGCODE_TEMPLATE, THEME_FRONTPAGE_TEMPLATE * SETTINGS_TEMPLATE, SEARCH_UI_SEARCH_TEMPLATE

Analytics * MATOMO_ANALYTICS_TEMPLATE, MATOMO_ANALYTICS_URL, MATOMO_ANALYTICS_SITE_ID - only if analytics="matomo" and this is not a local-development deployment.

Branding * THEME_FRONTPAGE, THEME_LOGO, THEME_FRONTPAGE_LOGO * THEME_SITENAME, THEME_FRONTPAGE_TITLE, THEME_SHOW_FRONTPAGE_INTRO_SECTION

Repository metadata (SEO & front page) * REPOSITORY_NAME, REPOSITORY_DESCRIPTION, REPOSITORY_SUPPORT_CONTACT, REPOSITORY_SUBTITLE, REPOSITORY_KEYWORDS

Build pipeline * JAVASCRIPT_PACKAGES_MANAGER, ASSETS_BUILDER, WEBPACKEXT_NPM_PKG_CLS, WEBPACKEXT_PROJECT

Records & deposit UI * RECORDS_UI_ENDPOINTS, APP_RDM_DEPOSIT_NG_FILES_UI_ENABLED, DASHBOARD_RECORD_CREATE_URL * APP_RDM_DETAIL_SIDE_BAR_TEMPLATES

Search UI * THEME_SEARCH_ENDPOINT, SEARCH_UI_SEARCH_VIEW

Source code in oarepo_config/ui.py
def configure_ui(  # noqa PLR0915
    code: str = "myrepo",
    name: str | Any = "My Repository",
    subtitle: str = "",
    description: str = "",
    support_contact: str = "",
    keywords: str = "",
    use_default_frontpage: bool = False,
    show_frontpage_intro: bool = True,
    analytics: str | bool = False,
    languages: tuple[tuple[str, str], ...] = (("en", "English"),),
    csp: CSP | None = None,
) -> None:
    """Set up the repository's branding, name and general look-and-feel.

    Configures what visitors see: the repository's name and description
    shown in the browser tab/search results/front page, the theme, the
    page layout templates, and (optionally) analytics tracking.

    Args:
        code: A short, technical, all-lowercase identifier for this
            repository (e.g. `"myrepo"`); used internally to select
            the repository's own theme files.
        name: The repository's display name, shown in the browser title
            and on the front page, e.g. `_("My Repository")`.
        subtitle: A short subtitle/tagline shown next to the name.
        description: A longer description of the repository, used for
            SEO and on the front page.
        support_contact: Contact information (e.g. an e-mail address)
            shown to users who need help.
        keywords: Keywords describing the repository's content, used for
            SEO.
        use_default_frontpage: Whether to use Invenio's generic front
            page. Most repositories provide a custom front page, so this
            defaults to `False`.
        show_frontpage_intro: Whether to show the introductory text
            section on the front page.
        analytics: Set to `"matomo"` to enable Matomo web analytics
            tracking (only takes effect on deployed, non-local
            instances; requires the Matomo URL/site ID to be configured
            in the deployment's environment). `False` (the default)
            disables analytics.
        languages: Extra UI languages to offer, as a tuple of
            `(language_code, label)` pairs. English is always
            available and does not need to be listed. This should
            normally match what was passed to
            [`configure_generic_parameters`][oarepo_config.configure_generic_parameters].
        csp: Content Security Policy configuration. Only the sources passed
            here are recorded; the ones the deployment already allows (set up
            by [`configure_generic_parameters`][oarepo_config.configure_generic_parameters]) are added on top of them
            by `CSP.apply_defaults`.

    Should be called after [`configure_generic_parameters`][oarepo_config.configure_generic_parameters] (it
    builds on settings that function prepares) and before
    [`configure_oai`][oarepo_config.configure_oai] (which needs the repository name set here).

    Example:
        ```python
        config.configure_ui(
            code="myrepo",
            name=_("My Repository"),
            description=_(
                "A repository for my data"
            ),
            support_contact="support@example.com",
            csp=CSP(
                # where the UI's JavaScript may fetch data from,
                # e.g. an external REST API
                connect_src=[
                    "'self'",
                    "https://api.example.com",
                ],
            ),
        )
        ```

    Invenio configuration variables set, grouped by area:

    Versioning
        * `DEPLOYMENT_VERSION`

    Theme & security
        * `APP_THEME`
        * `APP_DEFAULT_SECURE_HEADERS` - extends the value prepared by
          [`configure_generic_parameters`][oarepo_config.configure_generic_parameters].

    Page layout templates
        * `INSTANCE_THEME_FILE`
        * `BASE_TEMPLATE`, `ADMINISTRATION_THEME_BASE_TEMPLATE`,
          `COVER_TEMPLATE`
        * `THEME_CSS_TEMPLATE`, `THEME_JAVASCRIPT_TEMPLATE`
        * `HEADER_TEMPLATE`, `THEME_HEADER_TEMPLATE`,
          `THEME_HEADER_LOGIN_TEMPLATE`, `THEME_FOOTER_TEMPLATE`
        * `THEME_TRACKINGCODE_TEMPLATE`, `THEME_FRONTPAGE_TEMPLATE`
        * `SETTINGS_TEMPLATE`, `SEARCH_UI_SEARCH_TEMPLATE`

    Analytics
        * `MATOMO_ANALYTICS_TEMPLATE`, `MATOMO_ANALYTICS_URL`,
          `MATOMO_ANALYTICS_SITE_ID` - only if `analytics="matomo"`
          and this is not a local-development deployment.

    Branding
        * `THEME_FRONTPAGE`, `THEME_LOGO`, `THEME_FRONTPAGE_LOGO`
        * `THEME_SITENAME`, `THEME_FRONTPAGE_TITLE`,
          `THEME_SHOW_FRONTPAGE_INTRO_SECTION`

    Repository metadata (SEO & front page)
        * `REPOSITORY_NAME`, `REPOSITORY_DESCRIPTION`,
          `REPOSITORY_SUPPORT_CONTACT`, `REPOSITORY_SUBTITLE`,
          `REPOSITORY_KEYWORDS`

    Build pipeline
        * `JAVASCRIPT_PACKAGES_MANAGER`, `ASSETS_BUILDER`,
          `WEBPACKEXT_NPM_PKG_CLS`, `WEBPACKEXT_PROJECT`

    Records & deposit UI
        * `RECORDS_UI_ENDPOINTS`,
          `APP_RDM_DEPOSIT_NG_FILES_UI_ENABLED`,
          `DASHBOARD_RECORD_CREATE_URL`
        * `APP_RDM_DETAIL_SIDE_BAR_TEMPLATES`

    Search UI
        * `THEME_SEARCH_ENDPOINT`, `SEARCH_UI_SEARCH_VIEW`

    """
    env = load_configuration_variables()

    DEPLOYMENT_VERSION = env.get("INVENIO_DEPLOYMENT_VERSION", "local development")

    APP_THEME = [code, "oarepo", "semantic-ui"]
    APP_DEFAULT_SECURE_HEADERS: dict[str, Any] = get_constant_from_caller("APP_DEFAULT_SECURE_HEADERS", {})
    APP_DEFAULT_SECURE_HEADERS["content_security_policy"]["default-src"].append(
        # Fix for displaying images from another source (this one is for licenses specifically)
        "https://licensebuttons.net/"
    )

    INSTANCE_THEME_FILE = "./less/theme.less"

    # Template config
    BASE_TEMPLATE = "page.html"
    ADMINISTRATION_THEME_BASE_TEMPLATE = "invenio_app_rdm/administration_page.html"
    COVER_TEMPLATE = "invenio_app_rdm/page_cover.html"
    THEME_CSS_TEMPLATE = "css.html"
    THEME_JAVASCRIPT_TEMPLATE = "javascript.html"
    THEME_HEADER_TEMPLATE = "header.html"
    THEME_HEADER_LOGIN_TEMPLATE = "invenio_app_rdm/header_login.html"
    THEME_FOOTER_TEMPLATE = "footer.html"
    THEME_TRACKINGCODE_TEMPLATE = "oarepo_ui/trackingcode.html"
    THEME_FRONTPAGE_TEMPLATE = "frontpage.html"

    # Invenio has problems with order of loading templates. If invenio-userprofiles is loaded
    # before invenio-theme, the userprofile page will not work because base settings page
    # will be taken from userprofiles/semantic-ui/userprofiles/settings/base.html which is faulty.
    # If invenio-theme is loaded first, SETTINGS_TEMPLATE is filled, then userprofiles will use
    # it and the UI loads correctly.
    # This line just makes sure that SETTINGS_TEMPLATE and HEADER_TEMPLATE is always set up.
    SETTINGS_TEMPLATE = "invenio_theme/page_settings.html"
    HEADER_TEMPLATE = "invenio_theme/header.html"
    SEARCH_UI_SEARCH_TEMPLATE = "invenio_app_rdm/records/search.html"

    if analytics == "matomo" and DEPLOYMENT_VERSION != "local development":
        MATOMO_ANALYTICS_TEMPLATE = "oarepo_ui/matomo_analytics.html"
        MATOMO_ANALYTICS_URL = env.INVENIO_MATOMO_ANALYTICS_URL
        MATOMO_ANALYTICS_SITE_ID = env.INVENIO_MATOMO_ANALYTICS_SITE_ID
        APP_DEFAULT_SECURE_HEADERS["content_security_policy"]["default-src"].append(env.INVENIO_MATOMO_ANALYTICS_URL)

    # UI Branding & copywriting
    THEME_FRONTPAGE = use_default_frontpage
    THEME_FRONTPAGE_LOGO = None
    THEME_SITENAME = _(name)
    THEME_FRONTPAGE_TITLE = name
    THEME_SHOW_FRONTPAGE_INTRO_SECTION = show_frontpage_intro

    # SEO & Front-page information
    REPOSITORY_NAME = name
    REPOSITORY_DESCRIPTION = description
    REPOSITORY_SUPPORT_CONTACT = support_contact
    REPOSITORY_SUBTITLE = subtitle
    REPOSITORY_KEYWORDS = keywords

    # Build pipeline config
    JAVASCRIPT_PACKAGES_MANAGER = "pnpm"
    ASSETS_BUILDER = "rspack"
    WEBPACKEXT_NPM_PKG_CLS = "pynpm:PNPMPackage"
    WEBPACKEXT_PROJECT = "oarepo_ui.webpack:project"

    # Do not add default records UI as we provide our own compatibility layer
    RECORDS_UI_ENDPOINTS: list = []  # type: ignore[var-annotated]
    # UPPY uploader is default for us
    APP_RDM_DEPOSIT_NG_FILES_UI_ENABLED = True

    DASHBOARD_RECORD_CREATE_URL = "/uploads/new"

    # change via configure_detail_sidebar
    APP_RDM_DETAIL_SIDE_BAR_TEMPLATES = [DETAIL_SIDEBAR_TEMPLATES[name] for name in DEFAULT_DETAIL_SIDEBAR]

    from invenio_search_ui import config as search_ui_config
    from invenio_theme import config as theme_config

    THEME_LOGO = "images/theme-logo.png"

    THEME_SEARCH_ENDPOINT = theme_config.THEME_SEARCH_ENDPOINT
    SEARCH_UI_SEARCH_VIEW = search_ui_config.SEARCH_UI_SEARCH_VIEW

    if csp is not None:
        APP_DEFAULT_SECURE_HEADERS.update(csp.apply_defaults(APP_DEFAULT_SECURE_HEADERS))

    set_constants_in_caller(locals())

configure_vocabulary(code: str, **kwargs: Any) -> None

Declare a custom controlled vocabulary (a fixed list of allowed values).

Vocabularies are controlled lists of values that records can pick from, such as languages, resource types or licenses. Call this once for each additional vocabulary type your repository needs, to describe it and any extra properties it should have.

Parameters:

Name Type Description Default
code str

A short, unique identifier for the vocabulary, e.g. "languages".

required
**kwargs Any

Extra details describing the vocabulary, typically including name (its display name), description, and props (a description of any extra fields each entry in the vocabulary should have, and how they appear in forms). See the OARepo reference docs for the full list of supported keys.

{}

Calling this multiple times with different code values adds multiple vocabularies; it does not replace previously configured ones.

Invenio configuration variables set:

  • INVENIO_VOCABULARY_TYPE_METADATA - the entry for code is set to kwargs; entries for other vocabulary codes (added by earlier calls) are kept.
Example
config.configure_vocabulary(
    code="languages",
    name=_("Languages"),
    description=_(
        "Language definitions"
    ),
    props={
        "alpha3Code": {
            "description": _(
                "ISO 639-2 standard 3-letter language code"
            ),
            "multiple": False,
            "search": False,
        },
    },
    dump_options=True,
)
Source code in oarepo_config/vocabulary.py
def configure_vocabulary(code: str, **kwargs: Any) -> None:
    """Declare a custom controlled vocabulary (a fixed list of allowed values).

    Vocabularies are controlled lists of values that records can pick
    from, such as languages, resource types or licenses. Call this once
    for each additional vocabulary type your repository needs, to
    describe it and any extra properties it should have.

    Args:
        code: A short, unique identifier for the vocabulary, e.g.
            `"languages"`.
        **kwargs: Extra details describing the vocabulary, typically
            including `name` (its display name), `description`, and
            `props` (a description of any extra fields each entry in
            the vocabulary should have, and how they appear in forms).
            See the
            [OARepo reference docs](https://nrp-cz.github.io/docs/customize/configure/reference#configure_vocabulary)
            for the full list of supported keys.

    Calling this multiple times with different `code` values adds
    multiple vocabularies; it does not replace previously configured
    ones.

    Invenio configuration variables set:

    * `INVENIO_VOCABULARY_TYPE_METADATA` - the entry for `code` is
      set to `kwargs`; entries for other vocabulary codes (added by
      earlier calls) are kept.

    Example:
        ```python
        config.configure_vocabulary(
            code="languages",
            name=_("Languages"),
            description=_(
                "Language definitions"
            ),
            props={
                "alpha3Code": {
                    "description": _(
                        "ISO 639-2 standard 3-letter language code"
                    ),
                    "multiple": False,
                    "search": False,
                },
            },
            dump_options=True,
        )
        ```

    """
    INVENIO_VOCABULARY_TYPE_METADATA = get_constant_from_caller("INVENIO_VOCABULARY_TYPE_METADATA", {})
    INVENIO_VOCABULARY_TYPE_METADATA[code] = kwargs

    set_constants_in_caller(locals())

configure_workflows(*workflow_definitions: BaseWorkflowSettings, default_individual_workflow: str = 'individual', default_community_workflow: str = 'community', context: dict | None = None) -> list[Workflow]

Set up workflows based on the provided workflow definitions.

This function is intended to be called from within invenio.cfg and will create a "WORKFLOWS" entry in the invenio.cfg context (in the caller's globals).

Example
# invenio.cfg
from oarepo_app.config import (
    configure_workflows,
    IndividualWorkflow,
    CommunityWorkflow,
)

configure_workflows(
    IndividualWorkflow(
        authenticated_draft_creation=False,
        review_required=True,
        publish_without_review=False,
    ),
    CommunityWorkflow(),
)
# no need to assign the result to WORKFLOWS, that is done automatically

If the workflow definitions are empty, a permissive IndividualWorkflow will be created (authenticated draft creation, publish without review allowed).

If there is no IndividualWorkflow definition in the workflow definitions (but there are other workflow types), a restricted IndividualWorkflow (no deposition allowed) will be created with default settings.

The default_individual_workflow parameter should be the code of the workflow to use as the default one for individual deposits, where no community is involved and the workflow code is not provided by the caller.

If the context is provided, the "WORKFLOWS" entry will be added to it instead of the caller's globals.

See https://nrp-cz.github.io/docs/customize/workflows for more information on how to customize the workflows.

Source code in oarepo_config/workflows/simplified/__init__.py
def configure_workflows(
    *workflow_definitions: BaseWorkflowSettings,
    default_individual_workflow: str = "individual",
    default_community_workflow: str = "community",
    context: dict | None = None,
) -> list[Workflow]:
    """Set up workflows based on the provided workflow definitions.

    This function is intended to be called from within invenio.cfg and will create
    a "WORKFLOWS" entry in the invenio.cfg context (in the caller's globals).

    Example:
        ```python
        # invenio.cfg
        from oarepo_app.config import (
            configure_workflows,
            IndividualWorkflow,
            CommunityWorkflow,
        )

        configure_workflows(
            IndividualWorkflow(
                authenticated_draft_creation=False,
                review_required=True,
                publish_without_review=False,
            ),
            CommunityWorkflow(),
        )
        # no need to assign the result to WORKFLOWS, that is done automatically
        ```

    If the workflow definitions are empty, a permissive IndividualWorkflow will be created
    (authenticated draft creation, publish without review allowed).

    If there is no IndividualWorkflow definition in the workflow definitions (but there are other workflow types), a
    restricted IndividualWorkflow (no deposition allowed) will be created with default settings.

    The default_individual_workflow parameter should be the code of the workflow to use
    as the default one for individual deposits, where no community is involved and the
    workflow code is not provided by the caller.

    If the context is provided, the "WORKFLOWS" entry will be added to it instead of
    the caller's globals.

    See https://nrp-cz.github.io/docs/customize/workflows for more information on how to customize the workflows.

    """
    if not workflow_definitions:
        workflow_definitions = (
            IndividualWorkflow(
                code=default_individual_workflow,
                authenticated_draft_creation=True,
                review_required=False,
                publish_without_review=True,
            ),
        )
    elif not any(isinstance(workflow, IndividualWorkflow) for workflow in workflow_definitions):
        workflow_definitions = (
            *workflow_definitions,
            IndividualWorkflow(
                code=default_individual_workflow,
                authenticated_draft_creation=False,
                review_required=False,
                publish_without_review=False,
            ),
        )
    built_workflows = [workflow.build_workflow() for workflow in workflow_definitions]
    if not any(workflow.code == default_individual_workflow for workflow in workflow_definitions):
        raise ValueError(f"No workflow with code '{default_individual_workflow}' found in workflow definitions")
    # check for duplicated codes
    if len(workflow_definitions) != len({workflow.code for workflow in workflow_definitions}):
        raise ValueError("Duplicate workflow codes found in workflow definitions")

    constants: dict[str, Any] = {
        "WORKFLOWS": built_workflows,
        "WORKFLOWS_DEFAULT_WORKFLOW": default_individual_workflow,
        "OAREPO_COMMUNITIES_DEFAULT_WORKFLOW": default_community_workflow,
    }

    # Default the requests permission policy to the one that also allows creating
    # community-topic request types (membership / invitation / sub-community), which
    # otherwise cannot resolve a workflow and are always denied. Respect an explicit
    # REQUESTS_PERMISSION_POLICY set by the caller.
    if RequestsPermissionPolicy is not None:
        # skipped if oarepo-workflows are not available
        if context:
            constants["REQUESTS_PERMISSION_POLICY"] = context.get(
                "REQUESTS_PERMISSION_POLICY", RequestsPermissionPolicy
            )
        else:
            constants["REQUESTS_PERMISSION_POLICY"] = get_constant_from_caller(
                "REQUESTS_PERMISSION_POLICY", RequestsPermissionPolicy
            )

    if context:
        context.update(constants)
    else:
        set_constants_in_caller(constants)
    return built_workflows

register_workflow(workflow_code: str, workflow_name: str | LazyString, permissions_policy: str | type, requests_policy: str | type, use_low_level_workflows: bool = False) -> None

Register a submission/review workflow that records can go through.

A workflow defines the path a record takes from being created to being published - for example, who may create it, whether it needs review/approval before publishing, and who may perform each of those steps. This adds one such workflow to the repository, so that it can be selected when configuring where records may be submitted (e.g. a community).

This is a low-level, single-workflow building block. Repositories that use the community-based workflow shape provided by the oarepo_app package typically use its higher-level configure_workflows(IndividualWorkflow(...), CommunityWorkflow(...)) helper instead - see this package's README for the difference.

Parameters:

Name Type Description Default
workflow_code str

A short, unique identifier for the workflow, e.g. "default".

required
workflow_name str | LazyString

The human-readable name of the workflow, shown to users, e.g. _("Default workflow").

required
permissions_policy str | type

Who is allowed to do what with records that use this workflow (create, edit, delete, publish, ...). Pass either a permissions policy class or its import path as a string.

required
requests_policy str | type

What review/approval requests are available for records using this workflow (e.g. a publish request that needs a curator's approval). Pass either a request policy class or its import path as a string.

required
use_low_level_workflows bool

Set to True to silence the warning recommending configure_workflows instead, for the (uncommon) cases that genuinely need this low-level, single-workflow API.

False

Requires the optional oarepo_workflows (and, for its defaults, oarepo_requests) package to be installed.

Invenio configuration variables set:

  • WORKFLOWS - the new workflow is appended; workflows already registered (by earlier calls) are kept.
  • REQUESTS_PERMISSION_POLICY - only if not already set by an earlier call; defaults to oarepo_config.requests.RequestsPermissionPolicy (workflow-based, plus creation of community-topic request types).
Example
from oarepo_workflows.services.permissions import (
    DefaultWorkflowPermissions,
)
from oarepo_requests.services.permissions.workflow_policies import (
    CreatorsFromWorkflowRequestsPermissionPolicy,
)

config.register_workflow(
    workflow_code="default",
    workflow_name=_("Default workflow"),
    permissions_policy=DefaultWorkflowPermissions,
    requests_policy=CreatorsFromWorkflowRequestsPermissionPolicy,
)
Source code in oarepo_config/workflows/low_level.py
def register_workflow(
    workflow_code: str,
    workflow_name: str | LazyString,
    permissions_policy: str | type,
    requests_policy: str | type,
    use_low_level_workflows: bool = False,
) -> None:
    """Register a submission/review workflow that records can go through.

    A workflow defines the path a record takes from being created to
    being published - for example, who may create it, whether it needs
    review/approval before publishing, and who may perform each of those
    steps. This adds one such workflow to the repository, so that it can
    be selected when configuring where records may be submitted (e.g. a
    community).

    This is a low-level, single-workflow building block. Repositories
    that use the community-based workflow shape provided by the
    `oarepo_app` package typically use its higher-level
    `configure_workflows(IndividualWorkflow(...), CommunityWorkflow(...))`
    helper instead - see this package's README for the difference.

    Args:
        workflow_code: A short, unique identifier for the workflow, e.g.
            `"default"`.
        workflow_name: The human-readable name of the workflow, shown to
            users, e.g. `_("Default workflow")`.
        permissions_policy: Who is allowed to do what with records that
            use this workflow (create, edit, delete, publish, ...). Pass
            either a permissions policy class or its import path as a
            string.
        requests_policy: What review/approval requests are available for
            records using this workflow (e.g. a publish request that
            needs a curator's approval). Pass either a request policy
            class or its import path as a string.
        use_low_level_workflows: Set to `True` to silence the warning
            recommending [`configure_workflows`][oarepo_config.configure_workflows] instead, for the
            (uncommon) cases that genuinely need this low-level,
            single-workflow API.

    Requires the optional `oarepo_workflows` (and, for its defaults,
    `oarepo_requests`) package to be installed.

    Invenio configuration variables set:

    * `WORKFLOWS` - the new workflow is appended; workflows already
      registered (by earlier calls) are kept.
    * `REQUESTS_PERMISSION_POLICY` - only if not already set by an
      earlier call; defaults to `oarepo_config.requests.RequestsPermissionPolicy`
      (workflow-based, plus creation of community-topic request types).

    Example:
        ```python
        from oarepo_workflows.services.permissions import (
            DefaultWorkflowPermissions,
        )
        from oarepo_requests.services.permissions.workflow_policies import (
            CreatorsFromWorkflowRequestsPermissionPolicy,
        )

        config.register_workflow(
            workflow_code="default",
            workflow_name=_("Default workflow"),
            permissions_policy=DefaultWorkflowPermissions,
            requests_policy=CreatorsFromWorkflowRequestsPermissionPolicy,
        )
        ```

    """
    if not use_low_level_workflows:
        warnings.warn(
            "register_workflow() is a low-level, single-workflow building block. "
            "configure_workflows(IndividualWorkflow(...), CommunityWorkflow(...)) is a "
            "simplified solution that should be used instead for the common case. Pass "
            "use_low_level_workflows=True if you intentionally need the low-level API.",
            stacklevel=2,
        )

    try:
        from oarepo_workflows import Workflow, WorkflowRequestPolicy
        from oarepo_workflows.services.permissions import DefaultWorkflowPermissions
    except ImportError as e:
        raise ImportError("oarepo_workflows package is required for workflow registration.") from e

    WORKFLOWS = get_constant_from_caller("WORKFLOWS", [])
    permission_policy_cls = obj_or_import_string(permissions_policy)
    if not (inspect.isclass(permission_policy_cls) and issubclass(permission_policy_cls, DefaultWorkflowPermissions)):
        raise TypeError("permissions_policy must be a subclass of DefaultWorkflowPermissions")

    requests_policy_cls = obj_or_import_string(requests_policy)
    if not (inspect.isclass(requests_policy_cls) and issubclass(requests_policy_cls, WorkflowRequestPolicy)):
        raise TypeError("requests_policy must be a subclass of WorkflowRequestPolicy")

    WORKFLOWS.append(
        Workflow(
            code=workflow_code,
            label=_(workflow_name),
            permission_policy_cls=permission_policy_cls,
            request_policy_cls=requests_policy_cls,
        )
    )
    from ..requests import RequestsPermissionPolicy

    REQUESTS_PERMISSION_POLICY = get_constant_from_caller("REQUESTS_PERMISSION_POLICY", RequestsPermissionPolicy)
    set_constants_in_caller(locals())