penpot/backend/test/backend_tests/config_test.clj
Andrey Antukh a7f66b18f9
✨ Honor trusted alternate origins for backend links and OIDC (#11892)
* ✨ Honor trusted alternate origins for backend links and OIDC

Add PENPOT_TRUSTED_ORIGINS, an optional list of bare scheme://host[:port]
alternate origins. A request whose Origin matches (exact, trimmed and
lowercased) uses that origin as the base for links generated while serving
it: emails, asset URLs, audit and webhook link fields, and redirects.
Unlisted origins, requests without Origin, and background or server-to-server
work keep the canonical public-uri (fail-closed). Malformed entries warn at
startup and never match.

Stamp the trusted origin on the request with a global http middleware that
binds config public-uri for the request extent; expose the chain as
root-middleware so tests assert it runs before auth and errors. Build every
backend link through the canonical cf/get-public-uri.

Carry the origin in the signed OIDC state (auth and organization SSO) so the
callback, a navigation without Origin, re-applies it with with-public-uri for
the token-exchange redirect_uri and every redirect, including logout. Verify
the state token once per callback and reuse the claims; build redirect URIs
with ensure-path-slash plus join and append-query-param for hash routes. A
removed origin does not invalidate states signed before it (up to four hours).

Bring MCP OAuth into scope: wrap its routes, stage the origin in the Redis
request record at authorize time, and re-apply it in decision so issuer,
resource, the approval redirect and the code-exchange iss agree on one base.

Keep the log-capture watch installed while waiting for the async rejection
record in the save tests; a watch removed first lost late records and read
nil. Add a delayed-executor regression test that makes the race deterministic
and document the rule in the backend testing memory.

Closes #11625

AI-assisted-by: deepseek-v4.1-flash
AI-assisted-by: qwen3.7-plus
AI-assisted-by: gpt-5.6-luna
AI-assisted-by: muse-spark-1.3-contributor

* ✨ Serve trusted alternate origins across frontend and backend

Let one installation serve a canonical domain plus trusted alternate
origins, without letting request headers pick arbitrary link bases.

The backend normalizes `PENPOT_TRUSTED_ORIGINS` on load: it drops malformed
entries with a warning and warns about HTTP origins outside localhost. It
selects the first trusted origin from `X-Penpot-Origin`, then `Origin`, and
applies only scheme, host and port to the public URI, keeping the configured
path. MCP OAuth keeps the canonical base because its authorize navigation
has no usable origin.

The frontend reads the same list from `config.js`, filled by the container
entrypoint, and selects the browser origin only on an exact match. It sends
`X-Penpot-Origin` on RPC calls (including GETs and multipart) and OIDC
initiation, not on asset, font or external requests. SSE captures the request
bindings, and export jobs store the effective base so the download link uses
it after the request ends. A closed export creation schema excludes
`:public-uri`, which the backend adds only after validation.

Register the OIDC callback for each alias. Removing an alias does not stop
already signed OIDC state, queued mail or export jobs from using it.

Add regression tests across backend, frontend and the nginx entrypoint, and
document the proxy setup, worker upgrade and rollback, and alias retirement.

Refs #11625

AI-assisted-by: hy4-flash-free
AI-assisted-by: gpt-6-luna
AI-assisted-by: gpt-6.2-sol
2026-11-24 20:02:29 +01:00

230 lines
12 KiB
Clojure

;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) KALEIDOS SUBSIDIARY SL
(ns backend-tests.config-test
(:require
[app.common.logging :as l]
[app.common.schema :as sm]
[app.common.time :as ct]
[app.common.uri :as u]
[app.config :as cf]
[clojure.core :as c]
[clojure.test :as t]))
(t/deftest tenant-is-normalized-to-lowercase
(t/testing "an uppercase tenant names the same tenant"
(t/is (= "acme" (:tenant (#'cf/normalize-tenant {:tenant "ACME"}))))
(t/is (= "acme" (:tenant (#'cf/normalize-tenant {:tenant "acme"})))))
(t/testing "a config without a tenant is left untouched"
(t/is (= {:x 1} (#'cf/normalize-tenant {:x 1}))))
(t/testing "the validated form is lowercase-only"
(t/is (not (sm/validate cf/schema:tenant "ACME")))
(t/is (sm/validate cf/schema:tenant "acme"))))
(t/deftest get-public-uri-normalizes-base
(t/testing "trailing slash is ensured with and without subpath"
(doseq [[base expected] [["http://localhost:3449" "http://localhost:3449/"]
["http://localhost:3449/" "http://localhost:3449/"]
["https://example.com/penpot" "https://example.com/penpot/"]
["https://example.com/penpot/" "https://example.com/penpot/"]]]
(t/testing (str "base " base)
(with-redefs [cf/config (assoc cf/config :public-uri base)]
(t/is (= expected (cf/get-public-uri))))))))
(t/deftest get-public-uri-preserves-subpath
(t/testing "joined segments keep the subpath"
(with-redefs [cf/config (assoc cf/config :public-uri "https://example.com/penpot")]
(t/is (= "https://example.com/penpot/assets/by-id/123"
(cf/get-public-uri "assets/by-id/123")))
(t/is (= "https://example.com/penpot/api/main/doc"
(cf/get-public-uri "api/main/doc"))))))
(t/deftest join-uri-joins-arbitrary-base
(t/testing "segments join onto any base with trailing slash normalization"
(t/is (= "https://nitrate.example.com/api/teams/123"
(cf/join-uri "https://nitrate.example.com" "api/teams/123")))
(t/is (= "https://nitrate.example.com/api/teams/123"
(cf/join-uri "https://nitrate.example.com/" "api/teams/123")))))
(t/deftest join-uri-rejects-leading-slash
(t/testing "a leading slash would drop the subpath, so it fails fast"
(t/is (thrown? AssertionError
(cf/join-uri "https://example.com/penpot" "/assets/by-id/123")))))
(t/deftest tenant-allows-only-alphanumeric
(t/testing "default and plain alphanumeric tenants validate"
(doseq [tenant ["default" "acme42" "my-company"]]
(t/is (cf/validate-config (assoc cf/config :tenant tenant)))))
(t/testing "LIKE wildcards and separators are rejected"
(doseq [tenant ["my_tenant" "a%b" "a:b" "a b" "" "acme.example.com"]]
(t/is (not (cf/validate-config (assoc cf/config :tenant tenant)))))))
(t/deftest worker-parallelism-keys
(t/testing "schema decodes all runner parallelism keys (env strings to int)"
(let [decoded (cf/decode-config {:worker-default-parallelism "4"
:worker-webhook-parallelism "2"
:worker-cron-parallelism "3"
:worker-binfile-parallelism "5"})]
(t/is (= 4 (:worker-default-parallelism decoded)))
(t/is (= 2 (:worker-webhook-parallelism decoded)))
(t/is (= 3 (:worker-cron-parallelism decoded)))
(t/is (= 5 (:worker-binfile-parallelism decoded)))))
(t/testing "lookups resolve configured values (unnamespaced keys, as main uses)"
(with-redefs [cf/config (assoc cf/config
:worker-default-parallelism 4)]
(t/is (= 4 (cf/get :worker-default-parallelism 1))))))
(t/deftest prepared-statement-cache-keys
(t/testing "negative sizes are rejected; the threshold takes -1 or non-negatives"
(t/is (not (cf/validate-config (assoc cf/config :database-prepared-statement-cache-queries -1))))
(t/is (not (cf/validate-config (assoc cf/config :database-prepared-statement-cache-size -1))))
(t/is (not (cf/validate-config (assoc cf/config :database-prepared-statement-cache-threshold -2))))
(t/is (cf/validate-config (assoc cf/config :database-prepared-statement-cache-threshold -1))))
(t/testing "a -1 threshold survives the environment decoding and validation"
(let [cfg (merge cf/config
(cf/decode-config {:database-prepared-statement-cache-threshold "-1"}))]
(t/is (= -1 (:database-prepared-statement-cache-threshold cfg)))
(t/is (cf/validate-config cfg))))
(t/testing "a decoded -2 threshold fails validation"
(let [cfg (merge cf/config
(cf/decode-config {:database-prepared-statement-cache-threshold "-2"}))]
(t/is (= -2 (:database-prepared-statement-cache-threshold cfg)))
(t/is (not (cf/validate-config cfg))))))
(t/deftest jobs-user-ttl
(t/testing "the env value is decoded as a duration"
(let [decoded (cf/decode-config {:jobs-user-ttl "72h"})]
(t/is (= (ct/duration {:days 3}) (:jobs-user-ttl decoded)))))
(t/testing "the getter resolves the configured value"
(with-redefs [cf/config (assoc cf/config :jobs-user-ttl (ct/duration {:days 1}))]
(t/is (= (ct/duration {:days 1}) (cf/get-jobs-user-ttl)))))
(t/testing "and falls back to a week"
(with-redefs [cf/config (dissoc cf/config :jobs-user-ttl)]
(t/is (= (ct/duration {:days 7}) (cf/get-jobs-user-ttl))))))
;; `legacy-db` is read-only: the file data moved to `file_data`, and
;; `file.data` / `file_change.data` are read-only leftovers. An instance
;; that keeps it starts healthy and then fails on every save. It is read
;; as `db` instead, which also serves the legacy rows.
(defn- read-config
"`read-config` with the environment replaced by `env`."
[env & {:keys [default] :or {default {}}}]
(with-redefs [cf/read-env (constantly env)]
(cf/read-config :default default)))
(defn- read-config-with-warning
"Reads the configuration and collects the warnings it emits. Logging is
emitted asynchronously, so the record is awaited (bounded)."
[env]
(let [records (atom [])]
(add-watch l/log-record ::capture
(fn [_ _ _ record] (swap! records conj record)))
(try
(let [config (read-config env)]
[(loop [remaining 100]
(let [warns (filter #(= :warn (::l/level %)) @records)]
(cond
(seq warns) warns
(zero? remaining) warns
:else (do (Thread/sleep 10) (recur (dec remaining))))))
config])
(finally
(remove-watch l/log-record ::capture)))))
(t/deftest read-config-replaces-the-read-only-legacy-db
(let [[warns config] (read-config-with-warning {:file-data-backend "legacy-db"})]
(t/testing "the configuration writes through db"
(t/is (= "db" (c/get config :file-data-backend))))
(t/testing "the operator is warned"
(t/is (contains? (into #{} (map #(c/get (::l/props %) :hint)) warns)
"file-data-backend=legacy-db is read-only, using db")))))
(t/deftest read-config-keeps-the-writable-back-ends
(doseq [backend ["db" "storage"]]
(t/testing backend
(t/is (= backend (c/get (read-config {:file-data-backend backend})
:file-data-backend))))))
(t/deftest read-config-takes-the-default-back-end
(t/is (= "db" (c/get (read-config {} :default cf/default)
:file-data-backend))))
(t/deftest audit-persistence-follows-consumer-flags
(t/testing "a consumer flag enables persistence"
(t/is (cf/persist-audit-events? #{:nexus}))
(t/is (cf/persist-audit-events? #{:admin-console})))
(t/testing "other sinks alone do not enable persistence"
(doseq [flags [#{} #{:webhooks} #{:telemetry} #{:error-reporting}
#{:audit-log-logger}]]
(t/is (not (cf/persist-audit-events? flags)) (str flags))))
(t/testing "the boot value is derived from the loaded flags"
(t/is (= (cf/persist-audit-events? cf/flags) cf/audit-persist?)))
(t/testing "a stale enable-audit-log in the environment is dropped"
(let [flags (#'cf/parse-flags {:flags #{"enable-audit-log" "enable-nexus"}})]
(t/is (not (contains? flags :audit-log)))
(t/is (contains? flags :nexus))
(t/is (cf/persist-audit-events? flags)))))
(t/deftest trusted-origins-decodes-from-env-string
(t/testing "comma and whitespace separated origins become a set"
(let [config (cf/decode-config {:tenant "default"
:host "localhost"
:public-uri "http://localhost:3449"
:trusted-origins "https://a.example.com, https://b.example.com https://c.example.com"})]
(t/is (= #{"https://a.example.com" "https://b.example.com" "https://c.example.com"}
(:trusted-origins config))))))
(t/deftest get-trusted-origin-checks-normalized-allowlist
(with-redefs [cf/config (assoc cf/config :trusted-origins #{"https://alt.example.com"})]
(t/testing "exact and normalized matches"
(t/is (= "https://alt.example.com" (cf/get-trusted-origin "https://alt.example.com")))
(t/is (= "https://alt.example.com" (cf/get-trusted-origin " HTTPS://Alt.Example.com "))))
(t/testing "nil, blank, unlisted, subdomain and path variants are rejected"
(t/is (nil? (cf/get-trusted-origin nil)))
(t/is (nil? (cf/get-trusted-origin "")))
(t/is (nil? (cf/get-trusted-origin "https://other.example.com")))
(t/is (nil? (cf/get-trusted-origin "https://sub.alt.example.com")))
(t/is (nil? (cf/get-trusted-origin "https://alt.example.com/penpot"))))))
(t/deftest read-config-prepares-trusted-origins
(let [config (read-config
{:trusted-origins
(str "null https://alt.example.com/penpot HTTPS://Alt.Example.com:443 "
"https://alt.example.com https://alt.example.com:8443 "
"http://localhost:80 http://internal.example.com:80 "
"https://*.example.com https://user@example.com "
"https://example.com:65536 https://example.com: ftp://example.com")})]
(t/is (= #{"https://alt.example.com" "https://alt.example.com:8443"
"http://localhost" "http://internal.example.com"}
(:trusted-origins config)))
(binding [cf/config config]
(t/is (= "https://alt.example.com" (cf/get-trusted-origin "HTTPS://alt.example.com:443")))
(t/is (= "http://internal.example.com" (cf/get-trusted-origin "http://internal.example.com:80")))
(t/is (nil? (cf/get-trusted-origin "https://alt.example.com:9443"))))))
(t/deftest get-trusted-origin-without-configuration
(with-redefs [cf/config (assoc cf/config :trusted-origins nil)]
(t/is (nil? (cf/get-trusted-origin "https://alt.example.com")))))
(t/deftest with-public-uri-overrides-base
(let [config {:public-uri "http://localhost:3449" :host "localhost"}
overridden (cf/with-public-uri "https://alt.example.com" config)]
(t/testing "the base keeps the URI type used by the configuration"
(t/is (u/uri? (:public-uri overridden)))
(t/is (= "alt.example.com" (:host (:public-uri overridden)))))
(t/testing "a nil base leaves the config unchanged"
(t/is (= config (cf/with-public-uri nil config))))))
(t/deftest get-trusted-origin-checks-bare-origin-shape
(binding [cf/config (read-config {:trusted-origins "https://alt.example.com https://[::1]:3449"})]
(t/is (= "https://[::1]:3449" (cf/get-trusted-origin "https://[::1]:3449")))
(doseq [origin ["alt.example.com" "localhost:3449" "https://alt.example.com/"
"https://alt.example.com?x=1" "https://alt.example.com#frag"]]
(t/is (nil? (cf/get-trusted-origin origin)) origin))))