From 620fcc9a56a4f03a114436f0cbbcb1f46098dadc Mon Sep 17 00:00:00 2001 From: Peter Evans Date: Tue, 22 Sep 2026 13:41:10 +0100 Subject: [PATCH] feature: inbound email trigger (#5730) Co-authored-by: Jeremie Pardou <571533+jrmi@users.noreply.github.com> --- .env.docker-dev.example | 10 + backend/Dockerfile | 18 + backend/docker/docker-entrypoint.sh | 58 ++ backend/docker/generate-mox-config.sh | 182 ++++++ .../src/baserow/api/settings/serializers.py | 12 + backend/src/baserow/config/settings/base.py | 30 + backend/src/baserow/config/settings/dev.py | 9 + .../src/baserow/contrib/automation/apps.py | 2 + .../0038_coreinboundemailtriggernode.py | 24 + .../contrib/automation/nodes/models.py | 3 + .../contrib/automation/nodes/node_types.py | 18 + .../contrib/automation/nodes/ws/signals.py | 52 +- .../builder/locale/en/LC_MESSAGES/django.po | 182 +++++- .../database/locale/en/LC_MESSAGES/django.po | 52 +- .../src/baserow/contrib/integrations/apps.py | 2 + .../core/api/inbound_email/__init__.py | 0 .../core/api/inbound_email/errors.py | 7 + .../core/api/inbound_email/views.py | 66 +++ .../contrib/integrations/core/exceptions.py | 18 + .../integrations/core/inbound_email.py | 488 ++++++++++++++++ .../core/inbound_email_receiver.py | 159 ++++++ .../contrib/integrations/core/models.py | 71 +++ .../integrations/core/service_types.py | 267 +++++++++ .../0036_coreinboundemailtriggerservice.py | 28 + .../src/baserow/contrib/integrations/tasks.py | 33 ++ .../core/locale/en/LC_MESSAGES/django.po | 126 ++++- .../baserow/locale/en/LC_MESSAGES/django.po | 162 +++++- .../test_utils/fixtures/automation_node.py | 8 + .../baserow/test_utils/fixtures/service.py | 6 + .../api/settings/test_settings_views.py | 44 ++ .../automation/api/nodes/test_nodes_views.py | 31 + .../automation/nodes/test_node_types.py | 59 ++ .../automation/nodes/test_node_ws_signals.py | 91 +++ .../core/api/inbound_email/__init__.py | 0 .../inbound_email/test_inbound_email_views.py | 355 ++++++++++++ .../core/inbound_email_test_utils.py | 63 +++ ...core_inbound_email_trigger_service_type.py | 341 +++++++++++ .../core/test_inbound_email_handler.py | 534 ++++++++++++++++++ .../core/test_inbound_email_receiver.py | 286 ++++++++++ ...by_email_trigger_that_starts_an_autom.json | 9 + deploy/all-in-one/Dockerfile | 5 + .../supervisor/default_baserow_env.sh | 5 + .../includes/disabled/email-receiver.conf | 17 + deploy/all-in-one/supervisor/start.sh | 15 + docker-compose.dev.yml | 33 ++ docker-compose.no-caddy.yml | 65 ++- docker-compose.yml | 54 +- docs/installation/configuration.md | 15 + .../install-with-docker-compose.md | 40 ++ docs/installation/install-with-docker.md | 36 ++ .../locale/en/LC_MESSAGES/django.po | 63 ++- justfile | 55 +- mox.just | 376 ++++++++++++ .../form/SimulateDispatchNodeForm.vue | 14 + .../workflow/WorkflowAddNodeMenu.vue | 1 + web-frontend/modules/automation/nodeTypes.js | 79 +++ web-frontend/modules/automation/plugin.js | 2 + web-frontend/modules/automation/realtime.js | 10 + .../store/automationWorkflowNode.js | 23 + .../core/assets/scss/components/all.scss | 1 + .../scss/components/sample_data_modal.scss | 10 + .../inbound_email_trigger_service_form.scss | 24 + .../core/components/SampleDataModal.vue | 55 +- .../core/components/SampleDataViewer.vue | 12 + web-frontend/modules/core/locales/en.json | 15 +- web-frontend/modules/core/serviceTypes.js | 17 + .../CoreInboundEmailTriggerServiceForm.vue | 125 ++++ .../modules/integrations/core/serviceTypes.js | 53 ++ .../modules/integrations/locales/en.json | 2 + web-frontend/modules/integrations/plugin.js | 5 + .../workflow/WorkflowAddNodeMenu.spec.js | 33 ++ .../test/unit/automation/nodeTypes.spec.js | 26 + .../automationWorkflowNodeRefetch.spec.js | 65 +++ .../core/components/sampleDataModal.spec.js | 102 ++++ .../inboundEmailTriggerServiceForm.spec.js | 165 ++++++ .../inboundEmailTriggerServiceType.spec.js | 41 ++ 76 files changed, 5417 insertions(+), 148 deletions(-) create mode 100755 backend/docker/generate-mox-config.sh create mode 100644 backend/src/baserow/contrib/automation/migrations/0038_coreinboundemailtriggernode.py create mode 100644 backend/src/baserow/contrib/integrations/core/api/inbound_email/__init__.py create mode 100644 backend/src/baserow/contrib/integrations/core/api/inbound_email/errors.py create mode 100644 backend/src/baserow/contrib/integrations/core/api/inbound_email/views.py create mode 100644 backend/src/baserow/contrib/integrations/core/inbound_email.py create mode 100644 backend/src/baserow/contrib/integrations/core/inbound_email_receiver.py create mode 100644 backend/src/baserow/contrib/integrations/migrations/0036_coreinboundemailtriggerservice.py create mode 100644 backend/tests/baserow/contrib/automation/nodes/test_node_ws_signals.py create mode 100644 backend/tests/baserow/contrib/integrations/core/api/inbound_email/__init__.py create mode 100644 backend/tests/baserow/contrib/integrations/core/api/inbound_email/test_inbound_email_views.py create mode 100644 backend/tests/baserow/contrib/integrations/core/inbound_email_test_utils.py create mode 100644 backend/tests/baserow/contrib/integrations/core/test_core_inbound_email_trigger_service_type.py create mode 100644 backend/tests/baserow/contrib/integrations/core/test_inbound_email_handler.py create mode 100644 backend/tests/baserow/contrib/integrations/core/test_inbound_email_receiver.py create mode 100644 changelog/entries/unreleased/feature/added_a_start_workflow_by_email_trigger_that_starts_an_autom.json create mode 100644 deploy/all-in-one/supervisor/includes/disabled/email-receiver.conf create mode 100644 mox.just create mode 100644 web-frontend/modules/core/assets/scss/components/services/inbound_email_trigger_service_form.scss create mode 100644 web-frontend/modules/integrations/core/components/services/CoreInboundEmailTriggerServiceForm.vue create mode 100644 web-frontend/test/unit/automation/store/automationWorkflowNodeRefetch.spec.js create mode 100644 web-frontend/test/unit/core/components/sampleDataModal.spec.js create mode 100644 web-frontend/test/unit/integrations/core/inboundEmailTriggerServiceForm.spec.js create mode 100644 web-frontend/test/unit/integrations/core/inboundEmailTriggerServiceType.spec.js diff --git a/.env.docker-dev.example b/.env.docker-dev.example index 7c6837ead4..69f9b84df5 100644 --- a/.env.docker-dev.example +++ b/.env.docker-dev.example @@ -22,6 +22,16 @@ COMPOSE_PROFILES=optional # BASEROW_ASSISTANT_PHOENIX_URL=http://phoenix:6006 # Only needed when pointing at an auth-enabled (team) Phoenix instance: # BASEROW_ASSISTANT_PHOENIX_API_KEY= +# Inbound email receiver (mox) for the "Start workflow by email" automation +# trigger, SMTP published on localhost:2025. Setting both variables below makes +# `just dc-dev up` enable the "inbound-email" profile and start the receiver +# automatically. +# (Native `just dev` reads the same two variables from .env.local instead.) +# BASEROW_INBOUND_EMAIL_DOMAIN=inbound.baserow.local +# BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET=change-me +# Where the receiver's SMTP port is published; keeps it on loopback and off port 25. +BASEROW_INBOUND_EMAIL_HOST_PUBLISH_IP=127.0.0.1 +BASEROW_INBOUND_EMAIL_HOST_SMTP_PORT=2025 SECRET_KEY=baserow # CHANGE THIS IN PRODUCTION! DATABASE_PASSWORD=baserow diff --git a/backend/Dockerfile b/backend/Dockerfile index adf63603e9..c1a58c5578 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -53,6 +53,21 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ chmod 0755 /usr/local/bin/wasmtime +# ============================================================================= +# Builder for mox (inbound SMTP receiver for the email trigger feature) +# ============================================================================= +FROM golang:1.25-bookworm AS mox-builder +ARG MOX_VERSION=v0.0.17 + +SHELL ["/bin/bash", "-o", "pipefail", "-c"] + +# `go install` verifies the module against the Go checksum database +# (sum.golang.org), so the pinned version is integrity-checked. +RUN CGO_ENABLED=0 GOFLAGS=-trimpath go install "github.com/mjl-/mox@${MOX_VERSION}" && \ + mv "$(go env GOPATH)/bin/mox" /usr/local/bin/mox && \ + chmod 0755 /usr/local/bin/mox + + # ============================================================================= # Builder for QuickJS-NG WASI runtime # ============================================================================= @@ -285,6 +300,7 @@ RUN groupadd --system --gid $GID ${DOCKER_USER} && \ COPY --from=tool-builder /usr/local/bin/su-exec /usr/local/bin/su-exec COPY --from=tool-builder /usr/bin/tini /usr/bin/tini COPY --from=wasmtime-builder /usr/local/bin/wasmtime /usr/local/bin/wasmtime +COPY --from=mox-builder /usr/local/bin/mox /usr/local/bin/mox COPY --from=quickjs-wasi-builder /usr/local/lib/baserow/qjs.wasm /usr/local/lib/baserow/qjs.wasm # hadolint ignore=DL3022 COPY --from=ghcr.io/astral-sh/uv:0.9.26 /uv /uvx /bin/ @@ -362,6 +378,7 @@ COPY --from=tool-builder /usr/local/bin/su-exec /usr/local/bin/su-exec COPY --from=tool-builder /usr/bin/tini /usr/bin/tini COPY --from=tool-builder /usr/bin/dos2unix /usr/local/bin/dos2unix COPY --from=wasmtime-builder /usr/local/bin/wasmtime /usr/local/bin/wasmtime +COPY --from=mox-builder /usr/local/bin/mox /usr/local/bin/mox COPY --from=quickjs-wasi-builder /usr/local/lib/baserow/qjs.wasm /usr/local/lib/baserow/qjs.wasm # hadolint ignore=DL3022 COPY --from=ghcr.io/astral-sh/uv:0.9.26 /uv /uvx /bin/ @@ -449,6 +466,7 @@ COPY ./backend/docker/mime.types /etc/ COPY --from=tool-builder /usr/local/bin/su-exec /usr/local/bin/su-exec COPY --from=tool-builder /usr/bin/tini /usr/bin/tini COPY --from=wasmtime-builder /usr/local/bin/wasmtime /usr/local/bin/wasmtime +COPY --from=mox-builder /usr/local/bin/mox /usr/local/bin/mox COPY --from=quickjs-wasi-builder /usr/local/lib/baserow/qjs.wasm /usr/local/lib/baserow/qjs.wasm RUN mkdir -p /baserow/media && chown -R $UID:$GID /baserow/ diff --git a/backend/docker/docker-entrypoint.sh b/backend/docker/docker-entrypoint.sh index 632f57bb4d..94ec2736fd 100755 --- a/backend/docker/docker-entrypoint.sh +++ b/backend/docker/docker-entrypoint.sh @@ -175,6 +175,11 @@ gunicorn-wsgi : Same as gunicorn but runs a wsgi server which does not sup celery-worker : Start the celery worker queue which runs important async tasks celery-exportworker : Start the celery worker queue which runs slower async tasks celery-beat : Start the celery beat service used to schedule periodic jobs +email-receiver : Start the mox mail server which receives inbound email for + the "Start workflow by email" automation trigger and forwards + it to the backend. Must run as root (mox drops privileges + itself). Idles until BASEROW_INBOUND_EMAIL_DOMAIN and + BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET are both set. HEALTHCHECK COMMANDS (exit with non zero when unhealthy, zero when healthy) backend-healthcheck : Checks the gunicorn/django-dev service health @@ -414,6 +419,59 @@ case "$1" in celery-flower) exec celery -A baserow flower "$@" ;; + email-receiver) + # Runs the mox mail server as the inbound SMTP receiver for the "Start + # workflow by email" automation trigger. Mox must be started as root; it + # binds its sockets and then drops privileges itself to the user + # configured by the generated config (default uid 9999). + export OTEL_SERVICE_NAME="email-receiver" + if [[ -z "${BASEROW_INBOUND_EMAIL_DOMAIN:-}" || -z "${BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET:-}" ]]; then + echo "Inbound email is not configured. Set BASEROW_INBOUND_EMAIL_DOMAIN" \ + "and BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET to enable the \"Start" \ + "workflow by email\" automation trigger. Idling until then." + exec tail -f /dev/null + fi + /baserow/backend/docker/generate-mox-config.sh + MOX_DATA_DIR="${BASEROW_INBOUND_EMAIL_DATA_DIR:-/baserow/data/mox}" + # Mox "fixes" the ownership and mode of its working directory on start. + # Run it from its own data directory so that never touches the backend + # code directory, which is a bind-mounted checkout in the dev stack. + cd "$MOX_DATA_DIR" + /usr/local/bin/mox -config "$MOX_DATA_DIR/config/mox.conf" serve & + mox_pid=$! + # A trapped signal interrupts the `wait` below straight away, so wait for + # mox inside the trap as well. Otherwise this script, and with it tini as + # PID 1, exits while mox is still shutting down and the kernel SIGKILLs it. + trap 'kill -TERM "$mox_pid" 2>/dev/null; wait "$mox_pid"' TERM INT + + # The backend's periodic sweep deletes handed-over messages through mox's + # web API, authenticating as the inbound account with + # BASEROW_INBOUND_EMAIL_RECEIVER_PASSWORD (the webhook secret by default). + # A password can only be set through the running server's control + # socket, so wait for it and (re)apply the password on every start. + for _ in $(seq 1 60); do + [ -S "$MOX_DATA_DIR/data/ctl" ] && break + sleep 0.5 + done + if printf '%s' "${BASEROW_INBOUND_EMAIL_RECEIVER_PASSWORD:-$BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET}" \ + | /usr/local/bin/mox -config "$MOX_DATA_DIR/config/mox.conf" setaccountpassword inbound; then + echo "Inbound account web API password applied." + else + echo "WARNING: could not set the inbound account's web API password;" \ + "the backend's periodic message sweep will fail until this is fixed." >&2 + fi + + wait "$mox_pid" || mox_status=$? + exit "${mox_status:-0}" + ;; + email-receiver-healthcheck) + echo "Running email receiver healthcheck..." + if [[ -z "${BASEROW_INBOUND_EMAIL_DOMAIN:-}" || -z "${BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET:-}" ]]; then + # Inbound email is disabled and the service is idling on purpose. + exit 0 + fi + exec bash -c "exec 3<>'/dev/tcp/127.0.0.1/${BASEROW_INBOUND_EMAIL_SMTP_PORT:-25}'" + ;; watch-py) # Ensure we watch all possible python source code locations for changes. directory_args='' diff --git a/backend/docker/generate-mox-config.sh b/backend/docker/generate-mox-config.sh new file mode 100755 index 0000000000..bd30aabda7 --- /dev/null +++ b/backend/docker/generate-mox-config.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# Generates a minimal, inbound-only mox configuration for the `email-receiver` +# role from BASEROW_INBOUND_EMAIL_* environment variables. Mox receives email +# for {token}@$BASEROW_INBOUND_EMAIL_DOMAIN addresses and POSTs its incoming +# delivery webhook to the Baserow backend, which dispatches the matching +# "Start workflow by email" automation triggers. +# +# The generated config lives inside the email receiver's persistent data +# directory. Mox's message store and webhook retry queue live there too; the +# at-least-once webhook delivery guarantee depends on that directory surviving +# container restarts. +# +# NOTE: mox config files are in 'sconf' format: indentation MUST be tabs. +set -euo pipefail + +DATA_DIR="${BASEROW_INBOUND_EMAIL_DATA_DIR:-/baserow/data/mox}" +CONFIG_DIR="$DATA_DIR/config" + +DOMAIN="${BASEROW_INBOUND_EMAIL_DOMAIN:?BASEROW_INBOUND_EMAIL_DOMAIN must be set to run the email-receiver}" +WEBHOOK_SECRET="${BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET:?BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET must be set to run the email-receiver}" +WEBHOOK_URL="${BASEROW_INBOUND_EMAIL_WEBHOOK_URL:-}" +if [ -z "$WEBHOOK_URL" ]; then + BACKEND_URL="${PRIVATE_BACKEND_URL:-${PUBLIC_BACKEND_URL:-}}" + : "${BACKEND_URL:?Set PRIVATE_BACKEND_URL or PUBLIC_BACKEND_URL}" + WEBHOOK_URL="${BACKEND_URL%/}/api/inbound-email/" +fi +SMTP_HOSTNAME="${BASEROW_INBOUND_EMAIL_SMTP_HOSTNAME:-$DOMAIN}" +SMTP_PORT="${BASEROW_INBOUND_EMAIL_SMTP_PORT:-25}" +TLS_MODE="${BASEROW_INBOUND_EMAIL_TLS_MODE:-self-signed}" +# Mox must be started as root (it binds its sockets as root and then drops +# privileges itself); this is the unprivileged uid it drops to. +MOX_USER="${BASEROW_INBOUND_EMAIL_MOX_USER:-9999}" +# The largest raw message (attachments included) mox accepts. Larger messages +# are refused during SMTP delivery and bounce back to the sender. +MAX_MESSAGE_SIZE_MB="${BASEROW_INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB:-25}" +# Plain-HTTP web API (never published) through which the backend's periodic +# sweep deletes messages it has already received, since mox has no retention +# setting of its own. It gets its own listener so its bind address can differ +# from the SMTP one: 0.0.0.0 lets the backend container reach it over the +# Compose network, while the all-in-one image binds it to 127.0.0.1 because +# the backend runs in the same container. The backend authenticates as this +# explicit address with BASEROW_INBOUND_EMAIL_RECEIVER_PASSWORD, which defaults +# to the webhook secret (the entrypoint applies it after mox starts); the +# localpart must match INBOUND_EMAIL_WEBAPI_LOCALPART in +# inbound_email_receiver.py. +WEBAPI_PORT="${BASEROW_INBOUND_EMAIL_WEBAPI_PORT:-8880}" +WEBAPI_BIND_IP="${BASEROW_INBOUND_EMAIL_WEBAPI_BIND_IP:-0.0.0.0}" +WEBAPI_LOCALPART="webapi" +WEBAPI_PASSWORD="${BASEROW_INBOUND_EMAIL_RECEIVER_PASSWORD:-$WEBHOOK_SECRET}" +if [ "${#WEBAPI_PASSWORD}" -lt 8 ]; then + echo "WARNING: the web API password (BASEROW_INBOUND_EMAIL_RECEIVER_PASSWORD, or BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET when unset) is shorter than 8 characters; mox will refuse it and received messages will not be deleted from the receiver." >&2 +fi +if ! [[ "$MAX_MESSAGE_SIZE_MB" =~ ^[0-9]+$ ]] || [[ "$MAX_MESSAGE_SIZE_MB" -eq 0 ]]; then + echo "BASEROW_INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB must be a positive whole number of MB, got: $MAX_MESSAGE_SIZE_MB" >&2 + exit 1 +fi +MAX_MESSAGE_SIZE=$((MAX_MESSAGE_SIZE_MB * 1024 * 1024)) + +mkdir -p "$CONFIG_DIR" "$DATA_DIR/data" + +case "$TLS_MODE" in + self-signed) + # Sending mail servers use opportunistic STARTTLS and do not validate the + # certificate, so a self-signed certificate still upgrades inbound + # connections to TLS. Use `manual` with a real certificate where possible. + TLS_CERT_FILE="$CONFIG_DIR/selfsigned.crt" + TLS_KEY_FILE="$CONFIG_DIR/selfsigned.key" + if [[ ! -f "$TLS_CERT_FILE" || ! -f "$TLS_KEY_FILE" ]]; then + echo "Generating self-signed TLS certificate for $SMTP_HOSTNAME..." + MOX_TLS_HOSTNAME="$SMTP_HOSTNAME" \ + MOX_TLS_CERT_FILE="$TLS_CERT_FILE" \ + MOX_TLS_KEY_FILE="$TLS_KEY_FILE" \ + python3 - <<'PYTHON' +import os +from datetime import datetime, timedelta, timezone + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.x509.oid import NameOID + +hostname = os.environ["MOX_TLS_HOSTNAME"] +key = ec.generate_private_key(ec.SECP256R1()) +name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, hostname)]) +now = datetime.now(timezone.utc) +cert = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(days=1)) + .not_valid_after(now + timedelta(days=3650)) + .add_extension( + x509.SubjectAlternativeName([x509.DNSName(hostname)]), critical=False + ) + .sign(key, hashes.SHA256()) +) +with open(os.environ["MOX_TLS_KEY_FILE"], "wb") as f: + f.write( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) +with open(os.environ["MOX_TLS_CERT_FILE"], "wb") as f: + f.write(cert.public_bytes(serialization.Encoding.PEM)) +PYTHON + fi + ;; + manual) + TLS_CERT_FILE="${BASEROW_INBOUND_EMAIL_TLS_CERT_FILE:?BASEROW_INBOUND_EMAIL_TLS_CERT_FILE must be set when BASEROW_INBOUND_EMAIL_TLS_MODE=manual}" + TLS_KEY_FILE="${BASEROW_INBOUND_EMAIL_TLS_KEY_FILE:?BASEROW_INBOUND_EMAIL_TLS_KEY_FILE must be set when BASEROW_INBOUND_EMAIL_TLS_MODE=manual}" + ;; + *) + echo "Unsupported BASEROW_INBOUND_EMAIL_TLS_MODE: $TLS_MODE (expected self-signed or manual)" >&2 + exit 1 + ;; +esac + +cat > "$CONFIG_DIR/mox.conf" < "$CONFIG_DIR/domains.conf" < bool: + return is_inbound_email_configured() + def to_representation(self, instance): representation = super().to_representation(instance) # TODO Remove in a future release once email_verification is null=False diff --git a/backend/src/baserow/config/settings/base.py b/backend/src/baserow/config/settings/base.py index aac47fb7e0..8c3aec6983 100644 --- a/backend/src/baserow/config/settings/base.py +++ b/backend/src/baserow/config/settings/base.py @@ -998,6 +998,36 @@ INTEGRATION_ALLOW_SMTP_SERVICE_TO_USE_INSTANCE_SETTINGS = str_to_bool( os.getenv("BASEROW_INTEGRATION_ALLOW_SMTP_SERVICE_TO_USE_INSTANCE_SETTINGS", "true") ) +# The domain used to generate inbound email addresses for email triggers, e.g. +# "inbound.baserow.io" results in addresses like "{token}@inbound.baserow.io". +# When empty, the email trigger feature is not configured on this instance. +INBOUND_EMAIL_DOMAIN = os.getenv("BASEROW_INBOUND_EMAIL_DOMAIN", "") +# The shared secret the inbound mail server must send in the Authorization +# header when delivering inbound email webhooks to this instance. When empty, +# the inbound email webhook endpoint rejects all requests. +INBOUND_EMAIL_WEBHOOK_SECRET = os.getenv("BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET", "") +# The password the backend authenticates with when deleting handed-over messages +# through the bundled mail server's web API. Empty means the webhook secret is +# used (see `inbound_email_receiver.py`), so one secret configures the whole +# feature; set it to keep the secret that travels in every webhook request out +# of the receiver's credentials. +INBOUND_EMAIL_RECEIVER_PASSWORD = os.getenv( + "BASEROW_INBOUND_EMAIL_RECEIVER_PASSWORD", "" +) +# The largest raw email, in MB, the bundled inbound mail server accepts. The +# limit itself is enforced by the mail server (see generate-mox-config.sh); it +# is mirrored here so it can be shown next to the trigger's address. +INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB = int( + os.getenv("BASEROW_INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB") or 25 +) +# Where the backend reaches the bundled inbound mail server's web API. Mox keeps +# every accepted message on disk and has no retention setting, so the backend +# deletes each message through this API shortly after receiving its webhook. +# Empty disables that (see `inbound_email_receiver.py`). +INBOUND_EMAIL_RECEIVER_URL = os.getenv("BASEROW_INBOUND_EMAIL_RECEIVER_URL", "").rstrip( + "/" +) + AUTOMATION_HISTORY_PAGE_SIZE_LIMIT = int( os.getenv("BASEROW_AUTOMATION_HISTORY_PAGE_SIZE_LIMIT", 100) ) diff --git a/backend/src/baserow/config/settings/dev.py b/backend/src/baserow/config/settings/dev.py index f7d79062c9..8f1dc8d80c 100755 --- a/backend/src/baserow/config/settings/dev.py +++ b/backend/src/baserow/config/settings/dev.py @@ -89,3 +89,12 @@ try: from .local import * # noqa: F403, F401 except ImportError: pass + +# Containers in the dev stack reach a natively running backend (`just dev`) +# through Docker's host alias, so their requests arrive with a Host header of +# `host.docker.internal:8000`, which Django refuses with a 400 (DisallowedHost) +# unless the name is allowed. The opt-in inbound email receiver started by +# `just mox up` posts its webhooks that way. Dev only: production deployments +# reach the backend through PRIVATE_BACKEND_URL, whose hostname is allowed in +# the base settings. +ALLOWED_HOSTS.append("host.docker.internal") # noqa: F405 diff --git a/backend/src/baserow/contrib/automation/apps.py b/backend/src/baserow/contrib/automation/apps.py index 3f892dc45b..a10081b99a 100644 --- a/backend/src/baserow/contrib/automation/apps.py +++ b/backend/src/baserow/contrib/automation/apps.py @@ -23,6 +23,7 @@ class AutomationConfig(AppConfig): CoreGotoActionNodeType, CoreHttpRequestNodeType, CoreHTTPTriggerNodeType, + CoreInboundEmailTriggerNodeType, CoreIteratorNodeType, CoreManualTriggerNodeType, CorePeriodicTriggerNodeType, @@ -196,6 +197,7 @@ class AutomationConfig(AppConfig): ) automation_node_type_registry.register(CorePeriodicTriggerNodeType()) automation_node_type_registry.register(CoreHTTPTriggerNodeType()) + automation_node_type_registry.register(CoreInboundEmailTriggerNodeType()) automation_node_type_registry.register(CoreManualTriggerNodeType()) automation_node_type_registry.register(AIAgentActionNodeType()) automation_node_type_registry.register(SlackWriteMessageActionNodeType()) diff --git a/backend/src/baserow/contrib/automation/migrations/0038_coreinboundemailtriggernode.py b/backend/src/baserow/contrib/automation/migrations/0038_coreinboundemailtriggernode.py new file mode 100644 index 0000000000..c16de687f1 --- /dev/null +++ b/backend/src/baserow/contrib/automation/migrations/0038_coreinboundemailtriggernode.py @@ -0,0 +1,24 @@ +# Generated by Django 5.2.15 on 2026-07-15 14:01 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('automation', '0037_automationworkflowhistory_cancellation_requested_by_and_more'), + ] + + operations = [ + migrations.CreateModel( + name='CoreInboundEmailTriggerNode', + fields=[ + ('automationnode_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='automation.automationnode')), + ], + options={ + 'abstract': False, + }, + bases=('automation.automationnode',), + ), + ] diff --git a/backend/src/baserow/contrib/automation/nodes/models.py b/backend/src/baserow/contrib/automation/nodes/models.py index a3c264911a..a60dfd3813 100644 --- a/backend/src/baserow/contrib/automation/nodes/models.py +++ b/backend/src/baserow/contrib/automation/nodes/models.py @@ -149,6 +149,9 @@ class CorePeriodicTriggerNode(AutomationTriggerNode): ... class CoreHTTPTriggerNode(AutomationTriggerNode): ... +class CoreInboundEmailTriggerNode(AutomationTriggerNode): ... + + class CoreManualTriggerNode(AutomationTriggerNode): ... diff --git a/backend/src/baserow/contrib/automation/nodes/node_types.py b/backend/src/baserow/contrib/automation/nodes/node_types.py index 62e579590c..ba0abe2177 100644 --- a/backend/src/baserow/contrib/automation/nodes/node_types.py +++ b/backend/src/baserow/contrib/automation/nodes/node_types.py @@ -25,6 +25,7 @@ from baserow.contrib.automation.nodes.models import ( CoreGotoActionNode, CoreHTTPRequestActionNode, CoreHTTPTriggerNode, + CoreInboundEmailTriggerNode, CoreIteratorActionNode, CoreManualTriggerNode, CorePeriodicTriggerNode, @@ -50,12 +51,16 @@ from baserow.contrib.automation.nodes.signals import automation_node_updated from baserow.contrib.automation.workflows.constants import WorkflowState from baserow.contrib.automation.workflows.models import AutomationWorkflow from baserow.contrib.integrations.ai.service_types import AIAgentServiceType +from baserow.contrib.integrations.core.inbound_email import ( + is_inbound_email_configured, +) from baserow.contrib.integrations.core.models import CoreGotoService from baserow.contrib.integrations.core.service_types import ( CoreCSVFileReaderServiceType, CoreGotoServiceType, CoreHTTPRequestServiceType, CoreHTTPTriggerServiceType, + CoreInboundEmailTriggerServiceType, CoreIteratorServiceType, CoreManualTriggerServiceType, CorePeriodicServiceType, @@ -781,6 +786,19 @@ class CoreHTTPTriggerNodeType(AutomationNodeTriggerType): service_type = CoreHTTPTriggerServiceType.type +class CoreInboundEmailTriggerNodeType(AutomationNodeTriggerType): + display_name = _("Email trigger") + type = "email_trigger" + model_class = CoreInboundEmailTriggerNode + service_type = CoreInboundEmailTriggerServiceType.type + + def is_deactivated(self, workspace) -> bool: + # Instance-wide (the workspace is irrelevant): the trigger is withheld + # until the domain, the webhook secret and the receiver URL are all + # configured. See `is_inbound_email_configured` for why each matters. + return not is_inbound_email_configured() + + class CoreManualTriggerNodeType(AutomationNodeTriggerType): type = "manual" model_class = CoreManualTriggerNode diff --git a/backend/src/baserow/contrib/automation/nodes/ws/signals.py b/backend/src/baserow/contrib/automation/nodes/ws/signals.py index 632b5eb192..a2174bc65b 100644 --- a/backend/src/baserow/contrib/automation/nodes/ws/signals.py +++ b/backend/src/baserow/contrib/automation/nodes/ws/signals.py @@ -1,4 +1,7 @@ +import json + from django.contrib.auth.models import AbstractUser +from django.core.serializers.json import DjangoJSONEncoder from django.db import transaction from django.dispatch import receiver @@ -20,6 +23,35 @@ from baserow.contrib.automation.workflows.object_scopes import ( ) from baserow.ws.tasks import broadcast_to_permitted_users +# Channel-layer messages are forwarded verbatim to every websocket. Daphne, which +# serves the dev server, refuses frames over 1 MiB and closes the socket, and the +# replay mechanism then re-sends the same event on reconnect, so one oversized +# event can wedge a client. A node's sample data alone can exceed that (the email +# trigger may carry two 1 MiB bodies), so oversized node events drop the sample +# data and ask the client to refetch the node over HTTP instead. Same bound and +# headroom as the AI provider updates in `baserow.ws.tasks`. +AUTOMATION_NODE_EVENT_MAX_BYTES = 900 * 1024 + + +def bounded_node_event(event: dict) -> dict: + """ + Returns the event unchanged when it fits comfortably in a websocket frame, + otherwise a copy whose node carries no sample data and a `requires_refresh` + flag telling the client to reload the node over HTTP. + """ + + encoded = json.dumps( + event, cls=DjangoJSONEncoder, ensure_ascii=False, separators=(",", ":") + ).encode("utf-8") + if len(encoded) <= AUTOMATION_NODE_EVENT_MAX_BYTES: + return event + + node = dict(event["node"]) + service = node.get("service") + if isinstance(service, dict): + node["service"] = {**service, "sample_data": None} + return {**event, "node": node, "requires_refresh": True} + @receiver(automation_node_created) def node_created(sender, node: AutomationNode, user: AbstractUser, **kwargs): @@ -29,10 +61,12 @@ def node_created(sender, node: AutomationNode, user: AbstractUser, **kwargs): ReadAutomationNodeOperationType.type, AutomationNodeObjectScopeType.type, node.id, - { - "type": "automation_node_created", - "node": AutomationNodeSerializer(node).data, - }, + bounded_node_event( + { + "type": "automation_node_created", + "node": AutomationNodeSerializer(node).data, + } + ), getattr(user, "web_socket_id", None), ) ) @@ -66,10 +100,12 @@ def node_updated(sender, node: AutomationNode, user: AbstractUser, **kwargs): ReadAutomationNodeOperationType.type, AutomationNodeObjectScopeType.type, node.id, - { - "type": "automation_node_updated", - "node": AutomationNodeSerializer(node).data, - }, + bounded_node_event( + { + "type": "automation_node_updated", + "node": AutomationNodeSerializer(node).data, + } + ), getattr(user, "web_socket_id", None), ) ) diff --git a/backend/src/baserow/contrib/builder/locale/en/LC_MESSAGES/django.po b/backend/src/baserow/contrib/builder/locale/en/LC_MESSAGES/django.po index eb0036077c..e14a408134 100644 --- a/backend/src/baserow/contrib/builder/locale/en/LC_MESSAGES/django.po +++ b/backend/src/baserow/contrib/builder/locale/en/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-08-26 15:25+0000\n" +"POT-Creation-Date: 2026-09-11 12:44+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -53,12 +53,54 @@ msgstr "" msgid "Last name" msgstr "" -#: src/baserow/contrib/builder/data_providers/data_provider_types.py:650 +#: src/baserow/contrib/builder/data_providers/data_provider_types.py:656 #, python-format msgid "%(user_source_name)s member" msgstr "" -#: src/baserow/contrib/builder/data_sources/service.py:173 +#: src/baserow/contrib/builder/data_sources/actions.py:29 +#: src/baserow/contrib/builder/workflow_actions/actions.py:36 +#, python-format +msgid "of page (%(page_id)s) in builder \"%(builder_name)s\" (%(builder_id)s)." +msgstr "" + +#: src/baserow/contrib/builder/data_sources/actions.py:50 +msgid "Create data source" +msgstr "" + +#: src/baserow/contrib/builder/data_sources/actions.py:51 +#, python-format +msgid "Data source (%(data_source_id)s) created" +msgstr "" + +#: src/baserow/contrib/builder/data_sources/actions.py:114 +msgid "Update data source" +msgstr "" + +#: src/baserow/contrib/builder/data_sources/actions.py:115 +#, python-format +msgid "Data source (%(data_source_id)s) updated" +msgstr "" + +#: src/baserow/contrib/builder/data_sources/actions.py:206 +msgid "Delete data source" +msgstr "" + +#: src/baserow/contrib/builder/data_sources/actions.py:207 +#, python-format +msgid "Data source (%(data_source_id)s) deleted" +msgstr "" + +#: src/baserow/contrib/builder/data_sources/actions.py:262 +msgid "Move data source" +msgstr "" + +#: src/baserow/contrib/builder/data_sources/actions.py:263 +#, python-format +msgid "Data source (%(data_source_id)s) moved" +msgstr "" + +#: src/baserow/contrib/builder/data_sources/service.py:176 msgid "Data source" msgstr "" @@ -107,93 +149,93 @@ msgstr "" msgid "Element (%(element_id)s) moved" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:138 +#: src/baserow/contrib/builder/elements/element_types.py:142 msgid "Column" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:334 +#: src/baserow/contrib/builder/elements/element_types.py:351 msgid "Form" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:406 +#: src/baserow/contrib/builder/elements/element_types.py:426 msgid "Container" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:418 +#: src/baserow/contrib/builder/elements/element_types.py:438 msgid "Table" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:483 +#: src/baserow/contrib/builder/elements/element_types.py:503 msgid "Repeat" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:551 +#: src/baserow/contrib/builder/elements/element_types.py:571 msgid "Record selector" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:800 +#: src/baserow/contrib/builder/elements/element_types.py:825 msgid "Heading" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:867 +#: src/baserow/contrib/builder/elements/element_types.py:892 msgid "Text" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:1089 +#: src/baserow/contrib/builder/elements/element_types.py:1114 msgid "Link" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:1227 +#: src/baserow/contrib/builder/elements/element_types.py:1252 msgid "Image" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:1391 +#: src/baserow/contrib/builder/elements/element_types.py:1416 msgid "Rating" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:1438 +#: src/baserow/contrib/builder/elements/element_types.py:1463 msgid "Rating input" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:1524 +#: src/baserow/contrib/builder/elements/element_types.py:1549 msgid "Input text" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:1664 +#: src/baserow/contrib/builder/elements/element_types.py:1689 msgid "Button" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:1709 +#: src/baserow/contrib/builder/elements/element_types.py:1737 msgid "Checkbox" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:1783 +#: src/baserow/contrib/builder/elements/element_types.py:1811 msgid "Choice" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:2096 +#: src/baserow/contrib/builder/elements/element_types.py:2124 msgid "Iframe" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:2168 +#: src/baserow/contrib/builder/elements/element_types.py:2196 msgid "Date time picker" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:2312 +#: src/baserow/contrib/builder/elements/element_types.py:2340 msgid "Shared header" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:2322 +#: src/baserow/contrib/builder/elements/element_types.py:2350 msgid "Shared footer" msgstr "" -#: src/baserow/contrib/builder/elements/element_types.py:2332 +#: src/baserow/contrib/builder/elements/element_types.py:2360 msgid "Menu" msgstr "" -#: src/baserow/contrib/builder/elements/mixins.py:707 -#: src/baserow/contrib/builder/elements/mixins.py:712 -#: src/baserow/contrib/builder/elements/mixins.py:717 +#: src/baserow/contrib/builder/elements/mixins.py:744 +#: src/baserow/contrib/builder/elements/mixins.py:749 +#: src/baserow/contrib/builder/elements/mixins.py:754 #, python-format msgid "Column %(count)s" msgstr "" @@ -201,3 +243,89 @@ msgstr "" #: src/baserow/contrib/builder/elements/registries.py:68 msgid "Unnamed element" msgstr "" + +#: src/baserow/contrib/builder/pages/actions.py:24 +#, python-format +msgid "in builder \"%(builder_name)s\" (%(builder_id)s)." +msgstr "" + +#: src/baserow/contrib/builder/pages/actions.py:30 +msgid "Create page" +msgstr "" + +#: src/baserow/contrib/builder/pages/actions.py:31 +#, python-format +msgid "Page \"%(page_name)s\" (%(page_id)s) created" +msgstr "" + +#: src/baserow/contrib/builder/pages/actions.py:86 +msgid "Update page" +msgstr "" + +#: src/baserow/contrib/builder/pages/actions.py:87 +#, python-format +msgid "Page \"%(page_name)s\" (%(page_id)s) updated" +msgstr "" + +#: src/baserow/contrib/builder/pages/actions.py:141 +msgid "Delete page" +msgstr "" + +#: src/baserow/contrib/builder/pages/actions.py:142 +#, python-format +msgid "Page \"%(page_name)s\" (%(page_id)s) deleted" +msgstr "" + +#: src/baserow/contrib/builder/pages/actions.py:185 +msgid "Duplicate page" +msgstr "" + +#: src/baserow/contrib/builder/pages/actions.py:187 +#, python-format +msgid "" +"Page \"%(page_name)s\" (%(page_id)s) duplicated from " +"\"%(original_page_name)s\" (%(original_page_id)s)" +msgstr "" + +#: src/baserow/contrib/builder/pages/actions.py:251 +msgid "Order pages" +msgstr "" + +#: src/baserow/contrib/builder/pages/actions.py:252 +msgid "Pages ordered" +msgstr "" + +#: src/baserow/contrib/builder/workflow_actions/actions.py:57 +msgid "Create workflow action" +msgstr "" + +#: src/baserow/contrib/builder/workflow_actions/actions.py:58 +#, python-format +msgid "Workflow action (%(workflow_action_id)s) created" +msgstr "" + +#: src/baserow/contrib/builder/workflow_actions/actions.py:120 +msgid "Update workflow action" +msgstr "" + +#: src/baserow/contrib/builder/workflow_actions/actions.py:121 +#, python-format +msgid "Workflow action (%(workflow_action_id)s) updated" +msgstr "" + +#: src/baserow/contrib/builder/workflow_actions/actions.py:188 +msgid "Delete workflow action" +msgstr "" + +#: src/baserow/contrib/builder/workflow_actions/actions.py:189 +#, python-format +msgid "Workflow action (%(workflow_action_id)s) deleted" +msgstr "" + +#: src/baserow/contrib/builder/workflow_actions/actions.py:244 +msgid "Order workflow actions" +msgstr "" + +#: src/baserow/contrib/builder/workflow_actions/actions.py:245 +msgid "Workflow actions ordered" +msgstr "" diff --git a/backend/src/baserow/contrib/database/locale/en/LC_MESSAGES/django.po b/backend/src/baserow/contrib/database/locale/en/LC_MESSAGES/django.po index 6cc3c6148b..2beb28a6af 100644 --- a/backend/src/baserow/contrib/database/locale/en/LC_MESSAGES/django.po +++ b/backend/src/baserow/contrib/database/locale/en/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-08-26 15:25+0000\n" +"POT-Creation-Date: 2026-09-11 12:44+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -69,7 +69,7 @@ msgid "" "\"%(airtable_share_id)s\"" msgstr "" -#: src/baserow/contrib/database/application_types.py:320 +#: src/baserow/contrib/database/application_types.py:411 msgid "Table" msgstr "" @@ -196,8 +196,8 @@ msgid "" "%(new_primary_field_name)s" msgstr "" -#: src/baserow/contrib/database/fields/models.py:494 -#: src/baserow/contrib/database/fields/models.py:706 +#: src/baserow/contrib/database/fields/models.py:493 +#: src/baserow/contrib/database/fields/models.py:705 msgid "The format of the duration." msgstr "" @@ -600,100 +600,100 @@ msgid "" "into view \"%(view_name)s\" (%(view_id)s)" msgstr "" -#: src/baserow/contrib/database/views/actions.py:1736 +#: src/baserow/contrib/database/views/actions.py:1742 msgid "Delete view" msgstr "" -#: src/baserow/contrib/database/views/actions.py:1737 +#: src/baserow/contrib/database/views/actions.py:1743 #, python-format msgid "View \"%(view_name)s\" (%(view_id)s) deleted" msgstr "" -#: src/baserow/contrib/database/views/actions.py:1799 +#: src/baserow/contrib/database/views/actions.py:1805 msgid "Create decoration" msgstr "" -#: src/baserow/contrib/database/views/actions.py:1800 +#: src/baserow/contrib/database/views/actions.py:1806 #, python-format msgid "View decoration %(decorator_id)s created" msgstr "" -#: src/baserow/contrib/database/views/actions.py:1904 +#: src/baserow/contrib/database/views/actions.py:1910 msgid "Update decoration" msgstr "" -#: src/baserow/contrib/database/views/actions.py:1905 +#: src/baserow/contrib/database/views/actions.py:1911 #, python-format msgid "View decoration %(decorator_id)s updated" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2042 +#: src/baserow/contrib/database/views/actions.py:2048 msgid "Delete decoration" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2043 +#: src/baserow/contrib/database/views/actions.py:2049 #, python-format msgid "View decoration %(decorator_id)s deleted" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2139 +#: src/baserow/contrib/database/views/actions.py:2145 msgid "Create a view group" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2140 +#: src/baserow/contrib/database/views/actions.py:2146 #, python-format msgid "View grouped on field \"%(field_name)s\" (%(field_id)s)" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2245 +#: src/baserow/contrib/database/views/actions.py:2251 msgid "Update a view group" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2246 +#: src/baserow/contrib/database/views/actions.py:2252 #, python-format msgid "View group by updated on field \"%(field_name)s\" (%(field_id)s)" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2395 +#: src/baserow/contrib/database/views/actions.py:2401 msgid "Delete a view group" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2396 +#: src/baserow/contrib/database/views/actions.py:2402 #, python-format msgid "View group by deleted from field \"%(field_name)s\" (%(field_id)s)" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2494 +#: src/baserow/contrib/database/views/actions.py:2500 msgid "Prioritize view group bys" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2495 +#: src/baserow/contrib/database/views/actions.py:2501 msgid "View group bys priority changed" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2570 +#: src/baserow/contrib/database/views/actions.py:2576 msgid "Submit form" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2571 +#: src/baserow/contrib/database/views/actions.py:2577 #, python-format msgid "Row (%(row_id)s) created via form submission" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2728 +#: src/baserow/contrib/database/views/actions.py:2734 msgid "Edit form row" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2729 +#: src/baserow/contrib/database/views/actions.py:2735 #, python-format msgid "Row (%(row_id)s) updated via form edit" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2808 +#: src/baserow/contrib/database/views/actions.py:2814 msgid "Update view default values" msgstr "" -#: src/baserow/contrib/database/views/actions.py:2809 +#: src/baserow/contrib/database/views/actions.py:2815 #, python-format msgid "Default row values updated for view (%(view_name)s)" msgstr "" diff --git a/backend/src/baserow/contrib/integrations/apps.py b/backend/src/baserow/contrib/integrations/apps.py index 85cb330db1..39ebca8c80 100644 --- a/backend/src/baserow/contrib/integrations/apps.py +++ b/backend/src/baserow/contrib/integrations/apps.py @@ -71,6 +71,7 @@ class IntegrationsConfig(AppConfig): CoreGotoServiceType, CoreHTTPRequestServiceType, CoreHTTPTriggerServiceType, + CoreInboundEmailTriggerServiceType, CoreIteratorServiceType, CoreManualTriggerServiceType, CorePeriodicServiceType, @@ -84,6 +85,7 @@ class IntegrationsConfig(AppConfig): service_type_registry.register(CoreRouterServiceType()) service_type_registry.register(CoreGotoServiceType()) service_type_registry.register(CoreHTTPTriggerServiceType()) + service_type_registry.register(CoreInboundEmailTriggerServiceType()) service_type_registry.register(CoreManualTriggerServiceType()) service_type_registry.register(CoreIteratorServiceType()) service_type_registry.register(CorePeriodicServiceType()) diff --git a/backend/src/baserow/contrib/integrations/core/api/inbound_email/__init__.py b/backend/src/baserow/contrib/integrations/core/api/inbound_email/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/backend/src/baserow/contrib/integrations/core/api/inbound_email/errors.py b/backend/src/baserow/contrib/integrations/core/api/inbound_email/errors.py new file mode 100644 index 0000000000..7b518cbdb1 --- /dev/null +++ b/backend/src/baserow/contrib/integrations/core/api/inbound_email/errors.py @@ -0,0 +1,7 @@ +from rest_framework.status import HTTP_400_BAD_REQUEST + +ERROR_INVALID_INBOUND_EMAIL_PAYLOAD = ( + "ERROR_INVALID_INBOUND_EMAIL_PAYLOAD", + HTTP_400_BAD_REQUEST, + "The inbound email payload is malformed.", +) diff --git a/backend/src/baserow/contrib/integrations/core/api/inbound_email/views.py b/backend/src/baserow/contrib/integrations/core/api/inbound_email/views.py new file mode 100644 index 0000000000..c47dd592a5 --- /dev/null +++ b/backend/src/baserow/contrib/integrations/core/api/inbound_email/views.py @@ -0,0 +1,66 @@ +import hmac + +from django.conf import settings +from django.db import transaction + +from drf_spectacular.utils import extend_schema +from rest_framework.permissions import AllowAny +from rest_framework.response import Response +from rest_framework.status import HTTP_401_UNAUTHORIZED +from rest_framework.views import APIView + +from baserow.api.decorators import map_exceptions +from baserow.api.schemas import get_error_schema +from baserow.contrib.integrations.core.api.inbound_email.errors import ( + ERROR_INVALID_INBOUND_EMAIL_PAYLOAD, +) +from baserow.contrib.integrations.core.exceptions import InvalidInboundEmailPayload +from baserow.contrib.integrations.core.inbound_email import InboundEmailHandler + +INBOUND_EMAIL_TAG = "Inbound email" + + +class CoreInboundEmailWebhookView(APIView): + """ + Receives incoming email delivery webhooks from the inbound mail server and + dispatches the matching email trigger services. The request is + authenticated with the shared secret configured in + `BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET`, which the mail server must send in + the Authorization header. + """ + + permission_classes = (AllowAny,) + http_method_names = ["post"] + + @extend_schema( + operation_id="handle_inbound_email_webhook", + tags=[INBOUND_EMAIL_TAG], + description="Receives and handles an inbound email webhook request " + "from the inbound mail server.", + responses={ + 200: None, + 400: get_error_schema(["ERROR_INVALID_INBOUND_EMAIL_PAYLOAD"]), + 401: None, + }, + ) + @transaction.atomic + @map_exceptions( + { + InvalidInboundEmailPayload: ERROR_INVALID_INBOUND_EMAIL_PAYLOAD, + } + ) + def post(self, request, *args, **kwargs): + secret = settings.INBOUND_EMAIL_WEBHOOK_SECRET + provided = request.headers.get("Authorization", "") + + # When no secret is configured the endpoint is disabled; never fall + # through to comparing against an empty string. + if not secret or not hmac.compare_digest(provided.encode(), secret.encode()): + return Response( + {"error": "ERROR_INVALID_INBOUND_EMAIL_SECRET"}, + status=HTTP_401_UNAUTHORIZED, + ) + + status = InboundEmailHandler().handle_webhook_payload(request.data) + + return Response({"status": status}) diff --git a/backend/src/baserow/contrib/integrations/core/exceptions.py b/backend/src/baserow/contrib/integrations/core/exceptions.py index 170153fe66..6b17aabe69 100644 --- a/backend/src/baserow/contrib/integrations/core/exceptions.py +++ b/backend/src/baserow/contrib/integrations/core/exceptions.py @@ -17,3 +17,21 @@ class CoreHTTPTriggerServiceMethodNotAllowed(Exception): """When the specified method isn't allowed for the service.""" pass + + +class CoreInboundEmailTriggerServiceDoesNotExist(Exception): + """When no email trigger service matches the provided token.""" + + def __init__(self, token: str, *args, **kwargs): + self.token = token + super().__init__( + f"No email trigger service matches the token {token}.", + *args, + **kwargs, + ) + + +class InvalidInboundEmailPayload(Exception): + """When an inbound email webhook payload is malformed.""" + + pass diff --git a/backend/src/baserow/contrib/integrations/core/inbound_email.py b/backend/src/baserow/contrib/integrations/core/inbound_email.py new file mode 100644 index 0000000000..c381ab621e --- /dev/null +++ b/backend/src/baserow/contrib/integrations/core/inbound_email.py @@ -0,0 +1,488 @@ +import re +from dataclasses import dataclass, field +from hashlib import sha256 +from typing import Any, Dict, List, Optional + +from django.conf import settings +from django.core.cache import cache +from django.db import transaction + +from loguru import logger + +from baserow.contrib.integrations.core.exceptions import ( + CoreInboundEmailTriggerServiceDoesNotExist, + InvalidInboundEmailPayload, +) + +INBOUND_EMAIL_DEDUPE_CACHE_PREFIX = "inbound_email_dedupe" +# Mox retries failed webhook deliveries with backoff for up to ~16 hours, so +# the dedupe entries must outlive the retry window comfortably. +INBOUND_EMAIL_DEDUPE_TIMEOUT_SECONDS = 60 * 60 * 48 + +INBOUND_EMAIL_TOKEN_REGEX = re.compile(r"^[0-9a-f]{32}$") + +# Mox forwards at most this many bytes of the text and of the HTML body in its +# incoming-delivery webhook, cutting silently at the limit; attachment contents +# are never forwarded at all. A body that is exactly at the limit is treated as +# truncated so the workflow can tell. +MOX_WEBHOOK_PART_LIMIT_BYTES = 1024 * 1024 + +# Prefixing the token with this in the localpart targets the draft version of +# the workflow instead of the published one, mirroring the HTTP trigger's +# `?test=true` query string: `test-{token}@domain` starts a test run. +INBOUND_EMAIL_TEST_PREFIX = "test-" + +# The catch-all sub-address separator configured on the receiving mail server +# (mox's LocalpartCatchallSeparator). Everything after it in the localpart is an +# optional recipient "tag": `token+tag@domain` still routes to the `token` +# trigger, and `tag` is exposed in the payload so a workflow can branch on it. +INBOUND_EMAIL_CATCHALL_SEPARATOR = "+" + + +def split_catchall_localpart(address: str) -> "tuple[str, str]": + """ + Splits an email address into its base localpart and sub-address tag on the + catch-all separator, e.g. `abc+sales@d` -> `("abc", "sales")`. The base is + lowercased (trigger tokens are lowercase hex) so it can be matched against a + token; the tag is returned as received so a router can match it exactly. The + tag is empty when the address has no separator. + + :param address: The full email address. + :return: A `(base_localpart, tag)` tuple. + """ + + localpart = (address or "").rpartition("@")[0] + base, separator, tag = localpart.partition(INBOUND_EMAIL_CATCHALL_SEPARATOR) + return base.lower(), (tag if separator else "") + + +def is_inbound_email_configured() -> bool: + """ + Whether this instance can offer the email trigger: an inbound email domain + to generate addresses, the webhook secret the receiver authenticates with, + and the receiver URL through which handed-over messages are deleted again. + Without the last one the mail server would keep every message forever, so + the trigger is withheld until all three are set. Used by the node type's + deactivation check and exposed to the frontend through the public settings. + """ + + return bool( + settings.INBOUND_EMAIL_DOMAIN + and settings.INBOUND_EMAIL_WEBHOOK_SECRET + and settings.INBOUND_EMAIL_RECEIVER_URL + ) + + +HANDLE_STATUS_ACCEPTED = "accepted" +HANDLE_STATUS_DUPLICATE = "duplicate" +HANDLE_STATUS_DISCARDED = "discarded" + + +@dataclass(frozen=True) +class InboundEmailTarget: + """ + A trigger address found among a message's recipients: which trigger token + it names, and whether it targets the draft (`test-` prefixed) or the + published version of the workflow. + """ + + token: str + simulate: bool = False + + @property + def localpart(self) -> str: + return f"{INBOUND_EMAIL_TEST_PREFIX if self.simulate else ''}{self.token}" + + +def parse_inbound_localpart(localpart: str) -> Optional[InboundEmailTarget]: + """ + Parses the base localpart of a recipient address (already lowercased and + stripped of any `+tag`) into a target, or None when it is not a trigger + address. + """ + + simulate = localpart.startswith(INBOUND_EMAIL_TEST_PREFIX) + token = localpart[len(INBOUND_EMAIL_TEST_PREFIX) :] if simulate else localpart + if not INBOUND_EMAIL_TOKEN_REGEX.match(token): + return None + return InboundEmailTarget(token=token, simulate=simulate) + + +@dataclass +class InboundEmailAddress: + name: str = "" + address: str = "" + + def to_payload(self) -> Dict[str, str]: + return {"name": self.name, "address": self.address} + + +@dataclass +class InboundEmailAttachment: + filename: str = "" + content_type: str = "" + size: int = 0 + + def to_payload(self) -> Dict[str, Any]: + return { + "filename": self.filename, + "content_type": self.content_type, + "size": self.size, + } + + +@dataclass +class InboundEmail: + """ + The normalized internal representation of an inbound email. The receiving + mail server's webhook payload is converted into this representation at the + endpoint boundary so that the rest of the pipeline is independent of the + receiver implementation. + """ + + from_: InboundEmailAddress = field(default_factory=InboundEmailAddress) + to: List[InboundEmailAddress] = field(default_factory=list) + cc: List[InboundEmailAddress] = field(default_factory=list) + reply_to: List[InboundEmailAddress] = field(default_factory=list) + subject: str = "" + body_text: str = "" + body_html: str = "" + # True when the receiving mail server cut the body at its forwarding limit. + body_text_truncated: bool = False + body_html_truncated: bool = False + message_id: str = "" + in_reply_to: str = "" + received_at: str = "" + attachments: List[InboundEmailAttachment] = field(default_factory=list) + sender_validated: bool = False + dkim_verified_domains: List[str] = field(default_factory=list) + remote_ip: str = "" + rcpt_to: str = "" + is_automated: bool = False + # The receiving mail server's internal message id, used as a dedupe + # fallback when the message has no RFC Message-ID header. + internal_message_id: str = "" + + def to_payload(self) -> Dict[str, Any]: + return { + "from": self.from_.to_payload(), + "to": [address.to_payload() for address in self.to], + "cc": [address.to_payload() for address in self.cc], + "reply_to": [address.to_payload() for address in self.reply_to], + "rcpt_to": self.rcpt_to, + "recipient_tag": split_catchall_localpart(self.rcpt_to)[1], + "subject": self.subject, + "body_text": self.body_text, + "body_html": self.body_html, + "body_text_truncated": self.body_text_truncated, + "body_html_truncated": self.body_html_truncated, + "message_id": self.message_id, + "in_reply_to": self.in_reply_to, + "received_at": self.received_at, + "attachments": [attachment.to_payload() for attachment in self.attachments], + "sender_validated": self.sender_validated, + "dkim_verified_domains": self.dkim_verified_domains, + "remote_ip": self.remote_ip, + } + + +def _normalize_addresses(values: Any) -> List[InboundEmailAddress]: + if not isinstance(values, list): + return [] + + return [ + InboundEmailAddress( + name=value.get("Name") or "", address=value.get("Address") or "" + ) + for value in values + if isinstance(value, dict) + ] + + +def _collect_attachments(structure: Any) -> List[InboundEmailAttachment]: + """ + Walks the MIME structure tree of the webhook payload and collects the + metadata of every part that presents itself as an attachment. + """ + + if not isinstance(structure, dict): + return [] + + attachments = [] + disposition = (structure.get("ContentDisposition") or "").lower() + filename = structure.get("Filename") or "" + + if disposition == "attachment" or (filename and disposition != "inline"): + attachments.append( + InboundEmailAttachment( + filename=filename, + content_type=structure.get("ContentType") or "", + size=int(structure.get("DecodedSize") or 0), + ) + ) + + for part in structure.get("Parts") or []: + attachments.extend(_collect_attachments(part)) + + return attachments + + +def _is_truncated_part(value: str) -> bool: + return len(value.encode("utf-8")) >= MOX_WEBHOOK_PART_LIMIT_BYTES + + +def normalize_mox_payload(data: Dict[str, Any]) -> InboundEmail: + """ + Converts a mox `webhook.Incoming` JSON payload into the internal + `InboundEmail` representation. + + :param data: The parsed JSON body of the webhook request. + :raises InvalidInboundEmailPayload: When the payload is not shaped like a + mox incoming delivery webhook. + :return: The normalized inbound email. + """ + + if not isinstance(data, dict): + raise InvalidInboundEmailPayload("The payload must be a JSON object.") + + meta = data.get("Meta") + from_addresses = data.get("From") + if not isinstance(meta, dict) or not isinstance(from_addresses, list): + raise InvalidInboundEmailPayload( + "The payload is missing the required From and Meta fields." + ) + + from_ = _normalize_addresses(from_addresses) + + body_text = data.get("Text") or "" + body_html = data.get("HTML") or "" + + return InboundEmail( + from_=from_[0] if from_ else InboundEmailAddress(), + to=_normalize_addresses(data.get("To")), + cc=_normalize_addresses(data.get("CC")), + reply_to=_normalize_addresses(data.get("ReplyTo")), + subject=data.get("Subject") or "", + body_text=body_text, + body_html=body_html, + body_text_truncated=_is_truncated_part(body_text), + body_html_truncated=_is_truncated_part(body_html), + message_id=data.get("MessageID") or "", + in_reply_to=data.get("InReplyTo") or "", + received_at=meta.get("Received") or "", + attachments=_collect_attachments(data.get("Structure")), + sender_validated=bool(meta.get("MsgFromValidated")), + dkim_verified_domains=meta.get("DKIMVerifiedDomains") or [], + remote_ip=meta.get("RemoteIP") or "", + rcpt_to=meta.get("RcptTo") or "", + is_automated=bool(meta.get("Automated")), + internal_message_id=str(meta.get("MsgID") or ""), + ) + + +class InboundEmailHandler: + """ + Orchestrates the processing of inbound email webhook payloads: payload + normalization, loop protection, recipient token extraction, Message-ID + deduplication and dispatching of the matching email trigger services. + """ + + def extract_targets(self, email: InboundEmail) -> List[InboundEmailTarget]: + """ + Extracts the trigger targets from the email's recipients. The envelope + recipient (RcptTo) is the most reliable source; the To and Cc headers + are scanned as a fallback. A `test-` prefixed localpart targets the + draft version of the workflow, a bare token the published one. + + :param email: The normalized inbound email. + :return: The unique list of targets found. + """ + + candidates = [email.rcpt_to] + [ + address.address for address in email.to + email.cc + ] + + domain = settings.INBOUND_EMAIL_DOMAIN.lower() + targets = [] + for candidate in candidates: + candidate_domain = (candidate or "").rpartition("@")[2].lower() + if candidate_domain != domain: + continue + # Strip any `+tag` sub-address so `token+tag@domain` resolves to the + # `token` trigger; the tag is surfaced separately in the payload. + localpart, _ = split_catchall_localpart(candidate) + target = parse_inbound_localpart(localpart) + if target is not None and target not in targets: + targets.append(target) + + return targets + + def get_dedupe_cache_key( + self, target: InboundEmailTarget, email: InboundEmail + ) -> Optional[str]: + message_id = email.message_id or email.internal_message_id + if not message_id: + return None + + # The test and published addresses of a trigger are separate targets, + # so one message sent to both is processed for both. + digest = sha256(message_id.encode()).hexdigest() + return f"{INBOUND_EMAIL_DEDUPE_CACHE_PREFIX}:{target.localpart}:{digest}" + + def handle_webhook_payload(self, data: Dict[str, Any]) -> str: + """ + Processes a parsed inbound email webhook payload and dispatches the + matching email trigger services. + + :param data: The parsed JSON body of the webhook request. + :raises InvalidInboundEmailPayload: When the payload is malformed. + :return: One of `accepted`, `duplicate` or `discarded`, describing + what happened to the message. + """ + + from baserow.core.services.registries import service_type_registry + + email = normalize_mox_payload(data) + + # Whatever happens to it below, the message now exists on the receiver, + # which keeps it forever unless told otherwise. + self._schedule_receiver_message_deletion(email) + + # Loop protection: never dispatch automated messages (auto-replies, + # delivery reports, etc), otherwise a forward rule plus an + # auto-responder could create an infinite loop. + if email.is_automated: + return self._log_status(HANDLE_STATUS_DISCARDED, "automated message", email) + + if not settings.INBOUND_EMAIL_DOMAIN: + return self._log_status( + HANDLE_STATUS_DISCARDED, "inbound email domain not configured", email + ) + + targets = self.extract_targets(email) + if not targets: + return self._log_status( + HANDLE_STATUS_DISCARDED, "no recipient matches a trigger address", email + ) + + service_type = service_type_registry.get("email_trigger") + + statuses = set() + for target in targets: + statuses.add(self._process_target(service_type, target, email)) + + for status in ( + HANDLE_STATUS_ACCEPTED, + HANDLE_STATUS_DUPLICATE, + HANDLE_STATUS_DISCARDED, + ): + if status in statuses: + return status + + return HANDLE_STATUS_DISCARDED + + def _schedule_receiver_message_deletion(self, email: InboundEmail) -> None: + """ + Queues the deletion of the message from the receiver once this + request's transaction has committed, i.e. once the webhook is about to + be acknowledged (see `inbound_email_receiver.py`). A retried delivery + of the same message queues a second deletion, which finds the message + already gone. Nothing is queued when the receiver is not configured, + which the node type's availability gate rules out for real triggers. + """ + + from baserow.contrib.integrations.core.inbound_email_receiver import ( + INBOUND_EMAIL_RECEIVER_DELETE_DELAY_SECONDS, + ) + from baserow.contrib.integrations.tasks import ( + delete_inbound_email_receiver_message, + ) + + try: + message_id = int(email.internal_message_id) + except (TypeError, ValueError): + return + if message_id <= 0 or not settings.INBOUND_EMAIL_RECEIVER_URL: + return + + transaction.on_commit( + lambda: delete_inbound_email_receiver_message.apply_async( + args=[message_id], + countdown=INBOUND_EMAIL_RECEIVER_DELETE_DELAY_SECONDS, + ) + ) + + def _process_target( + self, service_type, target: InboundEmailTarget, email: InboundEmail + ) -> str: + cache_key = self.get_dedupe_cache_key(target, email) + + # `cache.add` is atomic; it returns False when the key already exists, + # meaning this message was processed before. Mox delivers webhooks + # at-least-once, so the endpoint must be idempotent. When the message + # has no Message-ID at all, deduplication is skipped. + if cache_key is not None and not cache.add( + cache_key, True, timeout=INBOUND_EMAIL_DEDUPE_TIMEOUT_SECONDS + ): + return self._log_status( + HANDLE_STATUS_DUPLICATE, "message already processed", email, target + ) + + try: + service_type.process_inbound_email( + target.token, email, simulate=target.simulate + ) + except CoreInboundEmailTriggerServiceDoesNotExist: + return self._log_status( + HANDLE_STATUS_DISCARDED, "no trigger for token", email, target + ) + except Exception: + # The message was not processed, so remove the dedupe entry to + # make sure the next retried delivery is not treated as a + # duplicate. + if cache_key is not None: + cache.delete(cache_key) + raise + + return self._log_status( + HANDLE_STATUS_ACCEPTED, "dispatched to trigger", email, target + ) + + def _log_status( + self, + status: str, + reason: str, + email: InboundEmail, + target: Optional[InboundEmailTarget] = None, + ) -> str: + """ + Logs the outcome of handling an inbound message and returns the status + so callers can `return self._log_status(...)`. Every outcome is answered + with HTTP 200 (a non-2xx would make mox retry, and a distinct code would + let an outsider probe which tokens exist), so this log line is the only + place operators can tell accepted, duplicate and discarded apart. + + Neither the addresses nor the full token are logged: the token is the + routing secret of a trigger. The `test-` prefix is kept so test runs + can be told apart from live ones. The message is identified by a short + prefix of the hashed Message-ID, which is enough to correlate retried + deliveries of the same message. + """ + + message_id = email.message_id or email.internal_message_id + message_ref = ( + sha256(message_id.encode()).hexdigest()[:12] if message_id else "-" + ) + logger.info( + "Inbound email {status}: {reason} (message={message_ref}, token={token})", + status=status, + reason=reason, + message_ref=message_ref, + token=( + f"{INBOUND_EMAIL_TEST_PREFIX if target.simulate else ''}" + f"{target.token[:8]}…" + if target + else "-" + ), + ) + return status diff --git a/backend/src/baserow/contrib/integrations/core/inbound_email_receiver.py b/backend/src/baserow/contrib/integrations/core/inbound_email_receiver.py new file mode 100644 index 0000000000..392f180d9a --- /dev/null +++ b/backend/src/baserow/contrib/integrations/core/inbound_email_receiver.py @@ -0,0 +1,159 @@ +""" +Deletes handed-over messages from the bundled inbound mail server (mox). + +Mox writes every accepted message to disk before posting the incoming-delivery +webhook and never removes it: it has no retention setting. Its web API can +delete a message by id, and every webhook carries the id of the message it is +about, so `InboundEmailHandler.handle_webhook_payload` queues the deletion of +each message it is handed, whatever it then does with it. Deleting a message +whose webhook is still being retried is safe: mox retries from its own stored +copy of the payload, and Baserow never reads a message back. The one thing this +does not cover is a message whose webhook never reaches the backend at all, +which happens when the backend stays unreachable for longer than mox retries +(roughly 32 hours). +""" + +import json +from typing import Optional + +from django.conf import settings + +import requests +from loguru import logger + +# The explicit address the web API authenticates with. Must match the +# destination `generate-mox-config.sh` adds to the inbound account. +INBOUND_EMAIL_WEBAPI_LOCALPART = "webapi" +INBOUND_EMAIL_RECEIVER_TIMEOUT_SECONDS = 10 +# How long after its webhook a message is deleted from the receiver. Not needed +# for correctness (see the module docstring), but it lets the receiver finish +# its own bookkeeping for the delivery before the backend calls back into it. +INBOUND_EMAIL_RECEIVER_DELETE_DELAY_SECONDS = 60 + + +class InboundEmailReceiverError(Exception): + """Raised when the receiver's web API cannot be used.""" + + +# Mox only serves its internal web services, the web API included, when the +# request's Host header is an IP address, the listener's own hostname or +# "localhost"; anything else gets a 404. The backend reaches the receiver by +# whatever name the deployment gives it (`email-receiver` in compose), so the +# client always presents itself as localhost instead of the URL's hostname. +INBOUND_EMAIL_RECEIVER_HOST_HEADER = "localhost" + + +class InboundEmailReceiverClient: + """ + Minimal client for mox's web API: `POST {base}/webapi/v0/` with a + form field `request` holding the JSON request, HTTP basic auth with an + address of the account. One session is kept for the client's lifetime so a + sweep of many messages reuses its connection instead of opening one per + call. + """ + + def __init__( + self, + base_url: str, + username: str, + password: str, + timeout: int = INBOUND_EMAIL_RECEIVER_TIMEOUT_SECONDS, + ): + self.base_url = base_url.rstrip("/") + self.username = username + self.password = password + self.timeout = timeout + self._session = requests.Session() + self._session.auth = (username, password) + self._session.headers["Host"] = INBOUND_EMAIL_RECEIVER_HOST_HEADER + + def close(self) -> None: + self._session.close() + + @classmethod + def from_settings(cls) -> Optional["InboundEmailReceiverClient"]: + """ + Returns a client for the configured receiver, or None when inbound email + or the receiver URL is not configured on this instance. + """ + + if not ( + settings.INBOUND_EMAIL_RECEIVER_URL + and settings.INBOUND_EMAIL_DOMAIN + and settings.INBOUND_EMAIL_WEBHOOK_SECRET + ): + return None + return cls( + settings.INBOUND_EMAIL_RECEIVER_URL, + f"{INBOUND_EMAIL_WEBAPI_LOCALPART}@{settings.INBOUND_EMAIL_DOMAIN}", + # The entrypoint applies the same fallback when it sets the + # account's password on the receiver. + settings.INBOUND_EMAIL_RECEIVER_PASSWORD + or settings.INBOUND_EMAIL_WEBHOOK_SECRET, + ) + + def delete_message(self, message_id: int) -> bool: + """ + Deletes one message and returns True, or returns False when the receiver + no longer has it. Any other failure raises `InboundEmailReceiverError`. + """ + + try: + response = self._session.post( + f"{self.base_url}/webapi/v0/MessageDelete", + data={"request": json.dumps({"MsgID": message_id})}, + timeout=self.timeout, + ) + except requests.RequestException as exc: + raise InboundEmailReceiverError( + f"could not reach the inbound email receiver: {type(exc).__name__}" + ) from exc + + if response.status_code == 200: + return True + + if response.status_code == 400: + # Mox answers 400 for a bad request as well as for an unknown or + # already removed message; only the latter two mean "gone". + try: + error = response.json() + except ValueError: + error = {} + code = error.get("Code") + message = error.get("Message", "") + if code == "messageNotFound" or (code == "user" and "removed" in message): + return False + + raise InboundEmailReceiverError( + f"MessageDelete for message {message_id} failed with HTTP " + f"{response.status_code}: {response.text[:200]}" + ) + + +def delete_receiver_message(message_id: int) -> Optional[bool]: + """ + Deletes one message from the configured receiver. + + :param message_id: The receiver-side id of the message, as carried by its + webhook. + :raises InboundEmailReceiverError: When the receiver cannot be used; the + calling task retries. + :return: True when the message was deleted, False when the receiver no + longer had it, or None when no receiver is configured on this instance. + """ + + client = InboundEmailReceiverClient.from_settings() + if client is None: + return None + + try: + deleted = client.delete_message(message_id) + finally: + client.close() + + logger.debug( + "Inbound email receiver message {message_id} {outcome}.", + message_id=message_id, + outcome="deleted" if deleted else "was already gone", + ) + return deleted diff --git a/backend/src/baserow/contrib/integrations/core/models.py b/backend/src/baserow/contrib/integrations/core/models.py index 0be34db00a..0bceb79b99 100644 --- a/backend/src/baserow/contrib/integrations/core/models.py +++ b/backend/src/baserow/contrib/integrations/core/models.py @@ -1,5 +1,7 @@ +import secrets import uuid +from django.conf import settings from django.contrib.auth import get_user_model from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models @@ -49,6 +51,15 @@ class SMTPIntegration(Integration): ) +def generate_inbound_email_token() -> str: + """ + Generates a high-entropy token used as the localpart of an inbound email + address. Lowercase hex keeps the localpart case-insensitivity-safe. + """ + + return secrets.token_hex(16) + + class CoreIteratorService(Service): """ A service to iterate over an array of data. @@ -356,3 +367,63 @@ class CoreHTTPTriggerService(Service): default=False, help_text="Defines whether the service is published or not.", ) + + +class CoreInboundEmailTriggerService(Service): + """ + A trigger service that starts a workflow when an email is delivered to its + generated inbound email address. + """ + + token = models.CharField( + max_length=32, + default=generate_inbound_email_token, + db_index=True, + help_text="The localpart of the generated inbound email address.", + ) + + is_public = models.BooleanField( + default=False, + help_text="Defines whether the service is published or not.", + ) + + @property + def email_address(self) -> str | None: + """ + The full inbound email address for this trigger, or None when the + instance has no inbound email domain configured. + """ + + if not settings.INBOUND_EMAIL_DOMAIN: + return None + + return f"{self.token}@{settings.INBOUND_EMAIL_DOMAIN}" + + @property + def test_email_address(self) -> str | None: + """ + The `test-` prefixed address that targets the draft version of the + workflow (a test run) instead of the published one, or None when the + instance has no inbound email domain configured. + """ + + from baserow.contrib.integrations.core.inbound_email import ( + INBOUND_EMAIL_TEST_PREFIX, + ) + + if not settings.INBOUND_EMAIL_DOMAIN: + return None + + return ( + f"{INBOUND_EMAIL_TEST_PREFIX}{self.token}@{settings.INBOUND_EMAIL_DOMAIN}" + ) + + @property + def max_message_size_mb(self) -> int: + """ + The largest email, in MB, the instance's inbound mail server accepts. + Mirrors the receiver's configuration so the limit can be shown next to + the address. + """ + + return settings.INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB diff --git a/backend/src/baserow/contrib/integrations/core/service_types.py b/backend/src/baserow/contrib/integrations/core/service_types.py index a9b899a537..30cde48b0a 100644 --- a/backend/src/baserow/contrib/integrations/core/service_types.py +++ b/backend/src/baserow/contrib/integrations/core/service_types.py @@ -29,6 +29,9 @@ from baserow.config.celery import app as celery_app from baserow.contrib.automation.nodes.exceptions import ( AutomationNodeMisconfiguredService, ) +from baserow.contrib.integrations.core.api.inbound_email.views import ( + CoreInboundEmailWebhookView, +) from baserow.contrib.integrations.core.api.webhooks.views import CoreHTTPTriggerView from baserow.contrib.integrations.core.constants import ( BODY_TYPE, @@ -42,6 +45,11 @@ from baserow.contrib.integrations.core.constants import ( from baserow.contrib.integrations.core.exceptions import ( CoreHTTPTriggerServiceDoesNotExist, CoreHTTPTriggerServiceMethodNotAllowed, + CoreInboundEmailTriggerServiceDoesNotExist, +) +from baserow.contrib.integrations.core.inbound_email import ( + InboundEmail, + InboundEmailAddress, ) from baserow.contrib.integrations.core.integration_types import SMTPIntegrationType from baserow.contrib.integrations.core.models import ( @@ -49,6 +57,7 @@ from baserow.contrib.integrations.core.models import ( CoreGotoService, CoreHTTPRequestService, CoreHTTPTriggerService, + CoreInboundEmailTriggerService, CoreIteratorService, CoreManualTriggerService, CorePeriodicService, @@ -59,6 +68,7 @@ from baserow.contrib.integrations.core.models import ( HTTPFormData, HTTPHeader, HTTPQueryParam, + generate_inbound_email_token, ) from baserow.contrib.integrations.core.utils import calculate_next_periodic_run from baserow.contrib.integrations.utils import ( @@ -2200,6 +2210,263 @@ class CoreHTTPTriggerServiceType(TriggerServiceTypeMixin, ServiceType): ) +class CoreInboundEmailTriggerServiceType(TriggerServiceTypeMixin, ServiceType): + type = "email_trigger" + model_class = CoreInboundEmailTriggerService + + # The token is deliberately not part of the request serializer fields: a + # client-chosen token could collide with another workspace's address. It + # can only be regenerated via the `regenerate_token` flag. + allowed_fields = ["token", "is_public"] + serializer_field_names = [ + "token", + "email_address", + "test_email_address", + "max_message_size_mb", + "is_public", + ] + serializer_field_overrides = { + "email_address": serializers.CharField( + read_only=True, + allow_null=True, + help_text="The generated inbound email address of this trigger, or " + "null when the instance has no inbound email domain configured.", + ), + "test_email_address": serializers.CharField( + read_only=True, + allow_null=True, + help_text="The `test-` prefixed inbound email address that starts a " + "test run of the draft workflow instead of the published one, or " + "null when the instance has no inbound email domain configured.", + ), + "max_message_size_mb": serializers.IntegerField( + read_only=True, + help_text="The largest email, in MB, the inbound mail server of this " + "instance accepts. Larger emails are refused during delivery.", + ), + } + request_serializer_field_names = ["regenerate_token"] + request_serializer_field_overrides = { + "regenerate_token": serializers.BooleanField( + write_only=True, + required=False, + help_text="When true, a new inbound email address is generated for " + "this trigger.", + ), + } + + class SerializedDict(ServiceDict): + token: str + is_public: bool + + def get_api_urls(self) -> List[path]: + return [ + path( + r"inbound-email/", + CoreInboundEmailWebhookView.as_view(), + name="inbound_email", + ), + ] + + def prepare_values( + self, + values: Dict[str, Any], + user: AbstractUser, + instance: Optional[CoreInboundEmailTriggerService] = None, + ) -> Dict[str, Any]: + if values.pop("regenerate_token", False): + values["token"] = generate_inbound_email_token() + + return super().prepare_values(values, user, instance) + + def process_inbound_email( + self, token: str, email: InboundEmail, simulate: bool = False + ) -> None: + """ + Finds the CoreInboundEmailTriggerService matching the provided token and + calls the on_event handler for it with the email payload. The email is + passed through as-is; the trigger doesn't care which provider sent or + forwarded it. + + The draft and the published version of a service share the same token, + so `simulate` decides which one is targeted, exactly like the HTTP + trigger's `?test=true`: the `test-` prefixed address reaches the draft, + the bare one the published version. + + :param token: The token extracted from the recipient address. + :param email: The normalized inbound email. + :param simulate: True when the message was sent to the `test-` address, + targeting the draft version of the service; False targets the + published version. + :raises CoreInboundEmailTriggerServiceDoesNotExist: When the token doesn't + match a service of the requested version. + """ + + # When the service is published, the previous published service may be + # kept (e.g. see `AutomationWorkflowHandler::publish()`). Since the + # token is the same between the two, only the latest one is used. + service = ( + self.model_class.objects.filter(token=token, is_public=not simulate) + .order_by("-id") + .first() + ) + + if not service: + raise CoreInboundEmailTriggerServiceDoesNotExist(token) + + payload = email.to_payload() + self.on_event([service], lambda service: payload) + + def dispatch_data( + self, + service: CoreInboundEmailTriggerService, + resolved_values: Dict[str, Any], + dispatch_context: DispatchContext, + ): + # When the trigger is simulated before any real email arrived, there + # is no event payload, so a sample email is returned instead. + if dispatch_context.event_payload is None: + return self._get_sample_payload(service) + + return super().dispatch_data(service, resolved_values, dispatch_context) + + def _get_sample_payload( + self, service: CoreInboundEmailTriggerService + ) -> Dict[str, Any]: + return InboundEmail( + from_=InboundEmailAddress( + name="Sample sender", address="sender@example.com" + ), + to=[InboundEmailAddress(address=service.email_address or "")], + rcpt_to=service.email_address or "", + subject="Sample email subject", + body_text="This is a sample email body.", + body_html="

This is a sample email body.

", + message_id="", + received_at=timezone.now().isoformat(), + ).to_payload() + + def get_schema_name(self, service: CoreInboundEmailTriggerService) -> str: + return f"EmailTrigger{service.id}Schema" + + def generate_schema( + self, + service: CoreInboundEmailTriggerService, + allowed_fields: Optional[List[str]] = None, + ) -> Optional[Dict[str, Any]]: + email_address_schema = { + "type": "object", + "properties": { + "name": {"type": "string", "title": _("Name")}, + "address": {"type": "string", "title": _("Address")}, + }, + } + + properties = { + "from": {**email_address_schema, "title": _("From")}, + "to": { + "type": "array", + "title": _("To"), + "items": email_address_schema, + }, + "cc": { + "type": "array", + "title": _("Cc"), + "items": email_address_schema, + }, + "reply_to": { + "type": "array", + "title": _("Reply to"), + "items": email_address_schema, + }, + "rcpt_to": {"type": "string", "title": _("Recipient")}, + "recipient_tag": {"type": "string", "title": _("Recipient tag")}, + "subject": {"type": "string", "title": _("Subject")}, + "body_text": {"type": "string", "title": _("Body (text)")}, + "body_html": {"type": "string", "title": _("Body (HTML)")}, + "body_text_truncated": { + "type": "boolean", + "title": _("Body (text) truncated"), + }, + "body_html_truncated": { + "type": "boolean", + "title": _("Body (HTML) truncated"), + }, + "message_id": {"type": "string", "title": _("Message ID")}, + "in_reply_to": {"type": "string", "title": _("In reply to")}, + "received_at": {"type": "string", "title": _("Received at")}, + "attachments": { + "type": "array", + "title": _("Attachments"), + "items": { + "type": "object", + "properties": { + "filename": {"type": "string", "title": _("Filename")}, + "content_type": { + "type": "string", + "title": _("Content type"), + }, + "size": {"type": "number", "title": _("Size")}, + }, + }, + }, + "sender_validated": { + "type": "boolean", + "title": _("Sender validated"), + }, + "dkim_verified_domains": { + "type": "array", + "title": _("DKIM verified domains"), + "items": {"type": "string"}, + }, + "remote_ip": {"type": "string", "title": _("Remote IP")}, + } + + if allowed_fields is not None: + properties = { + key: value for key, value in properties.items() if key in allowed_fields + } + + return { + "title": self.get_schema_name(service), + "type": "object", + "properties": properties, + } + + def import_serialized( + self, + parent: Any, + serialized_values: Dict[str, Any], + id_mapping: Dict[str, Dict[str, str]], + import_export_config: Optional[ImportExportConfig] = None, + **kwargs, + ): + """ + Handle the is_public field during import based on publishing context. + """ + + if import_export_config: + if import_export_config.is_publishing: + # Publishing must keep the token so the published address is + # the one shown next to the draft. + serialized_values["is_public"] = True + else: + # Every other import (duplicating, installing a template, + # importing an exported application) gets a new address. The + # token is the address's only secret: keeping it would let an + # import of someone's export take over their trigger's mail, + # since the newest published service with a token wins. + serialized_values["token"] = generate_inbound_email_token() + + return super().import_serialized( + parent, + serialized_values, + id_mapping, + import_export_config=import_export_config, + **kwargs, + ) + + class CoreManualTriggerServiceType(TriggerServiceTypeMixin, CoreServiceType): type = "manual" model_class = CoreManualTriggerService diff --git a/backend/src/baserow/contrib/integrations/migrations/0036_coreinboundemailtriggerservice.py b/backend/src/baserow/contrib/integrations/migrations/0036_coreinboundemailtriggerservice.py new file mode 100644 index 0000000000..f99afd3ffb --- /dev/null +++ b/backend/src/baserow/contrib/integrations/migrations/0036_coreinboundemailtriggerservice.py @@ -0,0 +1,28 @@ +# Generated by Django 5.2.15 on 2026-07-15 14:01 + +import baserow.contrib.integrations.core.models +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('core', '0114_alter_workspaceinvitation_message'), + ('integrations', '0035_coreperiodicservice_timezone'), + ] + + operations = [ + migrations.CreateModel( + name='CoreInboundEmailTriggerService', + fields=[ + ('service_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.service')), + ('token', models.CharField(db_index=True, default=baserow.contrib.integrations.core.models.generate_inbound_email_token, help_text='The localpart of the generated inbound email address.', max_length=32)), + ('is_public', models.BooleanField(default=False, help_text='Defines whether the service is published or not.')), + ], + options={ + 'abstract': False, + }, + bases=('core.service',), + ), + ] diff --git a/backend/src/baserow/contrib/integrations/tasks.py b/backend/src/baserow/contrib/integrations/tasks.py index 439ca74418..5dcdc2e804 100644 --- a/backend/src/baserow/contrib/integrations/tasks.py +++ b/backend/src/baserow/contrib/integrations/tasks.py @@ -1,6 +1,9 @@ from django.db import transaction from baserow.config.celery import app +from baserow.contrib.integrations.core.inbound_email_receiver import ( + InboundEmailReceiverError, +) from baserow.core.services.registries import service_type_registry @@ -12,3 +15,33 @@ def call_periodic_services_that_are_due(self): service_type_registry.get( CorePeriodicServiceType.type ).call_periodic_services_that_are_due() + + +# Retried with exponential backoff (1, 2, 4 ... minutes, capped at an hour) +# while the receiver cannot be used, so a receiver restart or redeploy of a few +# hours does not leave the message behind. +INBOUND_EMAIL_RECEIVER_DELETE_MAX_RETRIES = 8 + + +@app.task( + bind=True, + queue="export", + autoretry_for=(InboundEmailReceiverError,), + retry_backoff=60, + retry_backoff_max=60 * 60, + retry_jitter=True, + max_retries=INBOUND_EMAIL_RECEIVER_DELETE_MAX_RETRIES, +) +def delete_inbound_email_receiver_message(self, message_id: int): + """ + Deletes one handed-over message from the bundled inbound mail server, which + keeps every accepted message forever otherwise. Queued by the inbound email + webhook for each message it receives. A no-op when inbound email is not + configured on this instance. + """ + + from baserow.contrib.integrations.core.inbound_email_receiver import ( + delete_receiver_message, + ) + + delete_receiver_message(message_id) diff --git a/backend/src/baserow/core/locale/en/LC_MESSAGES/django.po b/backend/src/baserow/core/locale/en/LC_MESSAGES/django.po index a2da64c6ec..f0e0d5b03e 100644 --- a/backend/src/baserow/core/locale/en/LC_MESSAGES/django.po +++ b/backend/src/baserow/core/locale/en/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-08-26 15:25+0000\n" +"POT-Creation-Date: 2026-09-11 12:44+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -279,11 +279,53 @@ msgstr "" msgid "Unlabeled" msgstr "" -#: src/baserow/core/handler.py:2239 src/baserow/core/user/handler.py:276 +#: src/baserow/core/handler.py:2241 src/baserow/core/user/handler.py:284 #, python-format msgid "%(name)s's workspace" msgstr "" +#: src/baserow/core/integrations/actions.py:19 +#: src/baserow/core/user_sources/actions.py:19 +#, python-format +msgid "in application \"%(application_name)s\" (%(application_id)s)." +msgstr "" + +#: src/baserow/core/integrations/actions.py:26 +msgid "Create integration" +msgstr "" + +#: src/baserow/core/integrations/actions.py:27 +#, python-format +msgid "Integration (%(integration_id)s) created" +msgstr "" + +#: src/baserow/core/integrations/actions.py:87 +msgid "Update integration" +msgstr "" + +#: src/baserow/core/integrations/actions.py:88 +#, python-format +msgid "Integration (%(integration_id)s) updated" +msgstr "" + +#: src/baserow/core/integrations/actions.py:150 +msgid "Delete integration" +msgstr "" + +#: src/baserow/core/integrations/actions.py:151 +#, python-format +msgid "Integration (%(integration_id)s) deleted" +msgstr "" + +#: src/baserow/core/integrations/actions.py:203 +msgid "Move integration" +msgstr "" + +#: src/baserow/core/integrations/actions.py:204 +#, python-format +msgid "Integration (%(integration_id)s) moved" +msgstr "" + #: src/baserow/core/mcp/actions.py:20 msgid "Create MCP endpoint" msgstr "" @@ -584,109 +626,109 @@ msgid "" "(%(auth_provider_id)s) auth provider (invitation: %(with_invitation_token)s)" msgstr "" -#: src/baserow/core/user/actions.py:119 +#: src/baserow/core/user/actions.py:122 msgid "Update User" msgstr "" -#: src/baserow/core/user/actions.py:120 +#: src/baserow/core/user/actions.py:123 #, python-format msgid "User \"%(user_email)s\" (%(user_id)s) updated" msgstr "" -#: src/baserow/core/user/actions.py:184 +#: src/baserow/core/user/actions.py:187 msgid "Schedule user deletion" msgstr "" -#: src/baserow/core/user/actions.py:186 +#: src/baserow/core/user/actions.py:189 #, python-format msgid "" "User \"%(user_email)s\" (%(user_id)s) scheduled to be deleted after grace " "time" msgstr "" -#: src/baserow/core/user/actions.py:220 +#: src/baserow/core/user/actions.py:223 msgid "Cancel user deletion" msgstr "" -#: src/baserow/core/user/actions.py:222 +#: src/baserow/core/user/actions.py:225 #, python-format msgid "" "User \"%(user_email)s\" (%(user_id)s) logged in cancelling the deletion " "process" msgstr "" -#: src/baserow/core/user/actions.py:256 +#: src/baserow/core/user/actions.py:259 msgid "Sign In User" msgstr "" -#: src/baserow/core/user/actions.py:258 +#: src/baserow/core/user/actions.py:261 #, python-format msgid "" "User \"%(user_email)s\" (%(user_id)s) signed in via " "\"%(auth_provider_type)s\" (%(auth_provider_id)s) auth provider" msgstr "" -#: src/baserow/core/user/actions.py:327 +#: src/baserow/core/user/actions.py:330 msgid "Send reset user password" msgstr "" -#: src/baserow/core/user/actions.py:328 +#: src/baserow/core/user/actions.py:331 #, python-format msgid "User \"%(user_email)s\" (%(user_id)s) requested to reset password" msgstr "" -#: src/baserow/core/user/actions.py:361 +#: src/baserow/core/user/actions.py:364 msgid "Change user password" msgstr "" -#: src/baserow/core/user/actions.py:362 +#: src/baserow/core/user/actions.py:365 #, python-format msgid "User \"%(user_email)s\" (%(user_id)s) changed password" msgstr "" -#: src/baserow/core/user/actions.py:401 +#: src/baserow/core/user/actions.py:404 msgid "Reset user password" msgstr "" -#: src/baserow/core/user/actions.py:402 +#: src/baserow/core/user/actions.py:405 #, python-format msgid "User \"%(user_email)s\" (%(user_id)s) reset password" msgstr "" -#: src/baserow/core/user/actions.py:438 +#: src/baserow/core/user/actions.py:441 msgid "Send verify email" msgstr "" -#: src/baserow/core/user/actions.py:439 +#: src/baserow/core/user/actions.py:442 #, python-format msgid "User \"%(user_email)s\" (%(user_id)s) requested to verify email" msgstr "" -#: src/baserow/core/user/actions.py:472 +#: src/baserow/core/user/actions.py:475 msgid "Verify email" msgstr "" -#: src/baserow/core/user/actions.py:473 +#: src/baserow/core/user/actions.py:476 #, python-format msgid "User \"%(user_email)s\" (%(user_id)s) verify email" msgstr "" -#: src/baserow/core/user/actions.py:510 +#: src/baserow/core/user/actions.py:513 msgid "Send change email confirmation" msgstr "" -#: src/baserow/core/user/actions.py:512 +#: src/baserow/core/user/actions.py:515 #, python-format msgid "" "User \"%(user_email)s\" (%(user_id)s) requested to change email to " "\"%(new_email)s\"" msgstr "" -#: src/baserow/core/user/actions.py:558 +#: src/baserow/core/user/actions.py:561 msgid "Change email" msgstr "" -#: src/baserow/core/user/actions.py:560 +#: src/baserow/core/user/actions.py:563 #, python-format msgid "" "User \"%(old_email)s\" (%(user_id)s) changed email to \"%(new_email)s\" by " @@ -716,3 +758,39 @@ msgstr "" #: src/baserow/core/user/emails.py:110 msgid "Confirm email address change - Baserow" msgstr "" + +#: src/baserow/core/user_sources/actions.py:26 +msgid "Create user source" +msgstr "" + +#: src/baserow/core/user_sources/actions.py:27 +#, python-format +msgid "User source (%(user_source_id)s) created" +msgstr "" + +#: src/baserow/core/user_sources/actions.py:87 +msgid "Update user source" +msgstr "" + +#: src/baserow/core/user_sources/actions.py:88 +#, python-format +msgid "User source (%(user_source_id)s) updated" +msgstr "" + +#: src/baserow/core/user_sources/actions.py:150 +msgid "Delete user source" +msgstr "" + +#: src/baserow/core/user_sources/actions.py:151 +#, python-format +msgid "User source (%(user_source_id)s) deleted" +msgstr "" + +#: src/baserow/core/user_sources/actions.py:203 +msgid "Move user source" +msgstr "" + +#: src/baserow/core/user_sources/actions.py:204 +#, python-format +msgid "User source (%(user_source_id)s) moved" +msgstr "" diff --git a/backend/src/baserow/locale/en/LC_MESSAGES/django.po b/backend/src/baserow/locale/en/LC_MESSAGES/django.po index 2b4515cc29..8a8f3dec68 100755 --- a/backend/src/baserow/locale/en/LC_MESSAGES/django.po +++ b/backend/src/baserow/locale/en/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-08-26 15:25+0000\n" +"POT-Creation-Date: 2026-09-11 12:44+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -110,79 +110,83 @@ msgstr "" msgid "Node (%(node_id)s) moved" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:153 +#: src/baserow/contrib/automation/nodes/node_types.py:156 msgid "Local Baserow create row" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:170 +#: src/baserow/contrib/automation/nodes/node_types.py:173 msgid "Local Baserow update row" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:187 +#: src/baserow/contrib/automation/nodes/node_types.py:190 msgid "Local Baserow delete row" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:195 +#: src/baserow/contrib/automation/nodes/node_types.py:198 msgid "Local Baserow get row" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:203 +#: src/baserow/contrib/automation/nodes/node_types.py:206 msgid "Local Baserow list rows" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:211 +#: src/baserow/contrib/automation/nodes/node_types.py:214 msgid "Local Baserow aggregate rows" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:219 +#: src/baserow/contrib/automation/nodes/node_types.py:222 msgid "HTTP request" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:226 +#: src/baserow/contrib/automation/nodes/node_types.py:229 msgid "Iterator" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:239 +#: src/baserow/contrib/automation/nodes/node_types.py:242 msgid "Send email" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:252 +#: src/baserow/contrib/automation/nodes/node_types.py:255 msgid "AI agent" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:259 +#: src/baserow/contrib/automation/nodes/node_types.py:262 msgid "Router" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:325 +#: src/baserow/contrib/automation/nodes/node_types.py:328 msgid "Branch" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:712 +#: src/baserow/contrib/automation/nodes/node_types.py:715 msgid "Local Baserow rows created" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:720 +#: src/baserow/contrib/automation/nodes/node_types.py:723 msgid "Local Baserow rows updated" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:728 +#: src/baserow/contrib/automation/nodes/node_types.py:731 msgid "Local Baserow rows deleted" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:744 +#: src/baserow/contrib/automation/nodes/node_types.py:747 msgid "Periodic trigger" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:751 +#: src/baserow/contrib/automation/nodes/node_types.py:754 msgid "HTTP trigger" msgstr "" -#: src/baserow/contrib/automation/nodes/node_types.py:764 +#: src/baserow/contrib/automation/nodes/node_types.py:761 +msgid "Email trigger" +msgstr "" + +#: src/baserow/contrib/automation/nodes/node_types.py:783 msgid "Slack write message" msgstr "" -#: src/baserow/contrib/automation/nodes/registries.py:48 +#: src/baserow/contrib/automation/nodes/registries.py:50 msgid "Unnamed node" msgstr "" @@ -282,49 +286,145 @@ msgstr "" msgid "Widget \"%(widget_title)s\" (%(widget_id)s) deleted" msgstr "" -#: src/baserow/contrib/integrations/core/service_types.py:1176 +#: src/baserow/contrib/integrations/core/service_types.py:1334 msgid "Branch taken" msgstr "" -#: src/baserow/contrib/integrations/core/service_types.py:1181 +#: src/baserow/contrib/integrations/core/service_types.py:1339 msgid "Label" msgstr "" -#: src/baserow/contrib/integrations/core/service_types.py:1183 +#: src/baserow/contrib/integrations/core/service_types.py:1341 msgid "The label of the branch that matched the condition." msgstr "" -#: src/baserow/contrib/integrations/core/service_types.py:1376 +#: src/baserow/contrib/integrations/core/service_types.py:1534 msgid "Condition" msgstr "" -#: src/baserow/contrib/integrations/core/service_types.py:1378 +#: src/baserow/contrib/integrations/core/service_types.py:1536 msgid "Whether the condition evaluated to true and the jump was followed." msgstr "" -#: src/baserow/contrib/integrations/core/service_types.py:1785 +#: src/baserow/contrib/integrations/core/service_types.py:1982 msgid "Previous scheduled run" msgstr "" -#: src/baserow/contrib/integrations/core/service_types.py:1789 +#: src/baserow/contrib/integrations/core/service_types.py:1986 msgid "Next scheduled run" msgstr "" -#: src/baserow/contrib/integrations/local_baserow/service_types.py:1783 +#: src/baserow/contrib/integrations/core/service_types.py:2316 +msgid "Name" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2317 +msgid "Address" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2322 +msgid "From" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2325 +msgid "To" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2330 +msgid "Cc" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2335 +msgid "Reply to" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2338 +msgid "Recipient" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2339 +msgid "Recipient tag" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2340 +msgid "Subject" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2341 +msgid "Body (text)" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2342 +msgid "Body (HTML)" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2343 +msgid "Message ID" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2344 +msgid "In reply to" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2345 +msgid "Received at" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2348 +msgid "Attachments" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2352 +msgid "Filename" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2355 +msgid "Content type" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2357 +msgid "Size" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2363 +msgid "Sender validated" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2367 +msgid "DKIM verified domains" +msgstr "" + +#: src/baserow/contrib/integrations/core/service_types.py:2370 +msgid "Remote IP" +msgstr "" + +#: src/baserow/contrib/integrations/local_baserow/service_types.py:1812 msgid "No rows found" msgstr "" -#: src/baserow/contrib/integrations/local_baserow/service_types.py:2408 +#: src/baserow/contrib/integrations/local_baserow/service_types.py:2453 #, python-format msgid "The %(operation)s action can process at most %(limit)s rows at once." msgstr "" -#: src/baserow/contrib/integrations/local_baserow/service_types.py:2774 +#: src/baserow/contrib/integrations/local_baserow/service_types.py:2819 #, python-format msgid "" "The batch delete rows action can process at most %(limit)s rows at once." msgstr "" -#: src/baserow/contrib/integrations/slack/service_types.py:166 +#: src/baserow/contrib/integrations/slack/service_types.py:246 msgid "OK" msgstr "" + +#: src/baserow/contrib/integrations/slack/service_types.py:247 +msgid "Channel" +msgstr "" + +#: src/baserow/contrib/integrations/slack/service_types.py:248 +msgid "Message timestamp" +msgstr "" + +#: src/baserow/contrib/integrations/slack/service_types.py:258 +msgid "Data" +msgstr "" diff --git a/backend/src/baserow/test_utils/fixtures/automation_node.py b/backend/src/baserow/test_utils/fixtures/automation_node.py index 68d0370aca..de0be216d0 100644 --- a/backend/src/baserow/test_utils/fixtures/automation_node.py +++ b/backend/src/baserow/test_utils/fixtures/automation_node.py @@ -13,6 +13,7 @@ from baserow.contrib.automation.nodes.models import ( from baserow.contrib.automation.nodes.node_types import ( CoreGotoActionNodeType, CoreHTTPTriggerNodeType, + CoreInboundEmailTriggerNodeType, CoreIteratorNodeType, CoreManualTriggerNodeType, CorePeriodicTriggerNodeType, @@ -222,6 +223,13 @@ class AutomationNodeFixtures: **kwargs, ) + def create_inbound_email_trigger_node(self, user=None, **kwargs): + return self.create_automation_node( + user=user, + type=CoreInboundEmailTriggerNodeType.type, + **kwargs, + ) + def create_manual_trigger_node(self, user=None, **kwargs): return self.create_automation_node( user=user, diff --git a/backend/src/baserow/test_utils/fixtures/service.py b/backend/src/baserow/test_utils/fixtures/service.py index 1face12f99..8c5ecf96b1 100644 --- a/backend/src/baserow/test_utils/fixtures/service.py +++ b/backend/src/baserow/test_utils/fixtures/service.py @@ -6,6 +6,7 @@ from baserow.contrib.integrations.core.models import ( CoreGotoService, CoreHTTPRequestService, CoreHTTPTriggerService, + CoreInboundEmailTriggerService, CoreIteratorService, CoreManualTriggerService, CorePeriodicService, @@ -196,6 +197,11 @@ class ServiceFixtures: return self.create_service(CoreHTTPTriggerService, **kwargs) + def create_core_inbound_email_trigger_service( + self, **kwargs + ) -> CoreInboundEmailTriggerService: + return self.create_service(CoreInboundEmailTriggerService, **kwargs) + def create_core_manual_trigger_service(self, **kwargs): return self.create_service(CoreManualTriggerService, **kwargs) diff --git a/backend/tests/baserow/api/settings/test_settings_views.py b/backend/tests/baserow/api/settings/test_settings_views.py index b4408eccbc..948280145a 100644 --- a/backend/tests/baserow/api/settings/test_settings_views.py +++ b/backend/tests/baserow/api/settings/test_settings_views.py @@ -2,6 +2,7 @@ from unittest.mock import patch from django.db import DEFAULT_DB_ALIAS from django.shortcuts import reverse +from django.test import override_settings import pytest from rest_framework.status import ( @@ -44,6 +45,49 @@ def test_get_settings(api_client): assert response_json["email_verification"] == "no_verification" +@pytest.mark.django_db +@pytest.mark.parametrize( + "domain,secret,receiver_url,expected", + [ + ("inbound.example.com", "s", "http://email-receiver:8880", True), + ("", "s", "http://email-receiver:8880", False), + ("inbound.example.com", "", "http://email-receiver:8880", False), + ("inbound.example.com", "s", "", False), + ], +) +def test_get_settings_reports_whether_inbound_email_is_enabled( + api_client, domain, secret, receiver_url, expected +): + # The frontend hides the email trigger unless this is true; it mirrors the + # backend's own gate, so an instance with the domain and secret but no + # receiver URL (and therefore no message sweep) does not offer the trigger. + with override_settings( + INBOUND_EMAIL_DOMAIN=domain, + INBOUND_EMAIL_WEBHOOK_SECRET=secret, + INBOUND_EMAIL_RECEIVER_URL=receiver_url, + ): + response = api_client.get(reverse("api:settings:get")) + + assert response.status_code == HTTP_200_OK + assert response.json()["inbound_email_enabled"] is expected + + +@pytest.mark.django_db +def test_inbound_email_enabled_cannot_be_updated(api_client, data_fixture): + _, token = data_fixture.create_user_and_token(is_staff=True) + + response = api_client.patch( + reverse("api:settings:update"), + {"inbound_email_enabled": True, "allow_new_signups": False}, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert response.json()["allow_new_signups"] is False + assert response.json()["inbound_email_enabled"] is False + + @pytest.mark.django_db def test_realtime_recovery_only_pins_authenticated_settings_reads( api_client, data_fixture diff --git a/backend/tests/baserow/contrib/automation/api/nodes/test_nodes_views.py b/backend/tests/baserow/contrib/automation/api/nodes/test_nodes_views.py index b9f754fa8c..8c8bcae09c 100644 --- a/backend/tests/baserow/contrib/automation/api/nodes/test_nodes_views.py +++ b/backend/tests/baserow/contrib/automation/api/nodes/test_nodes_views.py @@ -14,6 +14,7 @@ from rest_framework.status import ( from baserow.contrib.automation.nodes.models import AutomationNode from baserow.contrib.automation.nodes.node_types import ( + CoreInboundEmailTriggerNodeType, CorePeriodicTriggerNodeType, LocalBaserowRowsCreatedNodeTriggerType, ) @@ -975,6 +976,36 @@ def test_simulate_dispatch_trigger_node( mock_async_start_workflow.assert_not_called() +@pytest.mark.django_db() +@patch( + "baserow.contrib.automation.workflows.service.AutomationWorkflowHandler.async_start_workflow" +) +def test_simulate_dispatch_email_trigger_node_waits_for_an_email( + mock_async_start_workflow, api_client, data_fixture +): + # The email trigger is not immediately dispatchable: testing it must arm + # the workflow to wait for a message sent to the `test-` address, and must + # not fabricate sample data in the meantime. + user, token = data_fixture.create_user_and_token() + workflow = data_fixture.create_automation_workflow( + user=user, trigger_type=CoreInboundEmailTriggerNodeType.type + ) + trigger_node = workflow.get_trigger() + assert workflow.simulate_until_node is None + + api_kwargs = get_api_kwargs(token) + url = reverse(API_URL_SIMULATE_DISPATCH, kwargs={"node_id": trigger_node.id}) + response = api_client.post(url, **api_kwargs) + + assert response.status_code == HTTP_202_ACCEPTED + + workflow.refresh_from_db() + assert workflow.simulate_until_node_id == trigger_node.id + mock_async_start_workflow.assert_not_called() + trigger_node.service.refresh_from_db() + assert trigger_node.service.specific.sample_data is None + + @pytest.mark.django_db() @patch( "baserow.contrib.automation.workflows.service.AutomationWorkflowHandler.async_start_workflow" diff --git a/backend/tests/baserow/contrib/automation/nodes/test_node_types.py b/backend/tests/baserow/contrib/automation/nodes/test_node_types.py index e364255966..f32da69df7 100644 --- a/backend/tests/baserow/contrib/automation/nodes/test_node_types.py +++ b/backend/tests/baserow/contrib/automation/nodes/test_node_types.py @@ -2,6 +2,7 @@ import uuid from datetime import datetime from unittest.mock import MagicMock, patch +from django.test import override_settings from django.urls import reverse from django.utils.timezone import now @@ -805,3 +806,61 @@ def test_automation_node_type_has_display_name(node_type): assert node_type.display_name != _("Unnamed element"), ( f"{type(node_type).__name__}.display_name is still the default 'Unnamed element'" ) + + +@pytest.mark.parametrize( + "missing", + [ + "INBOUND_EMAIL_DOMAIN", + "INBOUND_EMAIL_WEBHOOK_SECRET", + "INBOUND_EMAIL_RECEIVER_URL", + ], +) +def test_inbound_email_trigger_deactivated_when_any_setting_is_missing(missing): + from baserow.contrib.automation.nodes.registries import ( + automation_node_type_registry, + ) + + values = { + "INBOUND_EMAIL_DOMAIN": "inbound.example.com", + "INBOUND_EMAIL_WEBHOOK_SECRET": "s", + # Without the receiver URL the sweep cannot delete handed-over messages + # and the mail server's disk would grow forever, so the trigger stays off. + "INBOUND_EMAIL_RECEIVER_URL": "http://email-receiver:8880", + missing: "", + } + node_type = automation_node_type_registry.get("email_trigger") + with override_settings(**values): + assert node_type.is_deactivated(None) is True + + +@override_settings( + INBOUND_EMAIL_DOMAIN="inbound.example.com", + INBOUND_EMAIL_WEBHOOK_SECRET="s", + INBOUND_EMAIL_RECEIVER_URL="http://email-receiver:8880", +) +def test_inbound_email_trigger_active_when_configured(): + from baserow.contrib.automation.nodes.registries import ( + automation_node_type_registry, + ) + + node_type = automation_node_type_registry.get("email_trigger") + assert node_type.is_deactivated(None) is False + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN="", INBOUND_EMAIL_WEBHOOK_SECRET="") +def test_create_inbound_email_trigger_blocked_when_unconfigured(data_fixture): + from rest_framework.exceptions import PermissionDenied + + from baserow.contrib.automation.nodes.registries import ( + automation_node_type_registry, + ) + from baserow.contrib.automation.nodes.service import AutomationNodeService + + user = data_fixture.create_user() + workflow = data_fixture.create_automation_workflow(user=user) + + node_type = automation_node_type_registry.get("email_trigger") + with pytest.raises(PermissionDenied): + AutomationNodeService().create_node(user, node_type, workflow) diff --git a/backend/tests/baserow/contrib/automation/nodes/test_node_ws_signals.py b/backend/tests/baserow/contrib/automation/nodes/test_node_ws_signals.py new file mode 100644 index 0000000000..eec07b6cb1 --- /dev/null +++ b/backend/tests/baserow/contrib/automation/nodes/test_node_ws_signals.py @@ -0,0 +1,91 @@ +import json +from unittest.mock import patch + +from django.core.serializers.json import DjangoJSONEncoder + +import pytest + +from baserow.contrib.automation.nodes.node_types import ( + CoreInboundEmailTriggerNodeType, +) +from baserow.contrib.automation.nodes.signals import automation_node_updated +from baserow.contrib.automation.nodes.ws.signals import ( + AUTOMATION_NODE_EVENT_MAX_BYTES, + bounded_node_event, +) + + +def _size(event): + return len( + json.dumps( + event, cls=DjangoJSONEncoder, ensure_ascii=False, separators=(",", ":") + ).encode("utf-8") + ) + + +def test_bounded_node_event_leaves_small_events_untouched(): + event = { + "type": "automation_node_updated", + "node": {"id": 1, "service": {"sample_data": {"data": {"subject": "Hi"}}}}, + } + + assert bounded_node_event(event) is event + + +def test_bounded_node_event_drops_sample_data_and_flags_refresh_when_too_large(): + event = { + "type": "automation_node_updated", + "node": { + "id": 1, + "label": "Email Trigger", + "service": { + "id": 5, + "sample_data": {"data": {"body_html": "x" * (2 * 1024 * 1024)}}, + }, + }, + } + assert _size(event) > AUTOMATION_NODE_EVENT_MAX_BYTES + + bounded = bounded_node_event(event) + + assert bounded["requires_refresh"] is True + assert bounded["node"]["service"]["sample_data"] is None + assert bounded["node"]["service"]["id"] == 5 + assert bounded["node"]["label"] == "Email Trigger" + assert _size(bounded) <= AUTOMATION_NODE_EVENT_MAX_BYTES + # The original is not mutated: it may still be used by the caller. + assert event["node"]["service"]["sample_data"]["data"]["body_html"] + + +@pytest.mark.django_db +@pytest.mark.parametrize("oversized", [True, False]) +def test_node_updated_broadcast_is_bounded( + data_fixture, django_capture_on_commit_callbacks, oversized +): + user = data_fixture.create_user() + workflow = data_fixture.create_automation_workflow( + user=user, trigger_type=CoreInboundEmailTriggerNodeType.type + ) + node = workflow.get_trigger() + service = node.service.specific + body = "x" * (2 * 1024 * 1024) if oversized else "small body" + service.sample_data = {"data": {"body_html": body}} + service.save() + + with ( + patch( + "baserow.contrib.automation.nodes.ws.signals.broadcast_to_permitted_users" + ) as mocked, + django_capture_on_commit_callbacks(execute=True), + ): + automation_node_updated.send(None, user=None, node=node) + + payload = mocked.delay.call_args.args[4] + assert payload["type"] == "automation_node_updated" + assert payload["node"]["id"] == node.id + if oversized: + assert payload["requires_refresh"] is True + assert payload["node"]["service"]["sample_data"] is None + else: + assert "requires_refresh" not in payload + assert payload["node"]["service"]["sample_data"]["data"]["body_html"] == body diff --git a/backend/tests/baserow/contrib/integrations/core/api/inbound_email/__init__.py b/backend/tests/baserow/contrib/integrations/core/api/inbound_email/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/backend/tests/baserow/contrib/integrations/core/api/inbound_email/test_inbound_email_views.py b/backend/tests/baserow/contrib/integrations/core/api/inbound_email/test_inbound_email_views.py new file mode 100644 index 0000000000..e049013b32 --- /dev/null +++ b/backend/tests/baserow/contrib/integrations/core/api/inbound_email/test_inbound_email_views.py @@ -0,0 +1,355 @@ +from datetime import timedelta +from unittest.mock import patch + +from django.core.cache import cache +from django.test import override_settings +from django.urls import reverse +from django.utils import timezone + +import pytest +from rest_framework.status import ( + HTTP_200_OK, + HTTP_400_BAD_REQUEST, + HTTP_401_UNAUTHORIZED, + HTTP_405_METHOD_NOT_ALLOWED, +) + +from baserow.contrib.automation.history.models import AutomationWorkflowHistory +from baserow.contrib.automation.workflows.constants import WorkflowState +from baserow.contrib.integrations.core.inbound_email_receiver import ( + INBOUND_EMAIL_RECEIVER_DELETE_DELAY_SECONDS, +) +from baserow.contrib.integrations.tasks import delete_inbound_email_receiver_message + +from ...inbound_email_test_utils import make_mox_payload + +INBOUND_DOMAIN = "inbound.test" +RECEIVER_URL = "http://email-receiver:8880" +SECRET = "super-secret-value" +TOKEN = "a" * 32 +ADDRESS = f"{TOKEN}@{INBOUND_DOMAIN}" +# Like the HTTP trigger's `?test=true`, this targets the draft workflow. +TEST_ADDRESS = f"test-{TOKEN}@{INBOUND_DOMAIN}" + + +def get_url(): + return reverse("api:inbound_email") + + +@pytest.fixture(autouse=True) +def clear_cache(): + cache.clear() + + +@pytest.fixture(autouse=True) +def receiver_deletion(): + """ + Every accepted webhook queues the deletion of its message from the mail + server once the request commits. Celery runs eagerly in tests and there is + no receiver to reach, so the queueing itself is captured instead. + """ + + with patch.object(delete_inbound_email_receiver_message, "apply_async") as m: + yield m + + +@pytest.mark.django_db +@override_settings( + INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER_URL, +) +@pytest.mark.parametrize("http_method", ["get", "put", "patch", "delete"]) +def test_rejects_disallowed_methods(api_client, http_method): + resp = getattr(api_client, http_method)(get_url(), HTTP_AUTHORIZATION=SECRET) + + assert resp.status_code == HTTP_405_METHOD_NOT_ALLOWED + + +@pytest.mark.django_db +@override_settings( + INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER_URL, +) +def test_rejects_missing_authorization_header(api_client): + resp = api_client.post(get_url(), make_mox_payload(ADDRESS), format="json") + + assert resp.status_code == HTTP_401_UNAUTHORIZED + + +@pytest.mark.django_db +@override_settings( + INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER_URL, +) +def test_rejects_wrong_secret(api_client): + resp = api_client.post( + get_url(), + make_mox_payload(ADDRESS), + format="json", + HTTP_AUTHORIZATION="wrong-secret", + ) + + assert resp.status_code == HTTP_401_UNAUTHORIZED + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, INBOUND_EMAIL_WEBHOOK_SECRET="") +def test_rejects_all_requests_when_secret_not_configured(api_client): + # An empty Authorization header must never match an empty configured + # secret. + resp = api_client.post( + get_url(), make_mox_payload(ADDRESS), format="json", HTTP_AUTHORIZATION="" + ) + + assert resp.status_code == HTTP_401_UNAUTHORIZED + + +@pytest.mark.django_db +@override_settings( + INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER_URL, +) +def test_rejects_malformed_payload(api_client): + resp = api_client.post( + get_url(), + {"not": "a mox payload"}, + format="json", + HTTP_AUTHORIZATION=SECRET, + ) + + assert resp.status_code == HTTP_400_BAD_REQUEST + assert resp.json()["error"] == "ERROR_INVALID_INBOUND_EMAIL_PAYLOAD" + + +@pytest.mark.django_db +@override_settings( + INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER_URL, +) +def test_discards_unknown_token(api_client): + resp = api_client.post( + get_url(), + make_mox_payload(ADDRESS), + format="json", + HTTP_AUTHORIZATION=SECRET, + ) + + assert resp.status_code == HTTP_200_OK + assert resp.json() == {"status": "discarded"} + + +@pytest.mark.django_db(transaction=True) +@override_settings( + INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER_URL, +) +def test_accepts_email_and_starts_live_workflow( + api_client, data_fixture, receiver_deletion +): + user, _ = data_fixture.create_user_and_token() + workspace = data_fixture.create_workspace(user=user) + automation = data_fixture.create_automation_application( + user=user, workspace=workspace + ) + workflow = data_fixture.create_automation_workflow( + user=user, automation=automation, state=WorkflowState.LIVE, create_trigger=False + ) + integration = data_fixture.create_local_baserow_integration( + user=user, application=automation + ) + + trigger_node = data_fixture.create_inbound_email_trigger_node( + workflow=workflow, + service_kwargs={"token": TOKEN, "is_public": True}, + ) + + database = data_fixture.create_database_application(user=user, workspace=workspace) + table, fields, _ = data_fixture.build_table( + user=user, + database=database, + columns=[("Name", "text")], + rows=[], + ) + action_service = data_fixture.create_local_baserow_upsert_row_service( + table=table, + integration=integration, + ) + action_service.field_mappings.create( + field=fields[0], + value=f"get('previous_node.{trigger_node.id}.subject')", + ) + data_fixture.create_local_baserow_create_row_action_node( + workflow=workflow, + service=action_service, + ) + + resp = api_client.post( + get_url(), + make_mox_payload(ADDRESS), + format="json", + HTTP_AUTHORIZATION=SECRET, + ) + + assert resp.status_code == HTTP_200_OK + assert resp.json() == {"status": "accepted"} + + model = table.get_model() + rows = model.objects.all() + assert len(rows) == 1 + assert getattr(rows[0], f"field_{fields[0].id}") == "Hello from Ada" + + # The message is deleted from the mail server once the request committed. + receiver_deletion.assert_called_once_with( + args=[42], countdown=INBOUND_EMAIL_RECEIVER_DELETE_DELAY_SECONDS + ) + + +@pytest.mark.django_db(transaction=True) +@override_settings( + INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER_URL, +) +def test_duplicate_delivery_is_idempotent(api_client, data_fixture): + user = data_fixture.create_user() + workflow = data_fixture.create_automation_workflow( + user=user, state=WorkflowState.LIVE, create_trigger=False + ) + data_fixture.create_inbound_email_trigger_node( + workflow=workflow, + service_kwargs={"token": TOKEN, "is_public": True}, + ) + + payload = make_mox_payload(ADDRESS) + + resp = api_client.post(get_url(), payload, format="json", HTTP_AUTHORIZATION=SECRET) + assert resp.json() == {"status": "accepted"} + + resp = api_client.post(get_url(), payload, format="json", HTTP_AUTHORIZATION=SECRET) + assert resp.json() == {"status": "duplicate"} + + assert AutomationWorkflowHistory.objects.count() == 1 + + +@pytest.mark.django_db(transaction=True) +@override_settings( + INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER_URL, +) +def test_draft_workflow_not_started_outside_test_window(api_client, data_fixture): + user = data_fixture.create_user() + workflow = data_fixture.create_automation_workflow( + user=user, state=WorkflowState.DRAFT, create_trigger=False + ) + data_fixture.create_inbound_email_trigger_node( + workflow=workflow, + service_kwargs={"token": TOKEN}, + ) + + resp = api_client.post( + get_url(), + make_mox_payload(TEST_ADDRESS), + format="json", + HTTP_AUTHORIZATION=SECRET, + ) + + # The test address matches the draft service, so the message is accepted, + # but the draft workflow is not started because it is not in a test run + # window. + assert resp.json() == {"status": "accepted"} + assert AutomationWorkflowHistory.objects.count() == 0 + + +@pytest.mark.django_db(transaction=True) +@override_settings( + INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER_URL, +) +def test_test_address_starts_draft_workflow_in_test_window(api_client, data_fixture): + user = data_fixture.create_user() + workflow = data_fixture.create_automation_workflow( + user=user, + state=WorkflowState.DRAFT, + create_trigger=False, + allow_test_run_until=timezone.now() + timedelta(minutes=5), + ) + data_fixture.create_inbound_email_trigger_node( + workflow=workflow, + service_kwargs={"token": TOKEN}, + ) + + resp = api_client.post( + get_url(), + make_mox_payload(TEST_ADDRESS), + format="json", + HTTP_AUTHORIZATION=SECRET, + ) + + assert resp.json() == {"status": "accepted"} + assert AutomationWorkflowHistory.objects.count() == 1 + + +@pytest.mark.django_db(transaction=True) +@override_settings( + INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER_URL, +) +def test_bare_address_does_not_reach_a_draft_workflow(api_client, data_fixture): + user = data_fixture.create_user() + workflow = data_fixture.create_automation_workflow( + user=user, + state=WorkflowState.DRAFT, + create_trigger=False, + allow_test_run_until=timezone.now() + timedelta(minutes=5), + ) + data_fixture.create_inbound_email_trigger_node( + workflow=workflow, + service_kwargs={"token": TOKEN}, + ) + + resp = api_client.post( + get_url(), + make_mox_payload(ADDRESS), + format="json", + HTTP_AUTHORIZATION=SECRET, + ) + + # Only the published version answers to the bare address; there is none. + assert resp.json() == {"status": "discarded"} + assert AutomationWorkflowHistory.objects.count() == 0 + + +@pytest.mark.django_db(transaction=True) +@override_settings( + INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER_URL, +) +def test_test_address_does_not_reach_a_published_workflow(api_client, data_fixture): + user = data_fixture.create_user() + workflow = data_fixture.create_automation_workflow( + user=user, state=WorkflowState.LIVE, create_trigger=False + ) + data_fixture.create_inbound_email_trigger_node( + workflow=workflow, + service_kwargs={"token": TOKEN, "is_public": True}, + ) + + resp = api_client.post( + get_url(), + make_mox_payload(TEST_ADDRESS), + format="json", + HTTP_AUTHORIZATION=SECRET, + ) + + assert resp.json() == {"status": "discarded"} + assert AutomationWorkflowHistory.objects.count() == 0 diff --git a/backend/tests/baserow/contrib/integrations/core/inbound_email_test_utils.py b/backend/tests/baserow/contrib/integrations/core/inbound_email_test_utils.py new file mode 100644 index 0000000000..f6565e649c --- /dev/null +++ b/backend/tests/baserow/contrib/integrations/core/inbound_email_test_utils.py @@ -0,0 +1,63 @@ +def make_mox_payload(rcpt_to, **overrides): + """ + Builds a realistic mox `webhook.Incoming` JSON payload, as POSTed by mox's + incoming-delivery webhook, targeting the provided recipient address. + """ + + payload = { + "Version": 0, + "From": [{"Name": "Ada Lovelace", "Address": "ada@example.com"}], + "To": [{"Name": "", "Address": rcpt_to}], + "CC": [], + "BCC": [], + "ReplyTo": [{"Name": "Ada Lovelace", "Address": "ada@example.com"}], + "Subject": "Hello from Ada", + "MessageID": "", + "InReplyTo": "", + "References": [], + "Date": "2026-07-15T12:00:00Z", + "Text": "Hi there,\n\nThis is the plain text body.\n", + "HTML": "

Hi there,

This is the HTML body.

", + "Structure": { + "ContentType": "multipart/mixed", + "ContentTypeParams": {"boundary": "x"}, + "ContentID": "", + "ContentDisposition": "", + "Filename": "", + "DecodedSize": 0, + "Parts": [ + { + "ContentType": "text/plain", + "ContentTypeParams": {"charset": "utf-8"}, + "ContentID": "", + "ContentDisposition": "", + "Filename": "", + "DecodedSize": 45, + "Parts": [], + }, + { + "ContentType": "application/pdf", + "ContentTypeParams": {}, + "ContentID": "", + "ContentDisposition": "attachment", + "Filename": "invoice.pdf", + "DecodedSize": 12345, + "Parts": [], + }, + ], + }, + "Meta": { + "MsgID": 42, + "MailFrom": "ada@example.com", + "MailFromValidated": True, + "MsgFromValidated": True, + "RcptTo": rcpt_to, + "DKIMVerifiedDomains": ["example.com"], + "RemoteIP": "203.0.113.10", + "Received": "2026-07-15T12:00:01Z", + "MailboxName": "Inbox", + "Automated": False, + }, + } + payload.update(overrides) + return payload diff --git a/backend/tests/baserow/contrib/integrations/core/test_core_inbound_email_trigger_service_type.py b/backend/tests/baserow/contrib/integrations/core/test_core_inbound_email_trigger_service_type.py new file mode 100644 index 0000000000..82eca08766 --- /dev/null +++ b/backend/tests/baserow/contrib/integrations/core/test_core_inbound_email_trigger_service_type.py @@ -0,0 +1,341 @@ +from unittest.mock import MagicMock + +from django.test import override_settings + +import pytest + +from baserow.contrib.integrations.core.exceptions import ( + CoreInboundEmailTriggerServiceDoesNotExist, +) +from baserow.contrib.integrations.core.inbound_email import ( + InboundEmail, + InboundEmailAddress, +) +from baserow.contrib.integrations.core.service_types import ( + CoreInboundEmailTriggerServiceType, +) +from baserow.core.registries import ImportExportConfig +from baserow.test_utils.pytest_conftest import fake_import_formula + +TOKEN = "a" * 32 + + +def make_email(): + return InboundEmail( + from_=InboundEmailAddress(name="Ada", address="ada@example.com"), + subject="Hello", + body_text="Hi", + message_id="", + ) + + +@pytest.mark.django_db +def test_token_is_generated_on_creation(data_fixture): + service = data_fixture.create_core_inbound_email_trigger_service() + + assert len(service.token) == 32 + assert service.token == service.token.lower() + + other_service = data_fixture.create_core_inbound_email_trigger_service() + assert other_service.token != service.token + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN="inbound.test") +def test_email_address_property(data_fixture): + service = data_fixture.create_core_inbound_email_trigger_service(token=TOKEN) + + assert service.email_address == f"{TOKEN}@inbound.test" + assert service.test_email_address == f"test-{TOKEN}@inbound.test" + + with override_settings(INBOUND_EMAIL_DOMAIN=""): + assert service.email_address is None + assert service.test_email_address is None + + +@pytest.mark.django_db +def test_max_message_size_mb_property_mirrors_setting(data_fixture): + service = data_fixture.create_core_inbound_email_trigger_service(token=TOKEN) + + with override_settings(INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB=40): + assert service.max_message_size_mb == 40 + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN="inbound.test") +def test_serializer_exposes_address_and_size_limit_read_only(data_fixture): + from baserow.api.services.serializers import ServiceSerializer + from baserow.core.services.registries import service_type_registry + + service = data_fixture.create_core_inbound_email_trigger_service(token=TOKEN) + + with override_settings(INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB=40): + data = service_type_registry.get_serializer(service, ServiceSerializer).data + + assert data["email_address"] == f"{TOKEN}@inbound.test" + assert data["test_email_address"] == f"test-{TOKEN}@inbound.test" + assert data["max_message_size_mb"] == 40 + + # Both values describe the instance, not the service, so they must not be + # writable. + request_serializer = service_type_registry.get_serializer( + service, ServiceSerializer, request=True + ) + request_data = request_serializer.data + assert "email_address" not in request_data + assert "test_email_address" not in request_data + assert "max_message_size_mb" not in request_data + # The token is the address's only secret and is_public is managed by + # publishing, so neither can be set through the API either; the address is + # only ever changed through the write-only `regenerate_token` flag. + assert "token" not in request_serializer.fields + assert "is_public" not in request_serializer.fields + assert request_serializer.fields["regenerate_token"].write_only + + +@pytest.mark.django_db +def test_process_inbound_email_raises_if_unknown_token(data_fixture): + with pytest.raises(CoreInboundEmailTriggerServiceDoesNotExist): + CoreInboundEmailTriggerServiceType().process_inbound_email(TOKEN, make_email()) + + +@pytest.mark.django_db +@pytest.mark.parametrize( + "is_public,simulate", + [ + (True, True), + (False, False), + ], +) +def test_process_inbound_email_raises_if_no_service_of_that_version( + data_fixture, is_public, simulate +): + # Like the HTTP trigger's `?test=true`: the `test-` address only reaches + # the draft, the bare address only the published version. + data_fixture.create_core_inbound_email_trigger_service( + token=TOKEN, is_public=is_public + ) + + with pytest.raises(CoreInboundEmailTriggerServiceDoesNotExist): + CoreInboundEmailTriggerServiceType().process_inbound_email( + TOKEN, make_email(), simulate=simulate + ) + + +@pytest.mark.django_db +@pytest.mark.parametrize( + "is_public,simulate", + [ + (True, False), + (False, True), + ], +) +def test_process_inbound_email_dispatches_only_the_targeted_version( + data_fixture, is_public, simulate +): + trigger_node = data_fixture.create_inbound_email_trigger_node( + service_kwargs={"token": TOKEN}, + ) + draft_service = trigger_node.service.specific + published_service = data_fixture.create_core_inbound_email_trigger_service( + token=TOKEN, is_public=True + ) + expected = published_service if is_public else draft_service + + service_type = CoreInboundEmailTriggerServiceType() + service_type.on_event = MagicMock() + + service_type.process_inbound_email(TOKEN, make_email(), simulate=simulate) + + services, event_payload = service_type.on_event.call_args.args + assert [service.id for service in services] == [expected.id] + payload = event_payload(expected) + assert payload["subject"] == "Hello" + assert payload["from"] == {"name": "Ada", "address": "ada@example.com"} + + +@pytest.mark.django_db +def test_process_inbound_email_uses_the_latest_published_service(data_fixture): + # Publishing can keep the previous published service around for a while; + # both share the token, so the newest one must win. + data_fixture.create_core_inbound_email_trigger_service(token=TOKEN, is_public=True) + latest = data_fixture.create_core_inbound_email_trigger_service( + token=TOKEN, is_public=True + ) + + service_type = CoreInboundEmailTriggerServiceType() + service_type.on_event = MagicMock() + + service_type.process_inbound_email(TOKEN, make_email()) + + services, _ = service_type.on_event.call_args.args + assert [service.id for service in services] == [latest.id] + + +@pytest.mark.django_db +def test_prepare_values_regenerates_token(data_fixture): + user = data_fixture.create_user() + service_type = CoreInboundEmailTriggerServiceType() + + values = service_type.prepare_values({"regenerate_token": True}, user) + assert len(values["token"]) == 32 + + values = service_type.prepare_values({"regenerate_token": False}, user) + assert "token" not in values + + values = service_type.prepare_values({}, user) + assert "token" not in values + + +@pytest.mark.django_db +@pytest.mark.parametrize("is_publishing", [True, False]) +def test_import_serialized_sets_is_public(data_fixture, is_publishing): + trigger_node = data_fixture.create_inbound_email_trigger_node() + service = trigger_node.service.specific + + service_type = CoreInboundEmailTriggerServiceType() + + serialized_service = service_type.export_serialized(service) + assert serialized_service["is_public"] is False + + import_export_config = ImportExportConfig( + include_permission_data=True, + reduce_disk_space_usage=False, + exclude_sensitive_data=False, + is_publishing=is_publishing, + ) + instance = service_type.import_serialized( + None, + serialized_service, + {}, + import_export_config, + import_formula=fake_import_formula, + ) + + assert instance.is_public is is_publishing + if is_publishing: + # Publishing must keep the same token so the address keeps working. + assert instance.token == service.token + else: + # Any other import is a new trigger and gets its own address. + assert instance.token != service.token + + +@pytest.mark.django_db +@pytest.mark.parametrize("is_duplicate", [True, False]) +def test_import_serialized_regenerates_token_unless_publishing( + data_fixture, is_duplicate +): + """ + Duplicating, installing a template and importing an exported application + must all produce a new address. Keeping the token would let an import of + someone else's export take over their trigger's mail on the same instance, + because the newest published service with a token is the one dispatched. + """ + + trigger_node = data_fixture.create_inbound_email_trigger_node() + service = trigger_node.service.specific + + service_type = CoreInboundEmailTriggerServiceType() + serialized_service = service_type.export_serialized(service) + + import_export_config = ImportExportConfig( + include_permission_data=True, + reduce_disk_space_usage=False, + exclude_sensitive_data=False, + is_duplicate=is_duplicate, + ) + instance = service_type.import_serialized( + None, + serialized_service, + {}, + import_export_config, + import_formula=fake_import_formula, + ) + + assert len(instance.token) == 32 + assert instance.token != service.token + + +@pytest.mark.django_db +def test_generate_schema(data_fixture): + trigger_node = data_fixture.create_inbound_email_trigger_node() + service = trigger_node.service.specific + + schema = CoreInboundEmailTriggerServiceType().generate_schema(service) + + assert schema["title"] == f"EmailTrigger{service.id}Schema" + assert schema["type"] == "object" + properties = schema["properties"] + assert set(properties.keys()) == { + "from", + "to", + "cc", + "reply_to", + "rcpt_to", + "recipient_tag", + "subject", + "body_text", + "body_html", + "body_html_truncated", + "body_text_truncated", + "message_id", + "in_reply_to", + "received_at", + "attachments", + "sender_validated", + "dkim_verified_domains", + "remote_ip", + } + assert properties["from"]["type"] == "object" + assert properties["to"]["type"] == "array" + assert properties["attachments"]["items"]["properties"]["filename"] == { + "type": "string", + "title": "Filename", + } + + +@pytest.mark.django_db +def test_generate_schema_with_allowed_fields(data_fixture): + trigger_node = data_fixture.create_inbound_email_trigger_node() + service = trigger_node.service.specific + + schema = CoreInboundEmailTriggerServiceType().generate_schema( + service, allowed_fields=["subject", "body_text"] + ) + + assert set(schema["properties"].keys()) == {"subject", "body_text"} + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN="inbound.test") +def test_dispatch_data_returns_sample_payload_without_event(data_fixture): + trigger_node = data_fixture.create_inbound_email_trigger_node( + service_kwargs={"token": TOKEN}, + ) + service = trigger_node.service.specific + + dispatch_context = MagicMock() + dispatch_context.event_payload = None + + payload = CoreInboundEmailTriggerServiceType().dispatch_data( + service, {}, dispatch_context + ) + + assert payload["subject"] == "Sample email subject" + assert payload["to"] == [{"name": "", "address": f"{TOKEN}@inbound.test"}] + + +@pytest.mark.django_db +def test_dispatch_data_returns_event_payload(data_fixture): + trigger_node = data_fixture.create_inbound_email_trigger_node() + service = trigger_node.service.specific + + dispatch_context = MagicMock() + dispatch_context.event_payload = {"subject": "real email"} + + payload = CoreInboundEmailTriggerServiceType().dispatch_data( + service, {}, dispatch_context + ) + + assert payload == {"subject": "real email"} diff --git a/backend/tests/baserow/contrib/integrations/core/test_inbound_email_handler.py b/backend/tests/baserow/contrib/integrations/core/test_inbound_email_handler.py new file mode 100644 index 0000000000..0525849596 --- /dev/null +++ b/backend/tests/baserow/contrib/integrations/core/test_inbound_email_handler.py @@ -0,0 +1,534 @@ +from unittest.mock import MagicMock, patch + +from django.core.cache import cache +from django.test import override_settings + +import pytest +from loguru import logger + +from baserow.contrib.integrations.core.exceptions import InvalidInboundEmailPayload +from baserow.contrib.integrations.core.inbound_email import ( + HANDLE_STATUS_ACCEPTED, + HANDLE_STATUS_DISCARDED, + HANDLE_STATUS_DUPLICATE, + INBOUND_EMAIL_TEST_PREFIX, + MOX_WEBHOOK_PART_LIMIT_BYTES, + InboundEmail, + InboundEmailAddress, + InboundEmailHandler, + InboundEmailTarget, + normalize_mox_payload, +) + +from .inbound_email_test_utils import make_mox_payload + +INBOUND_DOMAIN = "inbound.test" +TOKEN = "a" * 32 +ADDRESS = f"{TOKEN}@{INBOUND_DOMAIN}" +TEST_ADDRESS = f"{INBOUND_EMAIL_TEST_PREFIX}{TOKEN}@{INBOUND_DOMAIN}" + + +@pytest.fixture(autouse=True) +def clear_cache(): + cache.clear() + + +@pytest.fixture +def inbound_email_logs(): + """ + Collects the loguru messages emitted by the handler so tests can assert on + the outcome that operators see in the server log. + """ + + messages = [] + sink_id = logger.add(messages.append, level="INFO") + yield messages + logger.remove(sink_id) + + +def test_normalize_mox_payload(): + email = normalize_mox_payload(make_mox_payload(ADDRESS)) + + assert email.from_ == InboundEmailAddress( + name="Ada Lovelace", address="ada@example.com" + ) + assert email.to == [InboundEmailAddress(name="", address=ADDRESS)] + assert email.cc == [] + assert email.reply_to == [ + InboundEmailAddress(name="Ada Lovelace", address="ada@example.com") + ] + assert email.subject == "Hello from Ada" + assert email.body_text == "Hi there,\n\nThis is the plain text body.\n" + assert email.body_html == "

Hi there,

This is the HTML body.

" + assert email.message_id == "" + assert email.in_reply_to == "" + assert email.received_at == "2026-07-15T12:00:01Z" + assert len(email.attachments) == 1 + assert email.attachments[0].filename == "invoice.pdf" + assert email.attachments[0].content_type == "application/pdf" + assert email.attachments[0].size == 12345 + assert email.sender_validated is True + assert email.dkim_verified_domains == ["example.com"] + assert email.remote_ip == "203.0.113.10" + assert email.rcpt_to == ADDRESS + assert email.is_automated is False + assert email.internal_message_id == "42" + + +def test_normalize_mox_payload_to_payload(): + payload = normalize_mox_payload(make_mox_payload(ADDRESS)).to_payload() + + assert payload["from"] == {"name": "Ada Lovelace", "address": "ada@example.com"} + assert payload["to"] == [{"name": "", "address": ADDRESS}] + assert payload["subject"] == "Hello from Ada" + assert payload["attachments"] == [ + {"filename": "invoice.pdf", "content_type": "application/pdf", "size": 12345} + ] + assert payload["sender_validated"] is True + assert payload["dkim_verified_domains"] == ["example.com"] + # The envelope recipient and its sub-address tag are exposed for routing. + assert payload["rcpt_to"] == ADDRESS + assert payload["recipient_tag"] == "" + # The automation flag stays internal (used for loop protection only). + assert "is_automated" not in payload + + +@pytest.mark.parametrize( + "data", + [ + None, + [], + "a string", + {}, + {"From": []}, + {"Meta": {}}, + {"From": "not-a-list", "Meta": {}}, + {"From": [], "Meta": "not-a-dict"}, + ], +) +def test_normalize_mox_payload_invalid(data): + with pytest.raises(InvalidInboundEmailPayload): + normalize_mox_payload(data) + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_extract_targets_prefers_rcpt_to(): + email = InboundEmail(rcpt_to=ADDRESS) + assert InboundEmailHandler().extract_targets(email) == [InboundEmailTarget(TOKEN)] + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_extract_targets_falls_back_to_headers(): + other_token = "b" * 32 + email = InboundEmail( + rcpt_to="", + to=[InboundEmailAddress(address=f"someone@example.com")], + cc=[InboundEmailAddress(address=f"{other_token}@{INBOUND_DOMAIN}")], + ) + assert InboundEmailHandler().extract_targets(email) == [ + InboundEmailTarget(other_token) + ] + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_extract_targets_multiple_and_deduplicated(): + other_token = "b" * 32 + email = InboundEmail( + rcpt_to=ADDRESS, + to=[ + InboundEmailAddress(address=ADDRESS), + InboundEmailAddress(address=f"{other_token}@{INBOUND_DOMAIN}"), + ], + ) + assert InboundEmailHandler().extract_targets(email) == [ + InboundEmailTarget(TOKEN), + InboundEmailTarget(other_token), + ] + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +@pytest.mark.parametrize( + "address", + [ + f"{TOKEN}@other-domain.test", + f"not-a-token@{INBOUND_DOMAIN}", + f"{'A' * 31}@{INBOUND_DOMAIN}", + "no-at-sign", + "", + ], +) +def test_extract_targets_rejects_invalid_recipients(address): + email = InboundEmail(rcpt_to=address) + assert InboundEmailHandler().extract_targets(email) == [] + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_extract_targets_is_case_insensitive(): + email = InboundEmail(rcpt_to=f"{TOKEN.upper()}@{INBOUND_DOMAIN.upper()}") + assert InboundEmailHandler().extract_targets(email) == [InboundEmailTarget(TOKEN)] + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_extract_targets_strips_subaddress_tag(): + # `token+anything@domain` must resolve to the same `token` trigger. + for tag in ["gmail", "hotmail", "with+extra+pluses", "MixedCase"]: + email = InboundEmail(rcpt_to=f"{TOKEN}+{tag}@{INBOUND_DOMAIN}") + assert InboundEmailHandler().extract_targets(email) == [ + InboundEmailTarget(TOKEN) + ] + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_extract_targets_deduplicates_across_tags(): + # The same token reached via different tags must dispatch the trigger once. + email = InboundEmail( + rcpt_to=f"{TOKEN}+gmail@{INBOUND_DOMAIN}", + to=[InboundEmailAddress(address=f"{TOKEN}+hotmail@{INBOUND_DOMAIN}")], + ) + assert InboundEmailHandler().extract_targets(email) == [InboundEmailTarget(TOKEN)] + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_tagged_recipient_full_mox_path(): + # Full wire-format path: a mox webhook for `token+bob@domain` resolves to the + # `token` trigger and carries the tag through to the workflow payload. + email = normalize_mox_payload(make_mox_payload(f"{TOKEN}+bob@{INBOUND_DOMAIN}")) + assert InboundEmailHandler().extract_targets(email) == [InboundEmailTarget(TOKEN)] + assert email.to_payload()["recipient_tag"] == "bob" + + +def test_to_payload_exposes_recipient_tag(): + payload = InboundEmail(rcpt_to=f"{TOKEN}+sales@{INBOUND_DOMAIN}").to_payload() + assert payload["rcpt_to"] == f"{TOKEN}+sales@{INBOUND_DOMAIN}" + # The tag is returned as received (case preserved) for exact routing. + assert payload["recipient_tag"] == "sales" + + payload = InboundEmail(rcpt_to=f"{TOKEN}+Team-A@{INBOUND_DOMAIN}").to_payload() + assert payload["recipient_tag"] == "Team-A" + + payload = InboundEmail(rcpt_to=f"{TOKEN}@{INBOUND_DOMAIN}").to_payload() + assert payload["recipient_tag"] == "" + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_discards_automated_email(): + payload = make_mox_payload(ADDRESS) + payload["Meta"]["Automated"] = True + + handler = InboundEmailHandler() + with patch.object(handler, "_process_target") as mocked: + assert handler.handle_webhook_payload(payload) == HANDLE_STATUS_DISCARDED + + mocked.assert_not_called() + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN="") +def test_handle_webhook_payload_discards_when_domain_not_configured(): + handler = InboundEmailHandler() + assert ( + handler.handle_webhook_payload(make_mox_payload(ADDRESS)) + == HANDLE_STATUS_DISCARDED + ) + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_discards_when_no_token_matches(): + handler = InboundEmailHandler() + assert ( + handler.handle_webhook_payload(make_mox_payload("someone@example.com")) + == HANDLE_STATUS_DISCARDED + ) + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_discards_unknown_token(): + handler = InboundEmailHandler() + assert ( + handler.handle_webhook_payload(make_mox_payload(ADDRESS)) + == HANDLE_STATUS_DISCARDED + ) + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_accepts_and_deduplicates(data_fixture): + node = data_fixture.create_inbound_email_trigger_node( + service_kwargs={"token": TOKEN} + ) + + from baserow.core.services.registries import service_type_registry + + service_type = service_type_registry.get("email_trigger") + with patch.object(service_type, "on_event", MagicMock()) as mocked: + handler = InboundEmailHandler() + payload = make_mox_payload(TEST_ADDRESS) + + assert handler.handle_webhook_payload(payload) == HANDLE_STATUS_ACCEPTED + assert mocked.call_count == 1 + + services, event_payload = mocked.call_args.args + assert services == [node.service.specific] + assert event_payload(node.service)["subject"] == "Hello from Ada" + + # A retried delivery of the same message must be idempotent. + assert handler.handle_webhook_payload(payload) == HANDLE_STATUS_DUPLICATE + assert mocked.call_count == 1 + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_skips_dedupe_without_message_id(data_fixture): + data_fixture.create_inbound_email_trigger_node(service_kwargs={"token": TOKEN}) + + from baserow.core.services.registries import service_type_registry + + service_type = service_type_registry.get("email_trigger") + with patch.object(service_type, "on_event", MagicMock()) as mocked: + handler = InboundEmailHandler() + payload = make_mox_payload(TEST_ADDRESS, MessageID="") + payload["Meta"]["MsgID"] = 0 + + assert handler.handle_webhook_payload(payload) == HANDLE_STATUS_ACCEPTED + assert handler.handle_webhook_payload(payload) == HANDLE_STATUS_ACCEPTED + assert mocked.call_count == 2 + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_removes_dedupe_entry_on_error(data_fixture): + data_fixture.create_inbound_email_trigger_node(service_kwargs={"token": TOKEN}) + + from baserow.core.services.registries import service_type_registry + + service_type = service_type_registry.get("email_trigger") + handler = InboundEmailHandler() + payload = make_mox_payload(TEST_ADDRESS) + + with patch.object( + service_type, "on_event", MagicMock(side_effect=Exception("boom")) + ): + with pytest.raises(Exception, match="boom"): + handler.handle_webhook_payload(payload) + + # The failed delivery must not poison the dedupe cache; the retried + # delivery is processed normally. + with patch.object(service_type, "on_event", MagicMock()) as mocked: + assert handler.handle_webhook_payload(payload) == HANDLE_STATUS_ACCEPTED + + mocked.assert_called_once() + + +def _inbound_email_log(messages): + (record,) = [str(m) for m in messages if "Inbound email" in str(m)] + return record + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_logs_automated_discard(inbound_email_logs): + payload = make_mox_payload(ADDRESS) + payload["Meta"]["Automated"] = True + + InboundEmailHandler().handle_webhook_payload(payload) + + record = _inbound_email_log(inbound_email_logs) + assert "Inbound email discarded: automated message" in record + assert "token=-" in record + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_logs_no_matching_recipient(inbound_email_logs): + InboundEmailHandler().handle_webhook_payload( + make_mox_payload("someone@example.com") + ) + + record = _inbound_email_log(inbound_email_logs) + assert "discarded: no recipient matches a trigger address" in record + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN="") +def test_handle_webhook_payload_logs_domain_not_configured(inbound_email_logs): + InboundEmailHandler().handle_webhook_payload(make_mox_payload(ADDRESS)) + + record = _inbound_email_log(inbound_email_logs) + assert "discarded: inbound email domain not configured" in record + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_logs_unknown_token(inbound_email_logs): + InboundEmailHandler().handle_webhook_payload(make_mox_payload(ADDRESS)) + + record = _inbound_email_log(inbound_email_logs) + assert "Inbound email discarded: no trigger for token" in record + # Only a prefix of the token is logged; it is the trigger's routing secret. + assert f"token={TOKEN[:8]}…" in record + assert TOKEN not in record + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_logs_accepted_and_duplicate( + data_fixture, inbound_email_logs +): + data_fixture.create_inbound_email_trigger_node(service_kwargs={"token": TOKEN}) + + from baserow.core.services.registries import service_type_registry + + service_type = service_type_registry.get("email_trigger") + with patch.object(service_type, "on_event", MagicMock()): + handler = InboundEmailHandler() + payload = make_mox_payload(TEST_ADDRESS) + handler.handle_webhook_payload(payload) + handler.handle_webhook_payload(payload) + + first, second = [str(m) for m in inbound_email_logs if "Inbound email" in str(m)] + assert "Inbound email accepted: dispatched to trigger" in first + assert "Inbound email duplicate: message already processed" in second + + # Both deliveries of the same message share a reference so retries can be + # correlated, and neither leaks the sender or recipient address. + message_ref = first.split("message=")[1].split(",")[0] + assert len(message_ref) == 12 + assert f"message={message_ref}" in second + assert "ada@example.com" not in first + assert ADDRESS not in first + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_extract_targets_test_prefix_targets_the_draft(): + email = InboundEmail(rcpt_to=TEST_ADDRESS) + + assert InboundEmailHandler().extract_targets(email) == [ + InboundEmailTarget(TOKEN, simulate=True) + ] + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +@pytest.mark.parametrize( + "rcpt_to", + [ + f"TEST-{TOKEN.upper()}@{INBOUND_DOMAIN}", + f"test-{TOKEN}+sales@{INBOUND_DOMAIN}", + f"Test-{TOKEN}+Sales@{INBOUND_DOMAIN.upper()}", + ], +) +def test_extract_targets_test_prefix_is_case_insensitive_and_keeps_tags(rcpt_to): + email = InboundEmail(rcpt_to=rcpt_to) + + assert InboundEmailHandler().extract_targets(email) == [ + InboundEmailTarget(TOKEN, simulate=True) + ] + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +@pytest.mark.parametrize( + "rcpt_to", + [ + f"test{TOKEN}@{INBOUND_DOMAIN}", + f"test--{TOKEN}@{INBOUND_DOMAIN}", + f"tset-{TOKEN}@{INBOUND_DOMAIN}", + f"test-@{INBOUND_DOMAIN}", + ], +) +def test_extract_targets_rejects_malformed_test_prefix(rcpt_to): + email = InboundEmail(rcpt_to=rcpt_to) + + assert InboundEmailHandler().extract_targets(email) == [] + + +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_extract_targets_keeps_test_and_published_addresses_apart(): + email = InboundEmail( + rcpt_to=TEST_ADDRESS, + to=[ + InboundEmailAddress(address=ADDRESS), + InboundEmailAddress(address=TEST_ADDRESS), + ], + ) + + assert InboundEmailHandler().extract_targets(email) == [ + InboundEmailTarget(TOKEN, simulate=True), + InboundEmailTarget(TOKEN, simulate=False), + ] + + +def test_dedupe_cache_key_differs_between_test_and_published_targets(): + handler = InboundEmailHandler() + email = InboundEmail(message_id="") + + published_key = handler.get_dedupe_cache_key(InboundEmailTarget(TOKEN), email) + test_key = handler.get_dedupe_cache_key( + InboundEmailTarget(TOKEN, simulate=True), email + ) + + assert published_key != test_key + assert TOKEN in published_key and f"test-{TOKEN}" in test_key + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_passes_simulate_to_the_service_type(): + from baserow.core.services.registries import service_type_registry + + service_type = service_type_registry.get("email_trigger") + handler = InboundEmailHandler() + + with patch.object(service_type, "process_inbound_email") as mocked: + assert ( + handler.handle_webhook_payload(make_mox_payload(TEST_ADDRESS)) + == HANDLE_STATUS_ACCEPTED + ) + assert ( + handler.handle_webhook_payload( + make_mox_payload(ADDRESS, MessageID="") + ) + == HANDLE_STATUS_ACCEPTED + ) + + (test_call, live_call) = mocked.call_args_list + assert test_call.args[0] == TOKEN and test_call.kwargs == {"simulate": True} + assert live_call.args[0] == TOKEN and live_call.kwargs == {"simulate": False} + + +@pytest.mark.django_db +@override_settings(INBOUND_EMAIL_DOMAIN=INBOUND_DOMAIN) +def test_handle_webhook_payload_logs_test_prefix(inbound_email_logs): + InboundEmailHandler().handle_webhook_payload(make_mox_payload(TEST_ADDRESS)) + + record = _inbound_email_log(inbound_email_logs) + assert f"token=test-{TOKEN[:8]}…" in record + + +@pytest.mark.parametrize( + "size,expected", + [ + (MOX_WEBHOOK_PART_LIMIT_BYTES - 1, False), + (MOX_WEBHOOK_PART_LIMIT_BYTES, True), + ], +) +def test_normalize_mox_payload_flags_bodies_cut_at_the_forwarding_limit(size, expected): + # Mox forwards at most 1 MiB of each body and cuts silently, so a body at + # the limit is reported as truncated for the workflow to act on. + payload = make_mox_payload(ADDRESS, Text="t" * size, HTML="

" + "h" * (size - 3)) + + email = normalize_mox_payload(payload) + + assert email.body_text_truncated is expected + assert email.body_html_truncated is expected + assert email.to_payload()["body_text_truncated"] is expected + assert email.to_payload()["body_html_truncated"] is expected + + +def test_normalize_mox_payload_counts_bytes_not_characters(): + # 4-byte characters reach the limit with fewer characters. + quarter = MOX_WEBHOOK_PART_LIMIT_BYTES // 4 + payload = make_mox_payload(ADDRESS, Text="\U0001f600" * quarter) + + assert normalize_mox_payload(payload).body_text_truncated is True diff --git a/backend/tests/baserow/contrib/integrations/core/test_inbound_email_receiver.py b/backend/tests/baserow/contrib/integrations/core/test_inbound_email_receiver.py new file mode 100644 index 0000000000..e9a197bdc7 --- /dev/null +++ b/backend/tests/baserow/contrib/integrations/core/test_inbound_email_receiver.py @@ -0,0 +1,286 @@ +import json +from unittest.mock import MagicMock, call, patch +from urllib.parse import parse_qs + +from django.test import override_settings + +import pytest +import requests +import responses +from celery.exceptions import Retry + +from baserow.contrib.integrations.core.inbound_email import InboundEmailHandler +from baserow.contrib.integrations.core.inbound_email_receiver import ( + INBOUND_EMAIL_RECEIVER_DELETE_DELAY_SECONDS, + InboundEmailReceiverClient, + InboundEmailReceiverError, + delete_receiver_message, +) +from baserow.contrib.integrations.tasks import ( + delete_inbound_email_receiver_message as delete_task, +) + +from .inbound_email_test_utils import make_mox_payload + +RECEIVER = "http://email-receiver:8880" +DOMAIN = "inbound.test" +SECRET = "a-long-webhook-secret" +DELETE_URL = f"{RECEIVER}/webapi/v0/MessageDelete" + + +def make_client(): + return InboundEmailReceiverClient(RECEIVER, f"webapi@{DOMAIN}", SECRET) + + +@responses.activate +def test_client_deletes_a_message_with_the_web_api_request_shape(): + responses.add(responses.POST, DELETE_URL, json={}, status=200) + + assert make_client().delete_message(42) is True + + request = responses.calls[0].request + # Mox expects a form field `request` holding JSON, and HTTP basic auth with + # an address of the account. + assert request.body == "request=%7B%22MsgID%22%3A+42%7D" + assert request.headers["Authorization"].startswith("Basic ") + # Mox only serves the web API for requests addressed to an IP, its own + # hostname or "localhost"; the compose deployments reach it by service + # name, so the client must not send that name as the Host header. + assert request.headers["Host"] == "localhost" + + +def test_client_reuses_one_session_and_closes_it(): + client = make_client() + session = MagicMock() + session.post.return_value = MagicMock(status_code=200) + client._session = session + + assert client.delete_message(1) is True + assert client.delete_message(2) is True + + assert session.post.call_count == 2 + client.close() + session.close.assert_called_once_with() + + +@responses.activate +@pytest.mark.parametrize( + "error", + [ + {"Code": "messageNotFound", "Message": "getting message: no such message"}, + {"Code": "user", "Message": "getting message: message was removed"}, + ], +) +def test_client_reports_missing_or_removed_messages_as_gone(error): + responses.add(responses.POST, DELETE_URL, json=error, status=400) + + assert make_client().delete_message(42) is False + + +@responses.activate +@pytest.mark.parametrize( + "status,body", + [ + (401, "unauthorized"), + (400, '{"Code": "protocol", "Message": "missing/empty request"}'), + (500, "boom"), + ], +) +def test_client_raises_on_other_failures(status, body): + responses.add(responses.POST, DELETE_URL, body=body, status=status) + + with pytest.raises(InboundEmailReceiverError): + make_client().delete_message(42) + + +@responses.activate +def test_client_raises_when_the_receiver_is_unreachable(): + responses.add(responses.POST, DELETE_URL, body=requests.ConnectionError("down")) + + with pytest.raises(InboundEmailReceiverError): + make_client().delete_message(42) + + +@override_settings( + INBOUND_EMAIL_RECEIVER_URL=RECEIVER, + INBOUND_EMAIL_DOMAIN=DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, +) +def test_client_from_settings_authenticates_as_the_webapi_address(): + client = InboundEmailReceiverClient.from_settings() + + assert client.base_url == RECEIVER + assert client.username == f"webapi@{DOMAIN}" + assert client.password == SECRET + + +@pytest.mark.parametrize( + "overrides", + [ + {"INBOUND_EMAIL_RECEIVER_URL": ""}, + {"INBOUND_EMAIL_DOMAIN": ""}, + {"INBOUND_EMAIL_WEBHOOK_SECRET": ""}, + ], +) +def test_client_from_settings_is_none_when_not_configured(overrides): + values = { + "INBOUND_EMAIL_RECEIVER_URL": RECEIVER, + "INBOUND_EMAIL_DOMAIN": DOMAIN, + "INBOUND_EMAIL_WEBHOOK_SECRET": SECRET, + **overrides, + } + with override_settings(**values): + assert InboundEmailReceiverClient.from_settings() is None + + +CONFIGURED = dict( + INBOUND_EMAIL_DOMAIN=DOMAIN, + INBOUND_EMAIL_WEBHOOK_SECRET=SECRET, + INBOUND_EMAIL_RECEIVER_URL=RECEIVER, +) + + +def deleted_ids(request_calls): + return [ + json.loads(parse_qs(c.request.body)["request"][0])["MsgID"] + for c in request_calls + ] + + +@pytest.mark.django_db +@override_settings(**CONFIGURED) +def test_webhook_queues_the_deletion_of_every_received_message( + django_capture_on_commit_callbacks, +): + handler = InboundEmailHandler() + + with patch.object(delete_task, "apply_async") as apply_async: + # Unknown token: discarded, but the message exists on the receiver. + payload = make_mox_payload(f"{'a' * 32}@{DOMAIN}") + payload["Meta"]["MsgID"] = 7 + with django_capture_on_commit_callbacks(execute=True): + handler.handle_webhook_payload(payload) + + # Automated mail: discarded before any dispatch, still deleted. + payload = make_mox_payload(f"{'a' * 32}@{DOMAIN}", MessageID="") + payload["Meta"]["MsgID"] = 9 + payload["Meta"]["Automated"] = True + with django_capture_on_commit_callbacks(execute=True): + handler.handle_webhook_payload(payload) + + assert apply_async.call_args_list == [ + call(args=[7], countdown=INBOUND_EMAIL_RECEIVER_DELETE_DELAY_SECONDS), + call(args=[9], countdown=INBOUND_EMAIL_RECEIVER_DELETE_DELAY_SECONDS), + ] + + +@pytest.mark.django_db +@override_settings(**CONFIGURED) +def test_webhook_queues_the_deletion_only_once_the_request_commits( + django_capture_on_commit_callbacks, +): + """ + The deletion must not race the webhook it belongs to: it is queued from an + on-commit hook, so a failing request (which mox retries) queues nothing. + """ + + payload = make_mox_payload(f"{'a' * 32}@{DOMAIN}") + payload["Meta"]["MsgID"] = 7 + + with patch.object(delete_task, "apply_async") as apply_async: + with django_capture_on_commit_callbacks() as callbacks: + InboundEmailHandler().handle_webhook_payload(payload) + apply_async.assert_not_called() + + assert len(callbacks) == 1 + + +@pytest.mark.django_db +@pytest.mark.parametrize( + "message_id,receiver_url", + [ + # Mox always sends an id; a missing one is nothing to delete. + (0, RECEIVER), + # No receiver to delete from, so nothing is queued at all. + (7, ""), + ], +) +def test_webhook_queues_no_deletion_when_there_is_nothing_to_delete( + django_capture_on_commit_callbacks, message_id, receiver_url +): + payload = make_mox_payload(f"{'a' * 32}@{DOMAIN}") + payload["Meta"]["MsgID"] = message_id + + with override_settings( + **{**CONFIGURED, "INBOUND_EMAIL_RECEIVER_URL": receiver_url} + ): + with patch.object(delete_task, "apply_async") as apply_async: + with django_capture_on_commit_callbacks(execute=True): + InboundEmailHandler().handle_webhook_payload(payload) + + apply_async.assert_not_called() + + +@responses.activate +@override_settings(**CONFIGURED) +def test_delete_task_deletes_the_message_from_the_receiver(): + responses.add(responses.POST, DELETE_URL, json={}, status=200) + + delete_task.apply(args=[7]) + + assert deleted_ids(responses.calls) == [7] + + +@responses.activate +@override_settings(**CONFIGURED) +def test_delete_task_treats_an_already_gone_message_as_done(): + # A retried webhook queues a second deletion of the same message. + responses.add( + responses.POST, + DELETE_URL, + json={"Code": "messageNotFound", "Message": "message not found"}, + status=400, + ) + + result = delete_task.apply(args=[7]) + + assert result.successful() + assert len(responses.calls) == 1 + + +@responses.activate +def test_delete_task_is_a_no_op_when_no_receiver_is_configured(): + with override_settings(**{**CONFIGURED, "INBOUND_EMAIL_RECEIVER_URL": ""}): + assert delete_receiver_message(7) is None + result = delete_task.apply(args=[7]) + + assert result.successful() + assert len(responses.calls) == 0 + + +@responses.activate +@override_settings(**CONFIGURED) +def test_delete_task_retries_with_backoff_while_the_receiver_cannot_be_used(): + responses.add(responses.POST, DELETE_URL, status=502, body="bad gateway") + + # Eagerly, the retry surfaces as the Retry exception a worker would act on. + with pytest.raises(Retry) as retry: + delete_task.apply(args=[7]) + + assert isinstance(retry.value.exc, InboundEmailReceiverError) + assert len(responses.calls) == 1 + # Exponential backoff from a minute, capped at an hour, for a few hours. + assert delete_task.max_retries == 8 + assert delete_task.retry_backoff == 60 + assert delete_task.retry_backoff_max == 60 * 60 + + +@responses.activate +@override_settings(**CONFIGURED) +def test_delete_receiver_message_closes_the_client(): + responses.add(responses.POST, DELETE_URL, json={}, status=200) + + with patch.object(InboundEmailReceiverClient, "close") as close: + assert delete_receiver_message(7) is True + + close.assert_called_once_with() diff --git a/changelog/entries/unreleased/feature/added_a_start_workflow_by_email_trigger_that_starts_an_autom.json b/changelog/entries/unreleased/feature/added_a_start_workflow_by_email_trigger_that_starts_an_autom.json new file mode 100644 index 0000000000..1c848ccbe0 --- /dev/null +++ b/changelog/entries/unreleased/feature/added_a_start_workflow_by_email_trigger_that_starts_an_autom.json @@ -0,0 +1,9 @@ +{ + "type": "feature", + "message": "Added a 'Start workflow by email' trigger that starts an automation workflow when an email is sent to its generated inbound email address.", + "issue_origin": "github", + "issue_number": null, + "domain": "automation", + "bullet_points": [], + "created_at": "2026-07-15" +} diff --git a/deploy/all-in-one/Dockerfile b/deploy/all-in-one/Dockerfile index 3fe27c1b0a..837fc6081b 100644 --- a/deploy/all-in-one/Dockerfile +++ b/deploy/all-in-one/Dockerfile @@ -65,6 +65,7 @@ RUN ln -s /opt/yarn-v1.22.22/bin/yarn /usr/local/bin/yarn # Copy su-exec from backend image (already built with pinned version + SHA256 verification) COPY --from=backend_image /usr/local/bin/su-exec /usr/local/bin/su-exec COPY --from=backend_image /usr/local/bin/wasmtime /usr/local/bin/wasmtime +COPY --from=backend_image /usr/local/bin/mox /usr/local/bin/mox COPY --from=backend_image /usr/local/lib/baserow/qjs.wasm /usr/local/lib/baserow/qjs.wasm ENV POSTGRES_LOCATION=/etc/postgresql/15/main \ @@ -106,6 +107,8 @@ HEALTHCHECK --interval=60s CMD ["/bin/bash", "/baserow/backend/docker/docker-ent ENTRYPOINT ["/baserow.sh"] CMD ["start"] EXPOSE 80 +# SMTP for the optional email-receiver role (only bound when enabled). +EXPOSE 25 # ============================================================================= @@ -154,3 +157,5 @@ HEALTHCHECK --interval=60s CMD ["/bin/bash", "/baserow/backend/docker/docker-ent ENTRYPOINT ["/baserow.sh"] CMD ["start"] EXPOSE 80 +# SMTP for the optional email-receiver role (only bound when enabled). +EXPOSE 25 diff --git a/deploy/all-in-one/supervisor/default_baserow_env.sh b/deploy/all-in-one/supervisor/default_baserow_env.sh index 0490146632..55c8706c4e 100755 --- a/deploy/all-in-one/supervisor/default_baserow_env.sh +++ b/deploy/all-in-one/supervisor/default_baserow_env.sh @@ -37,6 +37,10 @@ export BASEROW_CADDY_ADDRESSES="${BASEROW_CADDY_ADDRESSES:-":80"}" export BASEROW_CADDY_GLOBAL_CONF="${BASEROW_CADDY_GLOBAL_CONF:-}" export PRIVATE_BACKEND_URL='http://localhost:8000' +export BASEROW_INBOUND_EMAIL_RECEIVER_URL="${BASEROW_INBOUND_EMAIL_RECEIVER_URL:-http://localhost:${BASEROW_INBOUND_EMAIL_WEBAPI_PORT:-8880}}" +# The backend runs in this container, so the receiver's web API only needs to +# listen on loopback. +export BASEROW_INBOUND_EMAIL_WEBAPI_BIND_IP="${BASEROW_INBOUND_EMAIL_WEBAPI_BIND_IP:-127.0.0.1}" export PRIVATE_WEB_FRONTEND_URL='http://localhost:3000' export BASEROW_BACKEND_BIND_ADDRESS=127.0.0.1 export BASEROW_WEBFRONTEND_BIND_ADDRESS=127.0.0.1 @@ -73,6 +77,7 @@ export BASEROW_BACKEND_STARTUP_COMMAND="${BASEROW_BACKEND_STARTUP_COMMAND:-$DEFA export BASEROW_CELERY_WORKER_STARTUP_COMMAND="${BASEROW_CELERY_WORKER_STARTUP_COMMAND:-$DEFAULT_CELERY_WORKER_STARTUP_COMMAND}" export BASEROW_CELERY_EXPORT_WORKER_STARTUP_COMMAND="${BASEROW_CELERY_EXPORT_WORKER_STARTUP_COMMAND:-$DEFAULT_CELERY_EXPORT_WORKER_STARTUP_COMMAND}" export BASEROW_CELERY_BEAT_STARTUP_COMMAND="${BASEROW_CELERY_BEAT_STARTUP_COMMAND:-$DEFAULT_CELERY_BEAT_STARTUP_COMMAND}" +export BASEROW_EMAIL_RECEIVER_STARTUP_COMMAND="${BASEROW_EMAIL_RECEIVER_STARTUP_COMMAND:-email-receiver}" export XDG_CONFIG_HOME=/home/$DOCKER_USER/ export HOME=/home/$DOCKER_USER/ diff --git a/deploy/all-in-one/supervisor/includes/disabled/email-receiver.conf b/deploy/all-in-one/supervisor/includes/disabled/email-receiver.conf new file mode 100644 index 0000000000..fcd7f4f8a5 --- /dev/null +++ b/deploy/all-in-one/supervisor/includes/disabled/email-receiver.conf @@ -0,0 +1,17 @@ +# Receives inbound email for the "Start workflow by email" automation trigger +# and forwards it to the backend. Enabled by start.sh when +# BASEROW_INBOUND_EMAIL_DOMAIN and BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET are +# set. Runs as root because mox binds its sockets (including privileged port +# 25) as root and then drops privileges itself. +[program:emailreceiver] +user=root +directory=/baserow/backend +command=/baserow/supervisor/wrapper.sh CYAN EMAIL_RECEIVER ./docker/docker-entrypoint.sh %(ENV_BASEROW_EMAIL_RECEIVER_STARTUP_COMMAND)s +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/stdout +stderr_logfile_maxbytes=0 +autostart=true +priority=2 +startretries=3 +startsecs=30 diff --git a/deploy/all-in-one/supervisor/start.sh b/deploy/all-in-one/supervisor/start.sh index 0b9ef8be63..bbcdeae2b3 100755 --- a/deploy/all-in-one/supervisor/start.sh +++ b/deploy/all-in-one/supervisor/start.sh @@ -67,6 +67,21 @@ elif [ -f "$SUPERVISOR_ENABLED_CONF_DIR/embedded-redis.conf" ]; then mv "$SUPERVISOR_ENABLED_CONF_DIR/embedded-redis.conf" "$SUPERVISOR_DISABLED_CONF_DIR/embedded-redis.conf" 2>/dev/null || true fi +# ======================== +# = SETUP EMAIL RECEIVER IF TURNED ON +# ======================== +if [[ -n "${BASEROW_INBOUND_EMAIL_DOMAIN:-}" && -n "${BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET:-}" ]]; then + startup_echo "Enabling the email receiver for inbound domain $BASEROW_INBOUND_EMAIL_DOMAIN." + # Enable the email receiver by moving it into the directory from which + # supervisor includes all .conf files it finds. + if [ ! -f "$SUPERVISOR_ENABLED_CONF_DIR/email-receiver.conf" ]; then + mv "$SUPERVISOR_DISABLED_CONF_DIR/email-receiver.conf" "$SUPERVISOR_ENABLED_CONF_DIR/email-receiver.conf" + fi +elif [ -f "$SUPERVISOR_ENABLED_CONF_DIR/email-receiver.conf" ]; then + # Disable the email receiver if somehow the conf is in the enabled folder + mv "$SUPERVISOR_ENABLED_CONF_DIR/email-receiver.conf" "$SUPERVISOR_DISABLED_CONF_DIR/email-receiver.conf" 2>/dev/null || true +fi + # ======================== # = LOG ABOUT URL # ======================== diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 3f1b74da42..8ee634eb69 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -231,6 +231,39 @@ services: stdin_open: true tty: true + # Inbound email receiver (mox) for the "Start workflow by email" automation + # trigger. Opt-in via the base file's "inbound-email" profile: `just mox up` + # starts it next to a natively running backend, and + # `COMPOSE_PROFILES=optional,inbound-email` starts it as part of + # `just dc-dev up`. Same `email-receiver` role as production, but built from + # the dev image so no Go toolchain or `brew install mox` is needed. + email-receiver: + image: baserow_backend:dev + # Inherited from the base file, repeated here so it is not mistaken for an + # omission: the receiver only exists under this profile. + profiles: ["inbound-email"] + build: + dockerfile: ./backend/Dockerfile + context: . + target: dev + args: + UID: $UID + GID: $GID + # The SMTP port mapping comes from the base file and is env-driven: + # .env.docker-dev publishes it on 127.0.0.1:2025 (off port 25, like mailhog). + # The web API is published on loopback too so a natively running backend + # (`just dev`) can delete handed-over messages through it. + ports: + - "${BASEROW_HOST_PUBLISH_IP:-127.0.0.1}:${BASEROW_INBOUND_EMAIL_WEBAPI_HOST_PORT:-8880}:${BASEROW_INBOUND_EMAIL_WEBAPI_PORT:-8880}" + # Lets the container reach a backend running natively on the host. + extra_hosts: + - "host.docker.internal:host-gateway" + # The dev image expects the source and plugin helpers bind-mounted, like + # the backend service above. + volumes: + - ./backend:/baserow/backend + - ./deploy/plugins/:/baserow/plugins/ + mailhog: image: mailhog/mailhog logging: diff --git a/docker-compose.no-caddy.yml b/docker-compose.no-caddy.yml index 1b5f41091b..d6986238b4 100644 --- a/docker-compose.no-caddy.yml +++ b/docker-compose.no-caddy.yml @@ -15,6 +15,11 @@ # to the URL the user's browser can access the files on. # 4. Ensure requests sent to the backend in /ws path are upgraded to websocket # connections. +# 5. (Optional) To use the "Start workflow by email" automation trigger, enable +# the "inbound-email" profile (COMPOSE_PROFILES=inbound-email) and set +# BASEROW_INBOUND_EMAIL_DOMAIN, BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET and +# BASEROW_INBOUND_EMAIL_HOST_PUBLISH_IP=0.0.0.0 so the email-receiver's SMTP +# port is reachable by sending mail servers. See the email-receiver service. # # See the following guides for more details and example configurations: # 1. https://baserow.io/docs/installation%2Finstall-behind-nginx @@ -137,7 +142,7 @@ x-backend-variables: POSTHOG_PROJECT_API_KEY: POSTHOG_HOST: - PRIVATE_BACKEND_URL: http://backend:8000 + PRIVATE_BACKEND_URL: ${PRIVATE_BACKEND_URL:-http://backend:8000} BASEROW_PUBLIC_URL: MEDIA_URL: MEDIA_ROOT: @@ -178,6 +183,11 @@ x-backend-variables: BASEROW_INTEGRATIONS_HTTP_MAX_RESPONSE_BYTES: BASEROW_INTEGRATIONS_SLACK_API_URL: BASEROW_INTEGRATIONS_PERIODIC_MINUTE_MIN: + BASEROW_INBOUND_EMAIL_DOMAIN: + BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET: + BASEROW_INBOUND_EMAIL_RECEIVER_URL: ${BASEROW_INBOUND_EMAIL_RECEIVER_URL:-http://email-receiver:8880} + BASEROW_INBOUND_EMAIL_RECEIVER_PASSWORD: + BASEROW_INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB: BASEROW_DATA_SYNC_ALLOW_PRIVATE_ADDRESS: BASEROW_PREVENT_POSTGRESQL_DATA_SYNC_CONNECTION_TO_DATABASE: BASEROW_POSTGRESQL_DATA_SYNC_BLACKLIST: @@ -393,6 +403,58 @@ services: networks: local: + # Receives inbound email for the "Start workflow by email" automation trigger + # and forwards it to the backend. Opt-in through the "inbound-email" Compose + # profile (COMPOSE_PROFILES=inbound-email): Compose cannot publish a port + # conditionally, so without the profile the SMTP port below would be bound on + # the host of every installation, including the ones that never use the + # trigger. Also set BASEROW_INBOUND_EMAIL_DOMAIN and + # BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET; the service idles until both are + # present. Runs as root because mox binds its sockets as root and then drops + # privileges itself. + # + # Like the other services in this file, the SMTP port is only published on the + # loopback address by default. Sending mail servers connect to port 25 directly + # (a HTTP reverse proxy cannot forward SMTP), so to receive inbound email set + # BASEROW_INBOUND_EMAIL_HOST_PUBLISH_IP=0.0.0.0 to publish only this port on all + # interfaces without also exposing the backend and web-frontend ports. + email-receiver: + image: baserow/backend:2.3.4 + profiles: ["inbound-email"] + restart: unless-stopped + user: root + command: email-receiver + ports: + - "${BASEROW_INBOUND_EMAIL_HOST_PUBLISH_IP:-${HOST_PUBLISH_IP:-127.0.0.1}}:${BASEROW_INBOUND_EMAIL_HOST_SMTP_PORT:-25}:25" + healthcheck: + test: + [ + "CMD-SHELL", + "/baserow/backend/docker/docker-entrypoint.sh email-receiver-healthcheck", + ] + environment: + BASEROW_INBOUND_EMAIL_DOMAIN: + BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET: + BASEROW_INBOUND_EMAIL_WEBHOOK_URL: + BASEROW_INBOUND_EMAIL_SMTP_HOSTNAME: + BASEROW_INBOUND_EMAIL_SMTP_PORT: + BASEROW_INBOUND_EMAIL_TLS_MODE: + BASEROW_INBOUND_EMAIL_TLS_CERT_FILE: + BASEROW_INBOUND_EMAIL_TLS_KEY_FILE: + BASEROW_INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB: + BASEROW_INBOUND_EMAIL_WEBAPI_PORT: + BASEROW_INBOUND_EMAIL_WEBAPI_BIND_IP: + BASEROW_INBOUND_EMAIL_RECEIVER_PASSWORD: + PRIVATE_BACKEND_URL: ${PRIVATE_BACKEND_URL:-http://backend:8000} + BASEROW_DEPLOYMENT_ENV: + OTEL_RESOURCE_ATTRIBUTES: + depends_on: + - backend + volumes: + - mox_data:/baserow/data/mox + networks: + local: + db: image: pgvector/pgvector:pg15 restart: unless-stopped @@ -436,6 +498,7 @@ services: volumes: pgdata: media: + mox_data: caddy_data: caddy_config: diff --git a/docker-compose.yml b/docker-compose.yml index aa28525d9b..aa41e1c455 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -96,6 +96,11 @@ x-backend-variables: BASEROW_FORMULA_RANGE_MAX_ITEMS: BASEROW_INTEGRATION_LOCAL_BASEROW_BATCH_OPERATION_SIZE_LIMIT: BASEROW_INTEGRATION_ALLOW_SMTP_SERVICE_TO_USE_INSTANCE_SETTINGS: + BASEROW_INBOUND_EMAIL_DOMAIN: + BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET: + BASEROW_INBOUND_EMAIL_RECEIVER_URL: ${BASEROW_INBOUND_EMAIL_RECEIVER_URL:-http://email-receiver:8880} + BASEROW_INBOUND_EMAIL_RECEIVER_PASSWORD: + BASEROW_INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB: BATCH_ROWS_SIZE_LIMIT: INITIAL_TABLE_DATA_LIMIT: BASEROW_FILE_UPLOAD_SIZE_LIMIT_MB: @@ -150,7 +155,7 @@ x-backend-variables: POSTHOG_PROJECT_API_KEY: POSTHOG_HOST: - PRIVATE_BACKEND_URL: http://backend:8000 + PRIVATE_BACKEND_URL: ${PRIVATE_BACKEND_URL:-http://backend:8000} PUBLIC_BACKEND_URL: PUBLIC_WEB_FRONTEND_URL: BASEROW_BUILDER_PREVIEW_URL: @@ -479,6 +484,52 @@ services: networks: local: + # Receives inbound email for the "Start workflow by email" automation trigger + # and forwards it to the backend. Opt-in through the "inbound-email" Compose + # profile (COMPOSE_PROFILES=inbound-email): Compose cannot publish a port + # conditionally, so without the profile the SMTP port below would be bound on + # the host of every installation, including the ones that never use the + # trigger. Also set BASEROW_INBOUND_EMAIL_DOMAIN and + # BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET; the service idles until both are + # present. Runs as root because mox binds its sockets as root and then drops + # privileges itself. + email-receiver: + image: baserow/backend:${BASEROW_VERSION:-2.3.4} + profiles: ["inbound-email"] + restart: unless-stopped + user: root + command: email-receiver + ports: + - "${BASEROW_INBOUND_EMAIL_HOST_PUBLISH_IP:-${HOST_PUBLISH_IP:-0.0.0.0}}:${BASEROW_INBOUND_EMAIL_HOST_SMTP_PORT:-25}:25" + healthcheck: + test: + [ + "CMD-SHELL", + "/baserow/backend/docker/docker-entrypoint.sh email-receiver-healthcheck", + ] + environment: + BASEROW_INBOUND_EMAIL_DOMAIN: + BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET: + BASEROW_INBOUND_EMAIL_WEBHOOK_URL: + BASEROW_INBOUND_EMAIL_SMTP_HOSTNAME: + BASEROW_INBOUND_EMAIL_SMTP_PORT: + BASEROW_INBOUND_EMAIL_TLS_MODE: + BASEROW_INBOUND_EMAIL_TLS_CERT_FILE: + BASEROW_INBOUND_EMAIL_TLS_KEY_FILE: + BASEROW_INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB: + BASEROW_INBOUND_EMAIL_WEBAPI_PORT: + BASEROW_INBOUND_EMAIL_WEBAPI_BIND_IP: + BASEROW_INBOUND_EMAIL_RECEIVER_PASSWORD: + PRIVATE_BACKEND_URL: ${PRIVATE_BACKEND_URL:-http://backend:8000} + BASEROW_DEPLOYMENT_ENV: + OTEL_RESOURCE_ATTRIBUTES: + depends_on: + - backend + volumes: + - mox_data:/baserow/data/mox + networks: + local: + db: image: pgvector/pgvector:pg15 # If you were using a previous version, perform the update by uncommenting the @@ -526,6 +577,7 @@ services: volumes: pgdata: media: + mox_data: caddy_data: caddy_config: diff --git a/docs/installation/configuration.md b/docs/installation/configuration.md index be97cc2381..30a646b6bc 100644 --- a/docs/installation/configuration.md +++ b/docs/installation/configuration.md @@ -58,6 +58,21 @@ The installation methods referred to in the variable descriptions are: | BASEROW\_FORMULA\_RANGE\_MAX\_ITEMS | The maximum number of items the `range` runtime formula function can generate. Prevents a small formula from producing an unbounded array. | 10000 | | BASEROW\_INTEGRATION\_LOCAL\_BASEROW\_BATCH\_OPERATION\_SIZE\_LIMIT | Controls how many rows can be created, updated, or deleted at once using Local Baserow batch workflow actions. | 1000 | | BASEROW\_REQUEST\_BODY\_SIZE\_LIMIT\_MB | The max size in MB of a JSON or form encoded request body. Bodies over the limit are rejected before they are parsed, with an `ERROR_REQUEST_BODY_TOO_LARGE` response. Unset by default, meaning no limit, because the table import and create endpoints send the whole dataset as one JSON body and the largest legitimate size depends on your data. Note that file uploads to a File Field are covered by `BASEROW_FILE_UPLOAD_SIZE_LIMIT_MB` instead. | unset (no limit) | +| BASEROW\_INBOUND\_EMAIL\_DOMAIN | The domain used to generate inbound email addresses for the "Start workflow by email" automation trigger, e.g. setting it to `inbound.example.com` generates addresses like `{token}@inbound.example.com`. When empty, the email trigger feature is not configured on this instance. | | +| BASEROW\_INBOUND\_EMAIL\_WEBHOOK\_SECRET | The shared secret that the inbound mail server must send in the `Authorization` header when delivering inbound email webhooks to the `/api/inbound-email/` endpoint. When empty, the endpoint rejects all requests. Must be at least 8 characters (a long random string is recommended): unless `BASEROW_INBOUND_EMAIL_RECEIVER_PASSWORD` is set it also serves as the receiver's web API password, and mox refuses shorter ones. | | +| BASEROW\_INBOUND\_EMAIL\_WEBHOOK\_URL | Only used by the `email-receiver` role. The URL the bundled mox mail server POSTs inbound email webhooks to. | `PRIVATE_BACKEND_URL` (falling back to `PUBLIC_BACKEND_URL`) + `/api/inbound-email/` | +| BASEROW\_INBOUND\_EMAIL\_SMTP\_HOSTNAME | Only used by the `email-receiver` role. The hostname the bundled mox mail server announces in its SMTP banner and uses for its TLS certificate. | $BASEROW\_INBOUND\_EMAIL\_DOMAIN | +| BASEROW\_INBOUND\_EMAIL\_SMTP\_PORT | Only used by the `email-receiver` role. The SMTP port the bundled mox mail server listens on inside the container. | 25 | +| BASEROW\_INBOUND\_EMAIL\_HOST\_SMTP\_PORT | Only used by the docker-compose files. The host port that is published to the email receiver's SMTP port. The MX record of the inbound email domain must resolve to this host and port 25 must be reachable from the internet. | 25 | +| BASEROW\_INBOUND\_EMAIL\_HOST\_PUBLISH\_IP | Only used by the docker-compose files. The host IP address the email receiver's SMTP port is published on. Defaults to `HOST_PUBLISH_IP`, which is `0.0.0.0` in `docker-compose.yml` and `127.0.0.1` in `docker-compose.no-caddy.yml`. Sending mail servers connect to port 25 directly, so with the no-caddy file set this to `0.0.0.0` to accept inbound email without exposing the backend and web-frontend ports. | $HOST\_PUBLISH\_IP | +| BASEROW\_INBOUND\_EMAIL\_TLS\_MODE | Only used by the `email-receiver` role. `self-signed` generates and persists a self-signed certificate for STARTTLS (sending mail servers use opportunistic TLS and do not validate it). `manual` uses the certificate and key files configured below. | self-signed | +| BASEROW\_INBOUND\_EMAIL\_TLS\_CERT\_FILE | Only used by the `email-receiver` role when the TLS mode is `manual`. Path inside the container to a PEM certificate (including intermediates) for the SMTP listener. | | +| BASEROW\_INBOUND\_EMAIL\_TLS\_KEY\_FILE | Only used by the `email-receiver` role when the TLS mode is `manual`. Path inside the container to the PEM private key for the certificate above. Both files must be readable by the unprivileged user mox drops to after binding its ports (uid 9999). | | +| BASEROW\_INBOUND\_EMAIL\_MAX\_MESSAGE\_SIZE\_MB | Used by the `email-receiver` role and the backend. The largest email, in MB, the bundled mox mail server accepts, attachments included. Larger emails are refused during SMTP delivery and bounce back to the sender. The backend only uses the value to show the limit in the email trigger's side panel, so set it once for the whole deployment. Independently of this limit, mox truncates the text and HTML bodies it forwards at 1MB each and never forwards attachment contents. | 25 | +| BASEROW\_INBOUND\_EMAIL\_RECEIVER\_URL | The URL where the backend reaches the bundled mox mail server's web API. Mox keeps every accepted message on disk and has no retention setting, so the backend deletes each message through this API about a minute after receiving its webhook, retrying with backoff while the mail server cannot be reached. Leave empty to disable that. | `http://email-receiver:8880` in the docker-compose files, `http://localhost:8880` in the all-in-one image, empty otherwise | +| BASEROW\_INBOUND\_EMAIL\_WEBAPI\_PORT | Only used by the `email-receiver` role. The port inside the container on which the mail server's web API listens. It is never published; the backend reaches it over the internal network. | 8880 | +| BASEROW\_INBOUND\_EMAIL\_WEBAPI\_BIND\_IP | Only used by the `email-receiver` role. The address inside the container the mail server's web API listens on. The default lets the backend container reach it over the Compose network; the all-in-one image sets `127.0.0.1` because the backend runs in the same container. | 0.0.0.0 | +| BASEROW\_INBOUND\_EMAIL\_RECEIVER\_PASSWORD | The password the backend authenticates with when deleting received messages through the mail server's web API. Empty means `BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET` is used, so one secret configures the whole feature. Set it separately to keep the secret that travels in every webhook request out of the receiver's credentials. At least 8 characters. | | | BASEROW\_FILE_UPLOAD\_SIZE\_LIMIT\_MB | The max file size in MB allowed to be uploaded by users into a Baserow File Field. | 1048576 (1 TB or 1024*1024) | | BASEROW\_FILE\_UPLOAD\_ACTIVE\_CONTENT\_POLICY | Controls how uploads with active-content extensions (`.html`, `.htm`, `.xhtml`, `.xml`, `.svg`, `.svgz`) or MIME types (`text/html`, `text/xml`, `application/xml`, `application/xhtml+xml`, `image/svg+xml`) are handled. Set to `download` to allow them but store them as `application/octet-stream` without image previews. Set to `block` to reject them. | download | | BASEROW\_OPENAI\_UPLOADED\_FILE\_SIZE\_LIMIT\_MB | The max file size in MB allowed to be loaded in RAM and uploaded to OpenAI servers. See also [OpenAI docs](https://platform.openai.com/docs/api-reference/files/create). | 512 | diff --git a/docs/installation/install-with-docker-compose.md b/docs/installation/install-with-docker-compose.md index f8dd80a49d..e5d8f080d1 100644 --- a/docs/installation/install-with-docker-compose.md +++ b/docs/installation/install-with-docker-compose.md @@ -198,6 +198,46 @@ can set the `WEB_FRONTEND_PORT` variable to change the default of port 80 and $ WEB_FRONTEND_SSL_PORT=444 WEB_FRONTEND_PORT=3000 docker-compose up ``` +### Enabling inbound email triggers + +The "Start workflow by email" automation trigger uses the `email-receiver` +service (the bundled mox mail server), which receives email for a dedicated +inbound domain (e.g. `inbound.yourdomain.com`) and forwards it to the backend. +The service sits behind the `inbound-email` Compose profile, so it is not +started, and its SMTP port is not bound on the host, unless you enable that +profile. Enable it and set both of the following variables (or put all three +in your `.env` file): + +```bash +$ COMPOSE_PROFILES=inbound-email \ + BASEROW_INBOUND_EMAIL_DOMAIN=inbound.yourdomain.com \ + BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET=some-long-random-secret \ + docker-compose up -d +``` + +The secret must be at least 8 characters long; a long random string is +recommended. + +You must also create an MX record for the inbound domain pointing at this +host, and port 25 must be reachable from the internet (if another service on +the host already uses port 25, override the published host port with +`BASEROW_INBOUND_EMAIL_HOST_SMTP_PORT`). Sending mail servers connect to the +receiver directly, so a HTTP reverse proxy cannot sit in front of it. If you use +`docker-compose.no-caddy.yml`, which publishes all ports on `127.0.0.1` by +default, additionally set `BASEROW_INBOUND_EMAIL_HOST_PUBLISH_IP=0.0.0.0` to +publish only the SMTP port on all interfaces. By default the +receiver offers STARTTLS with a self-signed certificate; see +`BASEROW_INBOUND_EMAIL_TLS_MODE` in [configuration](configuration.md) to +provide a real certificate. The receiver's webhook retry queue and TLS +certificate persist in the `mox_data` volume. Received messages are not +retained: the backend deletes each message from the mail server about a minute +after it has been handed over, whether or not it matched a trigger. + +Emails larger than 25 MB (`BASEROW_INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB`) are +refused during delivery and bounce back to the sender. Attachments are never +stored: the workflow only receives their name, type and size, and text or HTML +bodies over 1 MB are truncated. + ### Using a Domain with automatic https If you have a domain name and have correctly configured DNS then you can run the diff --git a/docs/installation/install-with-docker.md b/docs/installation/install-with-docker.md index 25a0f48645..5199588a2a 100644 --- a/docs/installation/install-with-docker.md +++ b/docs/installation/install-with-docker.md @@ -289,6 +289,42 @@ docker run \ baserow/baserow:2.3.4 ``` +### With inbound email triggers enabled + +The "Start workflow by email" automation trigger needs the bundled mox mail +server to receive email for a dedicated inbound domain (e.g. +`inbound.yourdomain.com`) and forward it to Baserow. Setting +`BASEROW_INBOUND_EMAIL_DOMAIN` and `BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET` +enables the embedded email receiver, which listens for SMTP on port 25. + +You must also create an MX record for the inbound domain pointing at this +host, and port 25 must be reachable from the internet. By default the +receiver offers STARTTLS with a self-signed certificate; see +`BASEROW_INBOUND_EMAIL_TLS_MODE` in [configuration](configuration.md) to +provide a real certificate. + +Emails larger than 25 MB (`BASEROW_INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB`) are +refused during delivery and bounce back to the sender. Attachments are never +stored: the workflow only receives their name, type and size, and text or HTML +bodies over 1 MB are truncated. Received messages are not retained: the backend +deletes each message from the mail server about a minute after it has been +handed over, whether or not it matched a trigger. + +```bash +docker run \ + -d \ + --name baserow \ + -e BASEROW_PUBLIC_URL=https://www.yourdomain.com \ + -e BASEROW_INBOUND_EMAIL_DOMAIN=inbound.yourdomain.com \ + -e BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET=$(tr -dc 'a-z0-9' < /dev/urandom | head -c 32) \ + -v baserow_data:/baserow/data \ + -p 80:80 \ + -p 443:443 \ + -p 25:25 \ + --restart unless-stopped \ + baserow/baserow:2.3.4 +``` + ### With a Postgresql server running on the same host as the Baserow docker container This is assuming you are using the postgresql server bundled by ubuntu. If not then you diff --git a/enterprise/backend/src/baserow_enterprise/locale/en/LC_MESSAGES/django.po b/enterprise/backend/src/baserow_enterprise/locale/en/LC_MESSAGES/django.po index 34c11a4e01..9eca540527 100644 --- a/enterprise/backend/src/baserow_enterprise/locale/en/LC_MESSAGES/django.po +++ b/enterprise/backend/src/baserow_enterprise/locale/en/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-06-15 14:48+0000\n" +"POT-Creation-Date: 2026-09-11 12:44+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -18,7 +18,16 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" -#: src/baserow_enterprise/assistant/tools/automation/agents.py:112 +#: src/baserow_enterprise/application_users/notification_types.py:49 +msgid "Application user limit reached" +msgstr "" + +#: src/baserow_enterprise/application_users/notification_types.py:53 +#, python-format +msgid "%(usage)s of %(limit)s application users used" +msgstr "" + +#: src/baserow_enterprise/assistant/tools/automation/agents.py:126 #: src/baserow_enterprise/assistant/tools/automation/tools.py:128 #: src/baserow_enterprise/assistant/tools/automation/tools.py:292 #, python-format @@ -57,27 +66,27 @@ msgstr "" msgid "Deleting node %(node_id)s..." msgstr "" -#: src/baserow_enterprise/assistant/tools/builder/agents.py:401 +#: src/baserow_enterprise/assistant/tools/builder/agents.py:405 #, python-format msgid "Generating formulas for element '%(ref)s'..." msgstr "" -#: src/baserow_enterprise/assistant/tools/builder/agents.py:447 +#: src/baserow_enterprise/assistant/tools/builder/agents.py:456 #, python-format msgid "Generating formulas for data source '%(name)s'..." msgstr "" -#: src/baserow_enterprise/assistant/tools/builder/agents.py:495 +#: src/baserow_enterprise/assistant/tools/builder/agents.py:512 #, python-format msgid "Generating formulas for data source %(id)d..." msgstr "" -#: src/baserow_enterprise/assistant/tools/builder/agents.py:575 +#: src/baserow_enterprise/assistant/tools/builder/agents.py:603 #, python-format msgid "Generating formulas for element %(id)d..." msgstr "" -#: src/baserow_enterprise/assistant/tools/builder/agents.py:644 +#: src/baserow_enterprise/assistant/tools/builder/agents.py:679 #, python-format msgid "Generating formulas for action on '%(ref)s'..." msgstr "" @@ -195,12 +204,12 @@ msgstr "" msgid "Updating %(app_name)s..." msgstr "" -#: src/baserow_enterprise/assistant/tools/database/agents.py:126 +#: src/baserow_enterprise/assistant/tools/database/agents.py:140 #, python-format msgid "Fixing formula for %(name)s..." msgstr "" -#: src/baserow_enterprise/assistant/tools/database/agents.py:227 +#: src/baserow_enterprise/assistant/tools/database/agents.py:240 msgid "Generating example rows for these new tables..." msgstr "" @@ -209,66 +218,66 @@ msgstr "" msgid "Creating field %(field_name)s..." msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:195 +#: src/baserow_enterprise/assistant/tools/database/tools.py:196 #, python-format msgid "Listing tables in %(database_names)s..." msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:247 +#: src/baserow_enterprise/assistant/tools/database/tools.py:248 #, python-format msgid "Inspecting %(table_names)s schema..." msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:301 +#: src/baserow_enterprise/assistant/tools/database/tools.py:302 #, python-format msgid "Listing rows in %(table_name)s " msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:351 +#: src/baserow_enterprise/assistant/tools/database/tools.py:352 #, python-format msgid "Listing views in %(table_name)s..." msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:385 +#: src/baserow_enterprise/assistant/tools/database/tools.py:386 #, python-format msgid "Creating table %(table_name)s..." msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:641 +#: src/baserow_enterprise/assistant/tools/database/tools.py:642 #, python-format msgid "Updating field %(field_id)s..." msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:697 +#: src/baserow_enterprise/assistant/tools/database/tools.py:698 #, python-format msgid "Deleting field %(field_id)s..." msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:755 +#: src/baserow_enterprise/assistant/tools/database/tools.py:756 #, python-format msgid "Creating %(view_type)s view %(view_name)s" msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:834 +#: src/baserow_enterprise/assistant/tools/database/tools.py:835 #, python-format msgid "Creating filters in %(view_name)s..." msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:910 +#: src/baserow_enterprise/assistant/tools/database/tools.py:915 msgid "Generating formula..." msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:1038 +#: src/baserow_enterprise/assistant/tools/database/tools.py:1045 #, python-format msgid "Creating rows in %(table_name)s " msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:1075 +#: src/baserow_enterprise/assistant/tools/database/tools.py:1082 #, python-format msgid "Updating rows in %(table_name)s " msgstr "" -#: src/baserow_enterprise/assistant/tools/database/tools.py:1111 +#: src/baserow_enterprise/assistant/tools/database/tools.py:1118 #, python-format msgid "Deleting rows in %(table_name)s " msgstr "" @@ -278,7 +287,7 @@ msgstr "" msgid "Navigating to %(location)s..." msgstr "" -#: src/baserow_enterprise/assistant/tools/search_user_docs/tools.py:149 +#: src/baserow_enterprise/assistant/tools/search_user_docs/tools.py:150 msgid "Exploring the knowledge base..." msgstr "" @@ -354,11 +363,11 @@ msgstr "" msgid "Code" msgstr "" -#: src/baserow_enterprise/builder/elements/element_types.py:31 +#: src/baserow_enterprise/builder/elements/element_types.py:32 msgid "Auth form" msgstr "" -#: src/baserow_enterprise/builder/elements/element_types.py:139 +#: src/baserow_enterprise/builder/elements/element_types.py:156 msgid "File input" msgstr "" @@ -488,11 +497,11 @@ msgid "" "resolved." msgstr "" -#: src/baserow_enterprise/field_permissions/actions.py:25 +#: src/baserow_enterprise/field_permissions/actions.py:26 msgid "Update field permissions" msgstr "" -#: src/baserow_enterprise/field_permissions/actions.py:27 +#: src/baserow_enterprise/field_permissions/actions.py:28 #, python-format msgid "" "Field \"%(field_name)s\" (%(field_id)s): permissions updated to role " diff --git a/justfile b/justfile index 9606f88897..6bafd61432 100644 --- a/justfile +++ b/justfile @@ -203,7 +203,7 @@ dev *ARGS: done echo "" echo "==> Docker Services" - just dc-dev ps redis db mailhog otel-collector 2>/dev/null || echo " Not running" + just dc-dev ps redis db mailhog otel-collector email-receiver 2>/dev/null || echo " Not running" ;; tmux) just _dev-tmux @@ -339,6 +339,19 @@ _dev-start: fi MAILHOG_STATUS_PORT="${MAILHOG_STATUS_PORT:-8025}" + # Inbound email receiver (mox): only when the trigger is configured in + # .env.local; `just mox up -d` runs it in Docker next to the native backend. + INBOUND_EMAIL_STATUS="not configured (set BASEROW_INBOUND_EMAIL_DOMAIN and BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET in .env.local)" + if [[ -n "${BASEROW_INBOUND_EMAIL_DOMAIN:-}" && -n "${BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET:-}" ]]; then + echo "" + echo "==> Starting inbound email receiver (mox) in Docker..." + if just mox up -d; then + INBOUND_EMAIL_STATUS="SMTP on localhost:${BASEROW_INBOUND_EMAIL_HOST_SMTP_PORT:-2025} for ${BASEROW_INBOUND_EMAIL_DOMAIN} (just mox address)" + else + INBOUND_EMAIL_STATUS="failed to start (see output above; run 'just mox up' to retry)" + fi + fi + echo "" echo "==============================================" echo "Baserow local development environment started!" @@ -349,6 +362,7 @@ _dev-start: echo " Frontend: ${PUBLIC_WEB_FRONTEND_URL:-http://localhost:3000}" echo " Storybook: http://localhost:${BASEROW_STORYBOOK_PORT:-6006}" echo " Mailhog: http://localhost:${MAILHOG_STATUS_PORT}" + echo " Inbound email: ${INBOUND_EMAIL_STATUS}" echo "" echo "Commands:" echo " just dev logs # View logs" @@ -407,6 +421,9 @@ _dev-stop: rm -f "${LOCAL_DEV_PREFIX}-storybook.pid" fi + # Stop the inbound email receiver if `just dev up` started it, before the + # stack's network goes away underneath it. + just mox _down-docker 2>/dev/null || true # Stop docker services echo "Stopping Docker services..." just dc-dev down @@ -462,6 +479,11 @@ _dev-tmux: create_window "celery" "$ROOT/backend" "just run-dev-celery" create_window "db" "$ROOT" "just dc-dev logs -f db" "PGPASSWORD=${DATABASE_PASSWORD:-baserow} just dc-dev exec db psql -U ${DATABASE_USER:-baserow} -d ${DATABASE_NAME:-baserow}" create_window "redis" "$ROOT" "just dc-dev logs -f redis" "just dc-dev exec redis redis-cli -a ${REDIS_PASSWORD:-baserow}" + # Inbound email receiver (mox), only when the trigger is configured in + # .env.local: the receiver in the left pane, the trigger addresses on the right. + if [[ -n "${BASEROW_INBOUND_EMAIL_DOMAIN:-}" && -n "${BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET:-}" ]]; then + create_window "mox" "$ROOT" "just mox up" "just mox address" + fi # Kill the temporary window tmux kill-window -t $SESSION:_tmp @@ -488,6 +510,12 @@ frontend *args: # Shortcut alias for frontend alias f := frontend +# Run any mox recipe for local "Start workflow by email" testing +[group('1 - local-dev')] +[doc("Run mox command: just mox (e.g., mox init, mox up, mox send)")] +mox *args: + @just --justfile mox.just {{ args }} + # Run all linters (backend + frontend) [group('1 - local-dev')] [doc("Lint all code (backend + frontend)")] @@ -581,6 +609,19 @@ dc-dev *ARGS: mkdir -p web-frontend/node_modules fi + # Enable the "inbound-email" profile (mox receiver) automatically once + # .env.docker-dev configures the trigger, so no COMPOSE_PROFILES edit is + # needed. Read from the file on purpose: the native `just dev` flow + # starts its own receiver via `just mox up -d`. + _env_value() { grep -E "^$1=" .env.docker-dev 2>/dev/null | tail -1 | cut -d= -f2- | sed 's/[[:space:]]*#.*$//; s/^["'"'"']//; s/["'"'"']$//'; } + if [[ -n "$(_env_value BASEROW_INBOUND_EMAIL_DOMAIN)" && -n "$(_env_value BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET)" ]]; then + PROFILES="${COMPOSE_PROFILES:-$(_env_value COMPOSE_PROFILES)}" + case ",${PROFILES}," in + *,inbound-email,*) ;; + *) PROFILES="${PROFILES:+${PROFILES},}inbound-email" ;; + esac + export COMPOSE_PROFILES="$PROFILES" + fi DC="docker compose --env-file .env.docker-dev -f docker-compose.yml -f docker-compose.dev.yml" ALLARGS=({{ ARGS }}) CMD="${ALLARGS[0]:-}" @@ -648,6 +689,12 @@ _dc-dev-tmux: create_window "celery" "just dc-dev exec celery bash" "just dc-dev logs -f celery celery-beat-worker celery-export-worker" create_window "db" "just dc-dev exec db psql -U baserow" "just dc-dev logs -f db" create_window "redis" "just dc-dev exec redis redis-cli" "just dc-dev logs -f redis" + # Inbound email receiver (mox): `just dc-dev up` starts it when + # .env.docker-dev sets both variables, so give it a window too. + if grep -qE '^BASEROW_INBOUND_EMAIL_DOMAIN=.+' .env.docker-dev 2>/dev/null \ + && grep -qE '^BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET=.+' .env.docker-dev 2>/dev/null; then + create_window "mox" "just dc-dev exec email-receiver bash" "just dc-dev logs -f email-receiver" + fi # Kill the temporary window tmux kill-window -t $SESSION:_tmp @@ -744,6 +791,12 @@ _dc-dev-tabs *ARGS: launch_tab_and_attach "celery" "celery" launch_tab_and_attach "export worker" "celery-export-worker" launch_tab_and_attach "beat worker" "celery-beat-worker" + # Inbound email receiver (mox), started by `just dc-dev up` when + # .env.docker-dev sets both variables. + if grep -qE '^BASEROW_INBOUND_EMAIL_DOMAIN=.+' .env.docker-dev 2>/dev/null \ + && grep -qE '^BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET=.+' .env.docker-dev 2>/dev/null; then + launch_tab_and_attach "mox" "email-receiver" + fi # Open lint tabs launch_tab_and_exec "web frontend lint" \ diff --git a/mox.just b/mox.just new file mode 100644 index 0000000000..b36c8cce0c --- /dev/null +++ b/mox.just @@ -0,0 +1,376 @@ +# Mox mail server recipes for local development of the "Start workflow by email" +# automation trigger. Delegated to from the root justfile as `just mox `. +# +# Typical flow (backend running natively with `just dev`): +# just mox up # run the receiver in Docker (foreground, Ctrl+C to stop) +# just mox address # print the trigger's inbound address (copy from here) +# just mox send

# send a test email through mox +# +# `just mox up` runs the same `email-receiver` role as production from the +# backend dev image (compose profile "inbound-email"), so nothing has to be installed on +# the host. It posts webhooks to the natively running backend through +# host.docker.internal. Once BASEROW_INBOUND_EMAIL_DOMAIN and +# BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET are set in .env.local, `just dev up` +# starts the receiver automatically (`just mox up -d`) and `just dev stop` +# stops it. The fully dockerised stack does the same from .env.docker-dev. +# +# Native alternative, if you have the `mox` binary installed (brew install mox): +# just mox init # one-time (or after a reset): generate + validate config +# just mox up-native # run `mox localserve` (foreground, Ctrl+C to stop) + +set unstable := true + +# Where the throwaway mox config + message store live. A short path is required: +# mox's unix control socket hits the macOS ~104 char sun_path limit otherwise. +MOX_DIR := "/tmp/baserow-mox" + +# Host port the receiver's SMTP listener is published on. Deliberately 2025, not +# localserve's default 1025, which collides with MailHog in the standard Baserow +# dev stack. Override with BASEROW_INBOUND_EMAIL_HOST_SMTP_PORT if 2025 is taken. +MOX_SMTP_PORT := env_var_or_default("BASEROW_INBOUND_EMAIL_HOST_SMTP_PORT", "2025") + +# Load the repo-root .env.local so the mox config uses the SAME inbound domain +# and webhook secret the backend reads, keeping the two sides in sync. +_load_env := 'set -a; [ -f .env.local ] && . ./.env.local; set +a' + +# The dev compose stack; the receiver is defined in docker-compose.yml behind the +# "inbound-email" profile and built from the dev image by docker-compose.dev.yml. +_dc := 'docker compose --env-file .env.docker-dev -f docker-compose.yml -f docker-compose.dev.yml' + +# Show the available mox recipes. +[doc("List mox recipes")] +default: + @just --justfile mox.just --list + +# Check the mox binary is installed, with install hints if not. +_check-binary: + #!/usr/bin/env bash + set -euo pipefail + if ! command -v mox >/dev/null 2>&1; then + echo "error: 'mox' is not installed or not on PATH." >&2 + echo " macOS: brew install mox" >&2 + echo " other: go install github.com/mjl-/mox@latest (needs Go)" >&2 + echo " docs: https://github.com/mjl-/mox" >&2 + exit 1 + fi + +# Ensure .env.local carries the two variables both the backend and the receiver +# need, generating a secret if absent. Appended only when the key is missing. +_ensure-env: + #!/usr/bin/env bash + set -euo pipefail + {{ _load_env }} + if [ -z "${BASEROW_INBOUND_EMAIL_DOMAIN:-}" ]; then + echo "BASEROW_INBOUND_EMAIL_DOMAIN=inbound.baserow.local" >> .env.local + echo " + added BASEROW_INBOUND_EMAIL_DOMAIN=inbound.baserow.local to .env.local" + fi + if [ -z "${BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET:-}" ]; then + echo "BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET=$(openssl rand -hex 16)" >> .env.local + echo " + added BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET (generated) to .env.local" + fi + # The backend deletes handed-over messages through the receiver's web API, + # published on loopback by the dev compose override. + if [ -z "${BASEROW_INBOUND_EMAIL_RECEIVER_URL:-}" ]; then + echo "BASEROW_INBOUND_EMAIL_RECEIVER_URL=http://localhost:${BASEROW_INBOUND_EMAIL_WEBAPI_HOST_PORT:-8880}" >> .env.local + echo " + added BASEROW_INBOUND_EMAIL_RECEIVER_URL to .env.local" + fi + +# Run the receiver in Docker from the backend dev image, next to a backend that +# runs natively on the host. Builds the dev image on first use. Pass -d to run +# detached (used by `just dev up`). +[doc("Run the mox receiver in Docker (foreground, Ctrl+C to stop; -d to detach)")] +up *FLAGS: + #!/usr/bin/env bash + set -euo pipefail + DETACHED=false + for flag in {{ FLAGS }}; do + [ "$flag" = "-d" ] && DETACHED=true + done + just --justfile mox.just _ensure-env + {{ _load_env }} + if [ ! -f .env.docker-dev ] && [ -f .env.docker-dev.example ]; then + cp .env.docker-dev.example .env.docker-dev + fi + # Build args for the dev image, as `just dc-dev` sets them. + if [[ -z "${UID:-}" ]]; then UID=$(id -u); fi; export UID + if [[ -z "${GID:-}" ]]; then GID=$(id -g); fi; export GID + # The container reaches the host's backend through Docker's host gateway. + BACKEND_URL="${PUBLIC_BACKEND_URL:-http://localhost:8000}" + BACKEND_URL="${BACKEND_URL/localhost/host.docker.internal}" + BACKEND_URL="${BACKEND_URL/127.0.0.1/host.docker.internal}" + export BASEROW_INBOUND_EMAIL_WEBHOOK_URL="${BASEROW_INBOUND_EMAIL_WEBHOOK_URL:-${BACKEND_URL%/}/api/inbound-email/}" + export BASEROW_INBOUND_EMAIL_HOST_SMTP_PORT="{{ MOX_SMTP_PORT }}" + export BASEROW_INBOUND_EMAIL_HOST_PUBLISH_IP="${BASEROW_HOST_PUBLISH_IP:-127.0.0.1}" + export BASEROW_INBOUND_EMAIL_DOMAIN BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET + export BASEROW_INBOUND_EMAIL_WEBAPI_HOST_PORT="${BASEROW_INBOUND_EMAIL_WEBAPI_HOST_PORT:-8880}" + if ! docker image inspect baserow_backend:dev >/dev/null 2>&1; then + echo "Building the backend dev image (first run only, takes a few minutes)..." + {{ _dc }} build email-receiver + fi + if [ "$DETACHED" = true ]; then + {{ _dc }} --profile inbound-email up -d --no-deps email-receiver + echo "Mox receiver started for '$BASEROW_INBOUND_EMAIL_DOMAIN' (SMTP on localhost:{{ MOX_SMTP_PORT }}, webhooks to $BASEROW_INBOUND_EMAIL_WEBHOOK_URL). Logs: docker logs -f baserow-email-receiver-1" + else + echo "Starting the mox receiver for '$BASEROW_INBOUND_EMAIL_DOMAIN' (SMTP on localhost:{{ MOX_SMTP_PORT }}, webhooks to $BASEROW_INBOUND_EMAIL_WEBHOOK_URL). Press Ctrl+C to stop." + exec {{ _dc }} --profile inbound-email up --no-deps email-receiver + fi + +# Wipe {{ MOX_DIR }} and generate a fresh, validated config for the native +# `mox localserve` flow. Safe to re-run: it always starts from a clean directory. +[doc("Native flow: wipe, regenerate and validate the local mox config")] +init: _check-binary + #!/usr/bin/env bash + set -euo pipefail + just --justfile mox.just _ensure-env + {{ _load_env }} + DOMAIN="$BASEROW_INBOUND_EMAIL_DOMAIN" + SECRET="$BASEROW_INBOUND_EMAIL_WEBHOOK_SECRET" + WEBHOOK_URL="${BASEROW_INBOUND_EMAIL_WEBHOOK_URL:-}" + if [ -z "$WEBHOOK_URL" ]; then + : "${PUBLIC_BACKEND_URL:?Set PUBLIC_BACKEND_URL in .env.local}" + WEBHOOK_URL="${PUBLIC_BACKEND_URL%/}/api/inbound-email/" + fi + + echo "Generating mox config in {{ MOX_DIR }} for domain '$DOMAIN'..." + rm -rf "{{ MOX_DIR }}" + mkdir -p "{{ MOX_DIR }}" + mox localserve -dir "{{ MOX_DIR }}" -initonly >/dev/null + + # Patch the generated config: SMTP port, inbound domain, catch-all + # destination, and the incoming webhook pointing at the backend. + MOX_DIR="{{ MOX_DIR }}" \ + MOX_SMTP_PORT="{{ MOX_SMTP_PORT }}" \ + INBOUND_DOMAIN="$DOMAIN" \ + WEBHOOK_URL="$WEBHOOK_URL" \ + WEBHOOK_SECRET="$SECRET" \ + python3 <<'PY' + import os + + mox_dir = os.environ["MOX_DIR"] + smtp_port = os.environ["MOX_SMTP_PORT"] + domain = os.environ["INBOUND_DOMAIN"] + url = os.environ["WEBHOOK_URL"] + secret = os.environ["WEBHOOK_SECRET"] + + # mox.conf: move the SMTP listener off localserve's default 1025. + conf_path = os.path.join(mox_dir, "mox.conf") + conf = open(conf_path).read() + old_port = "Port: 1025\n" + assert conf.count(old_port) == 1, f"expected one SMTP Port: 1025, found {conf.count(old_port)}" + conf = conf.replace(old_port, f"Port: {smtp_port}\n") + open(conf_path, "w").write(conf) + + # domains.conf: add the inbound domain, a catch-all destination, and the + # incoming webhook. sconf is tab-indented and orders IncomingWebhook before + # the KeepRetired* account fields, so it goes in as the first account field. + dom_path = os.path.join(mox_dir, "domains.conf") + dom = open(dom_path).read() + + old = "Domains:\n\tlocalhost:\n" + new = ( + "Domains:\n" + f"\t{domain}:\n" + "\t\tLocalpartCatchallSeparator: +\n" + "\tlocalhost:\n" + ) + assert dom.count(old) == 1, "domains anchor not found" + dom = dom.replace(old, new) + + old = "Accounts:\n\tmox:\n\n" + new = ( + "Accounts:\n\tmox:\n\n" + "\t\tIncomingWebhook:\n" + f"\t\t\tURL: {url}\n" + f"\t\t\tAuthorization: {secret}\n\n" + ) + assert dom.count(old) == 1, "account anchor not found" + dom = dom.replace(old, new) + + old = "\t\tDestinations:\n\t\t\tmox@localhost: nil\n" + new = ( + "\t\tDestinations:\n\t\t\tmox@localhost: nil\n" + f"\t\t\t@{domain}: nil\n" + ) + assert dom.count(old) == 1, "destinations anchor not found" + dom = dom.replace(old, new) + + # Remove the account's JunkFilter block (optional in sconf) so localserve + # stops rejecting small test emails as "junk-content-strict" (a fresh + # account has an untrained filter and rejects almost everything). + import re + + dom, removed = re.subn( + r"\t\tJunkFilter:\n(?:.*\n)*?(?=\t\t# Do not apply a delay)", "", dom + ) + assert removed == 1, "JunkFilter block not found" + + open(dom_path, "w").write(dom) + print(" + patched mox.conf and domains.conf") + PY + + just --justfile mox.just test + echo "" + echo "Mox is configured. Next:" + echo " just mox up-native # start the native mail server" + echo " just mox address # copy the trigger's inbound address" + echo " just mox send
# send a test email" + +# Run the native mox mail server in the foreground (Ctrl+C to stop). +# Auto-initialises the config if it does not exist yet. +[doc("Native flow: run `mox localserve` (foreground, Ctrl+C to stop)")] +up-native: _check-binary + #!/usr/bin/env bash + set -euo pipefail + if [ ! -f "{{ MOX_DIR }}/mox.conf" ]; then + echo "No mox config found, running 'just mox init' first..." + just --justfile mox.just init + fi + echo "Starting mox (SMTP on localhost:{{ MOX_SMTP_PORT }}). Press Ctrl+C to stop." + exec mox localserve -dir "{{ MOX_DIR }}" + +# Stop and remove the Docker receiver only (used by `just dev stop`). Prints +# nothing when it is not running. +_down-docker: + #!/usr/bin/env bash + set -euo pipefail + if [ -f .env.docker-dev ] && {{ _dc }} --profile inbound-email ps -q email-receiver 2>/dev/null | grep -q .; then + {{ _dc }} --profile inbound-email rm -sf email-receiver >/dev/null 2>&1 + echo "Stopped the mox receiver container." + fi + +# Stop the receiver, whether it runs as the Docker service or as a +# (backgrounded) native `mox localserve`. +[doc("Stop the mox receiver (Docker or native)")] +down: + #!/usr/bin/env bash + set -euo pipefail + stopped=0 + if [ -n "$(just --justfile mox.just _down-docker)" ]; then + echo "Stopped the mox receiver container." + stopped=1 + fi + if pkill -f "mox localserve -dir {{ MOX_DIR }}"; then + echo "Stopped native mox localserve." + stopped=1 + fi + [ "$stopped" = 1 ] || echo "No running mox receiver found." + +# Validate the generated mox config. +[doc("Native flow: validate the generated mox config")] +test: + #!/usr/bin/env bash + set -euo pipefail + if [ ! -f "{{ MOX_DIR }}/mox.conf" ]; then + echo "No mox config found. Run 'just mox init' first." >&2 + exit 1 + fi + MOXCONF="{{ MOX_DIR }}/mox.conf" mox config test + +# Remove the mox config and message store entirely. +[doc("Native flow: remove the mox config and message store")] +clean: + #!/usr/bin/env bash + set -euo pipefail + rm -rf "{{ MOX_DIR }}" + echo "Removed {{ MOX_DIR }}." + +# Print the inbound email addresses of all configured trigger services, so you +# can copy one instead of hunting for it in the UI. +[doc("Print configured inbound trigger addresses")] +address: + #!/usr/bin/env bash + set -euo pipefail + cd backend + just manage shell <<'PY' 2>/dev/null | grep '@' || echo "No configured inbound email trigger services found (create one in the UI, or check BASEROW_INBOUND_EMAIL_DOMAIN)." + from baserow.contrib.integrations.core.models import CoreInboundEmailTriggerService + for s in CoreInboundEmailTriggerService.objects.all(): + # The draft is reached through the `test-` prefixed address. + addr = s.email_address if s.is_public else s.test_email_address + if addr: + print(f"{addr} (service {s.id}, {'published' if s.is_public else 'draft'})") + PY + +# Send a test email through mox to the given trigger address. Uses a fresh +# Message-ID each time so it never trips the duplicate-delivery guard. The +# subject is variadic, so trailing words are used as-is without quoting. +# `--body FILE` / `--html FILE` replace the default plain-text / HTML part with +# the contents of a file (relative to where you ran just; no spaces in paths), +# e.g. to send a message close to the receiver's size limit +# (BASEROW_INBOUND_EMAIL_MAX_MESSAGE_SIZE_MB). Whatever the message size, mox +# forwards at most 1 MiB of each part to the backend. +# Usage: just mox send
[--body FILE] [--html FILE] [subject words...] +[doc("Send a test email: just mox send
[--body FILE] [--html FILE] [subject words...]")] +send ADDRESS *ARGS: + #!/usr/bin/env bash + set -euo pipefail + if ! (exec 3<>"/dev/tcp/127.0.0.1/{{ MOX_SMTP_PORT }}") 2>/dev/null; then + echo "error: nothing is listening on localhost:{{ MOX_SMTP_PORT }}. Is mox running? Start it with: just mox up" >&2 + exit 1 + fi + MOX_SMTP_PORT="{{ MOX_SMTP_PORT }}" \ + TO_ADDRESS="{{ ADDRESS }}" \ + ARGS="{{ ARGS }}" \ + INVOCATION_DIR="{{ invocation_directory() }}" \ + python3 <<'PY' + import os, smtplib, sys, time + from email.message import EmailMessage + + # Pull `--body FILE` / `--html FILE` out of the trailing words; the rest is + # the subject. + body_file = html_file = None + subject_words = [] + args = os.environ["ARGS"].split() + while args: + arg = args.pop(0) + if arg in ("--body", "--html"): + if not args: + sys.exit(f"error: {arg} needs a file path") + path = os.path.join(os.environ["INVOCATION_DIR"], args.pop(0)) + if arg == "--body": + body_file = path + else: + html_file = path + else: + subject_words.append(arg) + + def read_part(path, default): + if path is None: + return default + try: + with open(path, encoding="utf-8") as f: + return f.read() + except OSError as e: + sys.exit(f"error: cannot read {path}: {e.strerror}") + + text = read_part(body_file, "This is the plain text body sent through local mox.") + html = read_part( + html_file, + "

This is the HTML body sent through local mox.

", + ) + to_address = os.environ["TO_ADDRESS"] + + msg = EmailMessage() + msg["From"] = "Ada Lovelace " # must be @localhost for mox + msg["To"] = to_address + msg["Subject"] = " ".join(subject_words) or "Test email from 'just mox send'" + msg["Message-ID"] = f"<{time.time_ns()}.{os.getpid()}@localhost>" + msg.set_content(text) + msg.add_alternative(html, subtype="html") + + # Flatten once with SMTP line endings, so the size printed is the size sent + # (and the one mox checks against SMTPMaxMessageSize). + raw = msg.as_bytes(policy=msg.policy.clone(linesep="\r\n")) + port = int(os.environ["MOX_SMTP_PORT"]) + try: + with smtplib.SMTP("localhost", port) as smtp: + smtp.sendmail("mox@localhost", [to_address], raw) + except smtplib.SMTPResponseException as e: + detail = e.smtp_error + detail = detail.decode(errors="replace") if isinstance(detail, bytes) else detail + sys.exit(f"error: mox refused the message: {e.smtp_code} {detail}") + except smtplib.SMTPRecipientsRefused as e: + sys.exit(f"error: mox refused the recipient: {e.recipients}") + print(f"Sent to {to_address} via localhost:{port} ({len(raw) / 1024 / 1024:.2f} MiB)") + if max(len(text), len(html)) > 1024 * 1024: + print("Note: mox forwards at most 1 MiB of each of the text and HTML parts to the backend.") + PY diff --git a/web-frontend/modules/automation/components/form/SimulateDispatchNodeForm.vue b/web-frontend/modules/automation/components/form/SimulateDispatchNodeForm.vue index 37785cdc7e..e6b2db8bcb 100644 --- a/web-frontend/modules/automation/components/form/SimulateDispatchNodeForm.vue +++ b/web-frontend/modules/automation/components/form/SimulateDispatchNodeForm.vue @@ -36,6 +36,8 @@ sample.value !== null) const isErrorSample = computed(() => Boolean(sample.value?._error)) +// Error samples are plain text, so they always render as JSON regardless of +// the node's sample data content type. +const sampleDataContentType = computed(() => + isErrorSample.value + ? 'json' + : nodeType.value.getSampleDataContentType(props.node) +) + +const sampleDataHtml = computed(() => + isErrorSample.value ? null : nodeType.value.getSampleDataHtml(props.node) +) + /** * All previous nodes must have been tested, i.e. they must have sample * data and shouldn't be in error. diff --git a/web-frontend/modules/automation/components/workflow/WorkflowAddNodeMenu.vue b/web-frontend/modules/automation/components/workflow/WorkflowAddNodeMenu.vue index 9597ac9448..b2537db188 100644 --- a/web-frontend/modules/automation/components/workflow/WorkflowAddNodeMenu.vue +++ b/web-frontend/modules/automation/components/workflow/WorkflowAddNodeMenu.vue @@ -87,6 +87,7 @@ export default { .getOrderedList('node') .filter( (nodeType) => + nodeType.isEnabled() && this.node?.type !== nodeType.type && (this.editingTriggerNode ? nodeType.isTrigger diff --git a/web-frontend/modules/automation/nodeTypes.js b/web-frontend/modules/automation/nodeTypes.js index 1181459d5f..15cf571962 100644 --- a/web-frontend/modules/automation/nodeTypes.js +++ b/web-frontend/modules/automation/nodeTypes.js @@ -22,6 +22,7 @@ import { import LocalBaserowNodeServiceForm from '@baserow/modules/automation/components/workflow/LocalBaserowNodeServiceForm' import { CoreCSVFileReaderServiceType, + CoreInboundEmailTriggerServiceType, CoreHTTPRequestServiceType, CoreRouterServiceType, CoreGotoServiceType, @@ -354,10 +355,42 @@ export class NodeType extends Registerable { return this.serviceType.getSampleData(service) } + /** + * The content type of this node's sample data. Nodes returning 'html' get + * an extra HTML preview tab in the sample data modal. + */ + getSampleDataContentType({ service }) { + if (!service) { + return 'json' + } + return this.serviceType.getSampleDataContentType(service) + } + + /** + * The HTML document rendered in the sample data modal's HTML tab. + */ + getSampleDataHtml({ service }) { + if (!service) { + return null + } + return this.serviceType.getSampleDataHtml(service) + } + getEdges({ node }) { return [{ uid: '', label: '' }] } + /** + * Whether this node type is offered at all. Unlike `isDeactivated`, which + * keeps the entry in the add-node menu but disabled with a reason, a type + * that is not enabled is omitted from the menu entirely. Types that only make + * sense when the instance is configured for them override this. + * @returns {boolean} + */ + isEnabled() { + return true + } + isDeactivatedReason({ workspace }) { const serviceReason = this.serviceType.isDeactivatedReason({ workspace }) if (serviceReason) { @@ -631,6 +664,52 @@ export class CoreHTTPTriggerNodeType extends TriggerNodeTypeMixin(NodeType) { } } +export class CoreInboundEmailTriggerNodeType extends TriggerNodeTypeMixin( + NodeType +) { + static getType() { + return 'email_trigger' + } + + get name() { + return this.app.$i18n.t('serviceType.inboundEmailTrigger') + } + + get description() { + return this.app.$i18n.t('serviceType.inboundEmailTriggerDescription') + } + + get serviceType() { + return this.app.$registry.get( + 'service', + CoreInboundEmailTriggerServiceType.getType() + ) + } + + getOrder() { + return 4.5 + } + + /** + * Only offered when the instance is configured for inbound email. The + * backend derives that from its environment (domain, webhook secret and the + * receiver URL its message sweep needs) and publishes the result in the + * public settings, so this mirrors the exact gate that would otherwise + * refuse to create the node. Without it the trigger is left out of the menu + * rather than shown deactivated, so instances that never use inbound email + * do not carry a dead entry. + */ + isEnabled() { + return ( + this.app.$store.getters['settings/get']?.inbound_email_enabled === true + ) + } + + getDefaultLabel({ automation, node }) { + return this.app.$i18n.t('serviceType.inboundEmailTrigger') + } +} + export class CoreManualTriggerNodeType extends TriggerNodeTypeMixin(NodeType) { static getType() { return 'manual' diff --git a/web-frontend/modules/automation/plugin.js b/web-frontend/modules/automation/plugin.js index 24dcc2db05..11cb3be71f 100644 --- a/web-frontend/modules/automation/plugin.js +++ b/web-frontend/modules/automation/plugin.js @@ -22,6 +22,7 @@ import { LocalBaserowRowsDeletedTriggerNodeType, LocalBaserowFieldsUpdatedTriggerNodeType, CoreHTTPTriggerNodeType, + CoreInboundEmailTriggerNodeType, LocalBaserowAggregateRowsActionNodeType, CoreCSVFileReaderNodeType, CoreHttpRequestNodeType, @@ -109,6 +110,7 @@ export default defineNuxtPlugin({ new LocalBaserowFieldsUpdatedTriggerNodeType(context) ) $registry.register('node', new CoreHTTPTriggerNodeType(context)) + $registry.register('node', new CoreInboundEmailTriggerNodeType(context)) $registry.register('node', new LocalBaserowCreateRowActionNodeType(context)) $registry.register( 'node', diff --git a/web-frontend/modules/automation/realtime.js b/web-frontend/modules/automation/realtime.js index 5412546ea0..c314a6289c 100644 --- a/web-frontend/modules/automation/realtime.js +++ b/web-frontend/modules/automation/realtime.js @@ -86,6 +86,16 @@ export const registerRealtimeEvents = (realtime) => { ) if (!existing) return + // The event was too large for a websocket frame, so the server left the + // sample data out and asks us to reload the node over HTTP instead. + if (data.requires_refresh === true) { + store.dispatch('automationWorkflowNode/refetch', { + workflow, + nodeId: node.id, + }) + return + } + store.dispatch('automationWorkflowNode/forceUpdate', { workflow, node: existing, diff --git a/web-frontend/modules/automation/store/automationWorkflowNode.js b/web-frontend/modules/automation/store/automationWorkflowNode.js index 41f4d1fae8..daa0d47522 100644 --- a/web-frontend/modules/automation/store/automationWorkflowNode.js +++ b/web-frontend/modules/automation/store/automationWorkflowNode.js @@ -315,6 +315,29 @@ const actions = { throw error } }, + /** + * Reloads one node from the server and applies it as a realtime update. + * Used when a websocket event was too large to carry the node's sample data + * and arrived with `requires_refresh` instead; the list endpoint is the only + * read endpoint for nodes, so the workflow's nodes are fetched and the one we + * need is picked out, leaving the selection and the other nodes untouched. + */ + async refetch({ dispatch, getters }, { workflow, nodeId }) { + const { data: nodes } = await AutomationWorkflowNodeService( + this.$client + ).get(workflow.id) + const values = nodes.find((node) => node.id === nodeId) + const existing = getters.findById(workflow, nodeId) + if (!values || !existing) return null + await dispatch('forceUpdate', { + workflow, + node: existing, + values, + override: true, + viaRealtime: true, + }) + return getters.findById(workflow, nodeId) + }, forceUpdate({ commit }, { workflow, node, values, override, viaRealtime }) { commit('UPDATE_ITEM', { workflow, diff --git a/web-frontend/modules/core/assets/scss/components/all.scss b/web-frontend/modules/core/assets/scss/components/all.scss index 0e5be0609c..66a13b734b 100644 --- a/web-frontend/modules/core/assets/scss/components/all.scss +++ b/web-frontend/modules/core/assets/scss/components/all.scss @@ -170,6 +170,7 @@ @import 'integrations/all'; @import 'services/service_form'; @import 'services/webhook_service_form'; +@import 'services/inbound_email_trigger_service_form'; @import 'editable'; @import 'notification_panel'; @import 'color_picker'; diff --git a/web-frontend/modules/core/assets/scss/components/sample_data_modal.scss b/web-frontend/modules/core/assets/scss/components/sample_data_modal.scss index 95bab25e0a..4159b289f9 100644 --- a/web-frontend/modules/core/assets/scss/components/sample_data_modal.scss +++ b/web-frontend/modules/core/assets/scss/components/sample_data_modal.scss @@ -52,3 +52,13 @@ .sample-data-modal__button-icon { color: $palette-neutral-600; } + +.sample-data-modal__html-preview { + display: block; + width: 100%; + height: 50vh; + border: 1px solid $palette-neutral-200; + background-color: $palette-neutral-0; + + @include rounded($rounded); +} diff --git a/web-frontend/modules/core/assets/scss/components/services/inbound_email_trigger_service_form.scss b/web-frontend/modules/core/assets/scss/components/services/inbound_email_trigger_service_form.scss new file mode 100644 index 0000000000..1cb7a24631 --- /dev/null +++ b/web-frontend/modules/core/assets/scss/components/services/inbound_email_trigger_service_form.scss @@ -0,0 +1,24 @@ +.inbound-email-trigger-service-form__copy-address { + position: relative; + text-decoration: none; + user-select: none; + color: $palette-neutral-1000; + + &:hover { + text-decoration: none; + color: $palette-neutral-1000; + } +} + +.inbound-email-trigger-service-form__email-address { + display: block; + width: 100%; + padding: 6px; + font-size: 12px; + background-color: $palette-neutral-100; + line-height: 140%; + white-space: pre-wrap; + overflow-wrap: break-word; + + @include rounded($rounded); +} diff --git a/web-frontend/modules/core/components/SampleDataModal.vue b/web-frontend/modules/core/components/SampleDataModal.vue index a8a9382a89..24f8d22ab0 100644 --- a/web-frontend/modules/core/components/SampleDataModal.vue +++ b/web-frontend/modules/core/components/SampleDataModal.vue @@ -30,7 +30,26 @@ }) }} -
+ + +
+
{{ displayedFormattedSampleData }}
+
+
+ + +
+ {{ $t('sampleDataViewer.noHtmlContent') }} +
+
+
+
{{ displayedFormattedSampleData }}
@@ -42,6 +61,13 @@ import { notifyIf } from '@baserow/modules/core/utils/error' const MAX_FORMATTED_SAMPLE_DATA_LENGTH = 10000 +// Prepended to the HTML preview. The iframe's empty sandbox already blocks +// scripts, forms and navigation; this policy additionally stops the document +// from loading anything remote, so a tracking pixel in a received email cannot +// report when, and from which address, the sample was previewed. +const SAMPLE_DATA_HTML_CSP = + '' + export default { name: 'SampleDataModal', mixins: [modal], @@ -50,6 +76,25 @@ export default { type: null, required: true, }, + /** + * The content type of the sample data. When it's 'html', the modal + * shows a JSON and an HTML tab instead of only the JSON payload. + */ + contentType: { + type: String, + required: false, + default: 'json', + }, + /** + * The HTML document rendered in the HTML tab when the content type is + * 'html'. It's rendered in a fully sandboxed iframe because the content + * is untrusted (e.g. a received email). + */ + sampleDataHtml: { + type: String, + required: false, + default: null, + }, title: { type: String, required: true, @@ -65,6 +110,14 @@ export default { }, }, computed: { + hasHtmlTab() { + return this.contentType === 'html' + }, + sandboxedSampleDataHtml() { + return this.sampleDataHtml + ? `${SAMPLE_DATA_HTML_CSP}${this.sampleDataHtml}` + : null + }, maxFormattedSampleDataLength() { return MAX_FORMATTED_SAMPLE_DATA_LENGTH }, diff --git a/web-frontend/modules/core/components/SampleDataViewer.vue b/web-frontend/modules/core/components/SampleDataViewer.vue index aef023edfc..812df1b383 100644 --- a/web-frontend/modules/core/components/SampleDataViewer.vue +++ b/web-frontend/modules/core/components/SampleDataViewer.vue @@ -25,6 +25,8 @@ @@ -45,6 +47,16 @@ export default { required: false, default: null, }, + contentType: { + type: String, + required: false, + default: 'json', + }, + sampleDataHtml: { + type: String, + required: false, + default: null, + }, isError: { type: Boolean, required: false, diff --git a/web-frontend/modules/core/locales/en.json b/web-frontend/modules/core/locales/en.json index e74ceb581e..bbd9400dbb 100644 --- a/web-frontend/modules/core/locales/en.json +++ b/web-frontend/modules/core/locales/en.json @@ -32,7 +32,8 @@ "showErrorLabel": "Show error", "downloadFullPayload": "Download full payload", "truncatedLabel": "[Output truncated]", - "truncatedPayloadWarning": "Only the first {size} characters are shown. Download the full payload to inspect it on your computer." + "truncatedPayloadWarning": "Only the first {size} characters are shown. Download the full payload to inspect it on your computer.", + "noHtmlContent": "This email has no HTML body." }, "action": { "cancel": "Cancel", @@ -1322,6 +1323,18 @@ "methodsOptionAll": "All", "methodsOptionExcludeGet": "Exclude GET" }, + "inboundEmailTriggerServiceForm": { + "title": "Email address", + "addressVersionTest": "Test", + "addressVersionPublished": "Published", + "copyAddress": "Copy email address", + "description": "Any email sent to this address will start the workflow with the email's sender, subject, body and attachment details as the payload.", + "limits": "Emails up to {size} MB are accepted, and the text and HTML bodies are passed on up to 1 MB each. Attachments are not stored: only their name, type and size are included in the payload.", + "autoForwardTip": "Tip: you can also add this address as an auto-forward rule in your own inbox, so the workflow runs whenever you receive an email.", + "secretWarning": "Treat this address as a secret: anyone who knows it can start this workflow.", + "regenerate": "Regenerate address", + "notConfigured": "This Baserow instance is not configured to receive inbound email. Set the BASEROW_INBOUND_EMAIL_DOMAIN environment variable to enable this trigger." + }, "twoFactorAuthEmpty": { "title": "You have not yet enabled 2FA", "description": "Add an extra layer of security to your account.", diff --git a/web-frontend/modules/core/serviceTypes.js b/web-frontend/modules/core/serviceTypes.js index 37f52bd634..ec2e0d2e34 100644 --- a/web-frontend/modules/core/serviceTypes.js +++ b/web-frontend/modules/core/serviceTypes.js @@ -119,6 +119,23 @@ export class ServiceType extends Registerable { return service.sample_data || null } + /** + * The content type of the sample data returned by this service. Service + * types returning 'html' get an extra HTML preview tab in the sample data + * modal, rendering the value of `getSampleDataHtml`. + */ + getSampleDataContentType(service) { + return 'json' + } + + /** + * The HTML document to render in the sample data modal's HTML tab, for + * service types whose sample data content type is 'html'. + */ + getSampleDataHtml(service) { + return null + } + /** * A hook called prior to an update to modify the new values * before they get persisted in the API. diff --git a/web-frontend/modules/integrations/core/components/services/CoreInboundEmailTriggerServiceForm.vue b/web-frontend/modules/integrations/core/components/services/CoreInboundEmailTriggerServiceForm.vue new file mode 100644 index 0000000000..d5bd3f6b99 --- /dev/null +++ b/web-frontend/modules/integrations/core/components/services/CoreInboundEmailTriggerServiceForm.vue @@ -0,0 +1,125 @@ + + + diff --git a/web-frontend/modules/integrations/core/serviceTypes.js b/web-frontend/modules/integrations/core/serviceTypes.js index 6ed5dd79f5..b8e3dd2f92 100644 --- a/web-frontend/modules/integrations/core/serviceTypes.js +++ b/web-frontend/modules/integrations/core/serviceTypes.js @@ -1,4 +1,5 @@ import CoreHTTPTriggerServiceForm from '@baserow/modules/integrations/core/components/services/CoreHTTPTriggerServiceForm' +import CoreInboundEmailTriggerServiceForm from '@baserow/modules/integrations/core/components/services/CoreInboundEmailTriggerServiceForm' import { DataSourceServiceTypeMixin, getFilesGroup, @@ -297,6 +298,58 @@ export class CoreHTTPTriggerServiceType extends TriggerServiceTypeMixin( } } +export class CoreInboundEmailTriggerServiceType extends TriggerServiceTypeMixin( + ServiceType +) { + static getType() { + return 'email_trigger' + } + + get name() { + return this.app.$i18n.t('serviceType.inboundEmailTrigger') + } + + get description() { + return this.app.$i18n.t('serviceType.inboundEmailTriggerDescription') + } + + get formComponent() { + return CoreInboundEmailTriggerServiceForm + } + + get icon() { + return 'iconoir-mail' + } + + getErrorMessage({ service }) { + if (service === undefined) { + return null + } + + return super.getErrorMessage({ service }) + } + + getDataSchema(service) { + return service.schema + } + + /** + * The sample data is a received email, so the sample data modal offers an + * HTML preview tab next to the JSON payload. + */ + getSampleDataContentType(service) { + return 'html' + } + + getSampleDataHtml(service) { + return service.sample_data?.data?.body_html || null + } + + getOrder() { + return 8.5 + } +} + export class CoreManualTriggerServiceType extends TriggerServiceTypeMixin( ServiceType ) { diff --git a/web-frontend/modules/integrations/locales/en.json b/web-frontend/modules/integrations/locales/en.json index 8a70b80142..f110bc9da1 100644 --- a/web-frontend/modules/integrations/locales/en.json +++ b/web-frontend/modules/integrations/locales/en.json @@ -54,6 +54,8 @@ "localBaserowFieldsUpdatedDescription": "Triggered when rows are updated in specific fields of a Baserow table.", "coreHTTPTrigger": "Receive an HTTP Request", "coreHTTPTriggerDescription": "Triggered when an HTTP request is received.", + "inboundEmailTrigger": "Email Trigger", + "inboundEmailTriggerDescription": "Triggered when an email is received on the generated email address.", "coreManualTrigger": "Manual trigger", "coreManualTriggerDescription": "Starts only when another workflow action starts this workflow.", "coreHTTPRequest": "Send an HTTP request", diff --git a/web-frontend/modules/integrations/plugin.js b/web-frontend/modules/integrations/plugin.js index 7ac5717786..4a7e62177f 100644 --- a/web-frontend/modules/integrations/plugin.js +++ b/web-frontend/modules/integrations/plugin.js @@ -19,6 +19,7 @@ import { } from '@baserow/modules/integrations/localBaserow/serviceTypes' import { CoreCSVFileReaderServiceType, + CoreInboundEmailTriggerServiceType, CoreHTTPRequestServiceType, PeriodicTriggerServiceType, CoreRouterServiceType, @@ -82,6 +83,10 @@ export default defineNuxtPlugin({ $registry.register('service', new CoreRouterServiceType(context)) $registry.register('service', new CoreGotoServiceType(context)) $registry.register('service', new CoreHTTPTriggerServiceType(context)) + $registry.register( + 'service', + new CoreInboundEmailTriggerServiceType(context) + ) $registry.register('service', new CoreManualTriggerServiceType(context)) $registry.register('service', new CoreIteratorServiceType(context)) $registry.register('service', new CoreCSVFileReaderServiceType(context)) diff --git a/web-frontend/test/unit/automation/components/workflow/WorkflowAddNodeMenu.spec.js b/web-frontend/test/unit/automation/components/workflow/WorkflowAddNodeMenu.spec.js index 725707fd8e..ccaf6e49dc 100644 --- a/web-frontend/test/unit/automation/components/workflow/WorkflowAddNodeMenu.spec.js +++ b/web-frontend/test/unit/automation/components/workflow/WorkflowAddNodeMenu.spec.js @@ -30,6 +30,7 @@ function makeNodeType({ integrationType = null, isTrigger = false, description = null, + isEnabled = true, }) { return { type, @@ -43,6 +44,7 @@ function makeNodeType({ serviceType: { integrationType }, getType: () => type, getOrder: () => order, + isEnabled: () => isEnabled, isDeactivated: () => false, isDeactivatedReason: () => null, getDeactivatedClickModal: () => null, @@ -78,6 +80,18 @@ const triggerNodeType = makeNodeType({ isTrigger: true, }) +// A trigger the instance is not configured for, e.g. the email trigger without +// an inbound email domain: it must be left out of the menu entirely rather than +// listed as deactivated. +const disabledTriggerNodeType = makeNodeType({ + type: 'email_trigger', + name: 'Email Trigger', + description: 'Triggered when an email is received.', + order: 2, + isTrigger: true, + isEnabled: false, +}) + const workflowTrigger = { id: 1, type: 'rows_created' } const mountComponent = ({ @@ -107,6 +121,7 @@ const mountComponent = ({ getRowNodeType, repeatNodeType, triggerNodeType, + disabledTriggerNodeType, ], get: (registry, type) => registry === 'node' && type === triggerNodeType.getType() @@ -215,6 +230,24 @@ describe('WorkflowAddNodeMenu', () => { ).toBe('Triggered when rows are created.') }) + test('omits node types that are not enabled instead of listing them disabled', () => { + const wrapper = mountComponent({ onlyTrigger: true, workflowNodes: [] }) + + expect(wrapper.vm.nodeTypes.map((nodeType) => nodeType.getType())).toEqual([ + 'rows_created', + ]) + expect( + wrapper + .findAll('.grouped-menu__actions .menu-list__item-label') + .map((item) => item.text()) + ).toEqual(['Rows are created']) + expect( + wrapper + .findAll('.grouped-menu__navigation .menu-list__item-label') + .map((item) => item.text()) + ).toEqual(['Local Baserow']) + }) + test('uses the trigger search when workflow nodes do not include a trigger', () => { const wrapper = mountComponent({ workflowNodes: [{ id: 1, type: 'create_row' }], diff --git a/web-frontend/test/unit/automation/nodeTypes.spec.js b/web-frontend/test/unit/automation/nodeTypes.spec.js index bd28e3bdd9..37b97e4cd2 100644 --- a/web-frontend/test/unit/automation/nodeTypes.spec.js +++ b/web-frontend/test/unit/automation/nodeTypes.spec.js @@ -1,6 +1,7 @@ import { NodeType, CoreRouterNodeType, + CoreInboundEmailTriggerNodeType, } from '@baserow/modules/automation/nodeTypes' import { TestApp } from '@baserow/test/helpers/testApp' @@ -203,3 +204,28 @@ describe('Automation node types', () => { expect(slack.image).toBeUndefined() }) }) + +describe('NodeType.isEnabled', () => { + class TestNodeType extends NodeType { + static getType() { + return 'test' + } + } + + test('node types are enabled by default', () => { + expect(new TestNodeType({ app: {} }).isEnabled()).toBe(true) + }) + + test('the email trigger follows the instance settings flag', () => { + const makeType = (settings) => + new CoreInboundEmailTriggerNodeType({ + app: { $store: { getters: { 'settings/get': settings } } }, + }) + + expect(makeType({ inbound_email_enabled: true }).isEnabled()).toBe(true) + expect(makeType({ inbound_email_enabled: false }).isEnabled()).toBe(false) + // Settings not loaded yet, or an older backend without the flag. + expect(makeType({}).isEnabled()).toBe(false) + expect(makeType(null).isEnabled()).toBe(false) + }) +}) diff --git a/web-frontend/test/unit/automation/store/automationWorkflowNodeRefetch.spec.js b/web-frontend/test/unit/automation/store/automationWorkflowNodeRefetch.spec.js new file mode 100644 index 0000000000..fbb2d33774 --- /dev/null +++ b/web-frontend/test/unit/automation/store/automationWorkflowNodeRefetch.spec.js @@ -0,0 +1,65 @@ +import { TestApp } from '@baserow/test/helpers/testApp' +import nodeStore from '@baserow/modules/automation/store/automationWorkflowNode' + +describe('automationWorkflowNode refetch', () => { + let testApp = null + let store = null + + beforeEach(() => { + testApp = new TestApp() + store = testApp.store + if (!store.hasModule('testNodes')) { + store.registerModule('testNodes', nodeStore) + } + }) + + afterEach(async () => { + await testApp.afterEach() + }) + + test('reloads only the requested node and keeps the selection', async () => { + const trigger = { + id: 1, + type: 'email_trigger', + workflow: 7, + service: { id: 11, sample_data: null }, + } + const action = { + id: 2, + type: 'create_row', + workflow: 7, + service: { id: 12, sample_data: null }, + } + const workflow = { id: 7, nodes: [], selectedNodeId: null } + store.commit('testNodes/SET_ITEMS', { workflow, nodes: [trigger, action] }) + workflow.selectedNodeId = 1 + + const freshSample = { data: { subject: 'Big HTML payload test' } } + testApp.mock.onGet('/automation/workflow/7/nodes/').reply(200, [ + { ...trigger, service: { id: 11, sample_data: freshSample } }, + { ...action, label: 'server-side label' }, + ]) + + const updated = await store.dispatch('testNodes/refetch', { + workflow, + nodeId: 1, + }) + + expect(updated.service.sample_data).toEqual(freshSample) + expect(workflow.selectedNodeId).toBe(1) + // Only the requested node is touched. + expect( + store.getters['testNodes/findById'](workflow, 2).label + ).toBeUndefined() + }) + + test('is a no-op when the node no longer exists', async () => { + const workflow = { id: 7, nodes: [], selectedNodeId: null } + store.commit('testNodes/SET_ITEMS', { workflow, nodes: [] }) + testApp.mock.onGet('/automation/workflow/7/nodes/').reply(200, []) + + await expect( + store.dispatch('testNodes/refetch', { workflow, nodeId: 99 }) + ).resolves.toBeNull() + }) +}) diff --git a/web-frontend/test/unit/core/components/sampleDataModal.spec.js b/web-frontend/test/unit/core/components/sampleDataModal.spec.js new file mode 100644 index 0000000000..d22b0eafdf --- /dev/null +++ b/web-frontend/test/unit/core/components/sampleDataModal.spec.js @@ -0,0 +1,102 @@ +import { defineComponent } from 'vue' +import { mountSuspended } from '@nuxt/test-utils/runtime' + +import SampleDataModal from '@baserow/modules/core/components/SampleDataModal' + +const ModalStub = defineComponent({ + name: 'Modal', + methods: { + show() {}, + hide() {}, + }, + template: '', +}) + +const ButtonStub = defineComponent({ + name: 'Button', + inheritAttrs: false, + template: '', +}) + +const TabsStub = defineComponent({ + name: 'Tabs', + inheritAttrs: false, + template: '
', +}) + +const TabStub = defineComponent({ + name: 'Tab', + props: { title: { type: String, required: false, default: '' } }, + template: '
', +}) + +async function mountComponent(props = {}) { + return await mountSuspended(SampleDataModal, { + props: { + sampleData: { subject: 'Hello' }, + title: 'Payload for trigger', + subtitle: 'JSON payload', + ...props, + }, + global: { + stubs: { + Modal: ModalStub, + Button: ButtonStub, + Tabs: TabsStub, + Tab: TabStub, + }, + mocks: { + $t: (key) => key, + }, + }, + }) +} + +describe('SampleDataModal', () => { + test('renders only the JSON payload by default', async () => { + const wrapper = await mountComponent() + + expect(wrapper.find('.tabs-stub').exists()).toBe(false) + expect(wrapper.find('.sample-data-modal__code').text()).toContain( + '"subject": "Hello"' + ) + }) + + test('renders JSON and HTML tabs for the html content type', async () => { + const wrapper = await mountComponent({ + contentType: 'html', + sampleDataHtml: '

An email body

', + }) + + expect(wrapper.find('.tabs-stub').exists()).toBe(true) + const tabTitles = wrapper + .findAll('.tab-stub') + .map((tab) => tab.attributes('data-title')) + expect(tabTitles).toStrictEqual(['JSON', 'HTML']) + expect(wrapper.find('.sample-data-modal__code').text()).toContain( + '"subject": "Hello"' + ) + + const iframe = wrapper.find('iframe.sample-data-modal__html-preview') + expect(iframe.exists()).toBe(true) + // The document is prefixed with a policy that blocks remote loads, so a + // tracking pixel cannot report the preview. + expect(iframe.attributes('srcdoc')).toMatch( + /^
', +}) + +const AlertStub = defineComponent({ + name: 'Alert', + inheritAttrs: false, + template: '
', +}) + +const ButtonStub = defineComponent({ + name: 'Button', + inheritAttrs: false, + template: '', +}) + +const CopiedStub = defineComponent({ + name: 'Copied', + methods: { + show() {}, + }, + template: '
', +}) + +const RadioGroupStub = defineComponent({ + name: 'RadioGroup', + props: ['modelValue', 'options'], + emits: ['update:modelValue'], + template: ` +
+ +
+ `, +}) + +const EMAIL_ADDRESS = `${'a'.repeat(32)}@inbound.baserow.io` +const TEST_EMAIL_ADDRESS = `test-${EMAIL_ADDRESS}` + +async function mountComponent({ defaultValues = {} } = {}) { + return await mountSuspended(CoreInboundEmailTriggerServiceForm, { + props: { + defaultValues, + }, + global: { + stubs: { + FormGroup: FormGroupStub, + Alert: AlertStub, + Button: ButtonStub, + Copied: CopiedStub, + RadioGroup: RadioGroupStub, + }, + mocks: { + // Render the key plus any interpolation params so tests can assert + // on the values passed to translations. + $t: (key, params) => + params ? `${key}(${Object.values(params).join(',')})` : key, + }, + }, + }) +} + +describe('Core email trigger service form', () => { + test('renders the test address by default, like the HTTP trigger', async () => { + const wrapper = await mountComponent({ + defaultValues: { + email_address: EMAIL_ADDRESS, + test_email_address: TEST_EMAIL_ADDRESS, + }, + }) + + expect(wrapper.find('code').text()).toBe(TEST_EMAIL_ADDRESS) + expect(wrapper.find('.alert-stub').exists()).toBe(false) + }) + + test('switches to the published address', async () => { + const wrapper = await mountComponent({ + defaultValues: { + email_address: EMAIL_ADDRESS, + test_email_address: TEST_EMAIL_ADDRESS, + }, + }) + + const [testOption, publishedOption] = wrapper.findAll('.radio-option-stub') + expect(testOption.text()).toBe( + 'inboundEmailTriggerServiceForm.addressVersionTest' + ) + expect(publishedOption.text()).toBe( + 'inboundEmailTriggerServiceForm.addressVersionPublished' + ) + + await publishedOption.trigger('click') + expect(wrapper.find('code').text()).toBe(EMAIL_ADDRESS) + + await testOption.trigger('click') + expect(wrapper.find('code').text()).toBe(TEST_EMAIL_ADDRESS) + }) + + test('shows the size limit and attachment note when the limit is known', async () => { + const wrapper = await mountComponent({ + defaultValues: { + email_address: EMAIL_ADDRESS, + test_email_address: TEST_EMAIL_ADDRESS, + max_message_size_mb: 25, + }, + }) + + expect(wrapper.text()).toContain( + 'inboundEmailTriggerServiceForm.limits(25)' + ) + }) + + test('hides the size limit note when the limit is unknown', async () => { + const wrapper = await mountComponent({ + defaultValues: { + email_address: EMAIL_ADDRESS, + test_email_address: TEST_EMAIL_ADDRESS, + }, + }) + + expect(wrapper.text()).not.toContain( + 'inboundEmailTriggerServiceForm.limits' + ) + }) + + test('shows the not configured alert when there is no email address', async () => { + const wrapper = await mountComponent({ + defaultValues: { email_address: null }, + }) + + expect(wrapper.find('.alert-stub').exists()).toBe(true) + expect(wrapper.text()).toContain( + 'inboundEmailTriggerServiceForm.notConfigured' + ) + expect(wrapper.find('.button-stub').exists()).toBe(false) + }) + + test('regenerate button emits values-changed with the regenerate flag', async () => { + const wrapper = await mountComponent({ + defaultValues: { + email_address: EMAIL_ADDRESS, + test_email_address: TEST_EMAIL_ADDRESS, + }, + }) + + await wrapper.find('.button-stub').trigger('click') + + const emitted = wrapper.emitted('values-changed') + expect(emitted).toHaveLength(1) + expect(emitted[0]).toStrictEqual([{ regenerate_token: true }]) + }) +}) diff --git a/web-frontend/test/unit/integrations/core/inboundEmailTriggerServiceType.spec.js b/web-frontend/test/unit/integrations/core/inboundEmailTriggerServiceType.spec.js new file mode 100644 index 0000000000..b4a90d3f1a --- /dev/null +++ b/web-frontend/test/unit/integrations/core/inboundEmailTriggerServiceType.spec.js @@ -0,0 +1,41 @@ +import { + CoreInboundEmailTriggerServiceType, + CoreSMTPEmailServiceType, +} from '@baserow/modules/integrations/core/serviceTypes' + +const app = { + $i18n: { + t: (key) => key, + }, +} + +describe('CoreInboundEmailTriggerServiceType sample data', () => { + test('returns the html sample data content type', () => { + const serviceType = new CoreInboundEmailTriggerServiceType({ app }) + + expect(serviceType.getSampleDataContentType({})).toBe('html') + }) + + test('extracts the html body from the sample data envelope', () => { + const serviceType = new CoreInboundEmailTriggerServiceType({ app }) + + expect( + serviceType.getSampleDataHtml({ + sample_data: { data: { body_html: '

Hi

' } }, + }) + ).toBe('

Hi

') + expect(serviceType.getSampleDataHtml({ sample_data: null })).toBe(null) + expect( + serviceType.getSampleDataHtml({ + sample_data: { data: { body_html: '' } }, + }) + ).toBe(null) + }) + + test('other service types default to the json content type', () => { + const serviceType = new CoreSMTPEmailServiceType({ app }) + + expect(serviceType.getSampleDataContentType({})).toBe('json') + expect(serviceType.getSampleDataHtml({})).toBe(null) + }) +})