diff --git a/.serena/memories/backend/subtleties.md b/.serena/memories/backend/subtleties.md index cc644a9562..f16b2518b9 100644 --- a/.serena/memories/backend/subtleties.md +++ b/.serena/memories/backend/subtleties.md @@ -60,6 +60,7 @@ - Response formatting negotiates with `Accept` or `_fmt=json`. Transit is the default for collection/boolean bodies; JSON encoding has special pointer-map handling. - Auth prefers the session cookie token before the `Authorization` header. Headers may be `Token` or `Bearer`. Only `kid=1`/`ver=1` tokens are decoded as session tokens; anything else is left unauthenticated (legacy v1 tokens were removed). - Shared-key auth requires `x-shared-key` as ` ` and stores the lowercased key id on the request. If no shared keys are configured it always rejects. Management methods declare the key ids they accept with `::rpc/allowed-shared-keys`; a valid key outside that set answers 403 `:shared-key-not-allowed`, and a method without the metadata accepts any configured key. +- Secret configuration: `PENPOT_SECRET_KEY` is mandatory and never persisted or autogenerated; `app.setup/require-secret-key` raises `:missing-secret-key` at `ig/init-key ::props` when it is absent or blank, so every other service must receive its own key or file when the master is not shared. `PENPOT_SECRET_KEY` and the four `PENPOT__SHARED_KEY` variables accept `*_FILE` variants resolved in `app.config` before decoding; precedence is direct env > `*_FILE` > derivation from the master. A blank service key means disabled; a blank master means missing. Key files must be regular files of at most 4096 bytes; contents have the fixed Unicode White_Space set plus U+FEFF removed everywhere, matching exporter and media-processor. Missing or empty files raise `:invalid-key-file` naming the environment variable, and read failures are logged with their cause. This file-only normalization can change existing secrets; external consumers must use matching keys without whitespace. `:tokens-key` derives from the master; the four shared keys do not have to. - Session management uses DB storage unless the DB pool is read-only, then falls back to the in-memory manager. Sessions use only the v2 UUID model (`http_session_v2`); legacy string ids were removed. - Session cookies are renewed when `modified-at` is older than the 6h renewal interval. SameSite is `none` for CORS, otherwise strict/lax based on config. Session lifetime config and GC: `mem:backend/session-expiration`. diff --git a/.serena/memories/exporter/core.md b/.serena/memories/exporter/core.md index f48948d8d6..9731efb51f 100644 --- a/.serena/memories/exporter/core.md +++ b/.serena/memories/exporter/core.md @@ -15,7 +15,7 @@ - POST body limit is about 60 MB. Exporter supports `application/transit+json`; request params merge query params and body params. - Map response bodies are Transit JSON and force HTTP 200; nil 200 bodies become 204. -- Auth token comes from cookie `auth-token`, then uploads use Bearer auth plus the management shared key. +- Auth token comes from cookie `auth-token`, then uploads use Bearer auth plus the management shared key. The key source is `PENPOT_EXPORTER_SHARED_KEY` > `PENPOT_EXPORTER_SHARED_KEY_FILE` > HKDF derivation from `PENPOT_SECRET_KEY` or, if absent, `PENPOT_SECRET_KEY_FILE`. A present blank explicit service key disables the key and fails startup without falling back; a present blank master also takes precedence over its file. The master file is read only when deriving; an empty selected path fails and an independent service key needs no master. Key files must be regular files at most 4096 bytes; their contents have the fixed Unicode White_Space set plus U+FEFF removed everywhere, matching backend and media-processor. `prepare-config` accepts an env map for tests, and the four call sites send the same `exporter ` header. - Each export job gets a fresh Playwright browser context. On success, the context closes and the browser returns to the pool; on error, the browser is destroyed instead of reused. - Borrow validates browser connection. Pool acquire timeout is about 10s; font loading timeout logs a warning and continues after about 15s. diff --git a/.serena/memories/media-processor/core.md b/.serena/memories/media-processor/core.md index 209d4b1a37..a497bb8f85 100644 --- a/.serena/memories/media-processor/core.md +++ b/.serena/memories/media-processor/core.md @@ -50,7 +50,7 @@ media-processor/ ### Auth - Requests authenticated via `x-shared-key` header using timing-safe comparison - When no key configured, all requests rejected with 403 -- Key derived from `PENPOT_SECRET_KEY` via HKDF (blake2b512) or set directly via `PENPOT_MEDIA_PROCESSOR_SHARED_KEY` +- Key source precedence: `PENPOT_MEDIA_PROCESSOR_SHARED_KEY` > `PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE` > HKDF derivation from `PENPOT_SECRET_KEY` or, if absent, `PENPOT_SECRET_KEY_FILE` (blake2b512). A blank explicit key is disabled, not a fall-through to another source; a present blank master takes precedence over its file. The master file is read only for derivation, and an empty selected path fails. Key files must be regular files at most 4096 bytes; contents have the fixed Unicode White_Space set plus U+FEFF removed everywhere, matching backend and exporter, and missing or empty files fail at boot while read causes go to stderr. With no source `sharedKey` is null and every protected request is rejected. ### Resource Limits - Image: max pixels, max width/height enforced before processing diff --git a/backend/src/app/config.clj b/backend/src/app/config.clj index 57bbf5d22c..e207beae2b 100644 --- a/backend/src/app/config.clj +++ b/backend/src/app/config.clj @@ -147,6 +147,7 @@ [:flags {:optional true} [::sm/set :string]] [:admins {:optional true} [::sm/set ::sm/email]] [:secret-key {:optional true} :string] + [:secret-key-file {:optional true} :string] [:tenant {:optional false} schema:tenant] [:is-saas ::sm/boolean] @@ -168,6 +169,10 @@ [:admin-console-shared-key {:optional true} :string] [:nexus-shared-key {:optional true} :string] [:media-processor-shared-key {:optional true} :string] + [:exporter-shared-key-file {:optional true} :string] + [:admin-console-shared-key-file {:optional true} :string] + [:nexus-shared-key-file {:optional true} :string] + [:media-processor-shared-key-file {:optional true} :string] [:management-api-key {:optional true} :string] [:telemetry-uri {:optional true} :string] @@ -442,12 +447,66 @@ (assoc config :file-data-backend "db")) config)) +(def ^:private key-file->key + {:secret-key-file :secret-key + :exporter-shared-key-file :exporter-shared-key + :admin-console-shared-key-file :admin-console-shared-key + :nexus-shared-key-file :nexus-shared-key + :media-processor-shared-key-file :media-processor-shared-key}) + +(def ^:private max-key-file-size 4096) + +(defn- raise-key-file-error + [variable path hint] + (ex/raise :type :validation + :code :invalid-key-file + :hint hint + :variable variable + :path path)) + +(defn- get-key-file-value + "Reads a secret from a regular file of at most `max-key-file-size` bytes. + Unicode White_Space and BOM are removed so a wrapped base64 value works. + An empty value is an error: it would silently disable the credential." + [variable path] + (let [file (io/file path)] + (when-not (.isFile file) + (raise-key-file-error variable path "configuration key file is missing or not a regular file")) + (when (> (.length file) max-key-file-size) + (raise-key-file-error variable path "configuration key file is too large")) + (let [value (try + (str/replace (slurp file) + #"[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]+" "") + (catch Exception cause + (l/warn :hint "unable to read configuration key file" + :variable variable + :path path + :cause cause) + nil))] + (when (empty? value) + (raise-key-file-error variable path "configuration key file is missing or empty")) + value))) + +(defn- resolve-key-files + [config prefix] + (reduce-kv + (fn [result file-key key] + (if-let [path (c/get config file-key)] + (if (contains? result key) + result + (let [variable (str/upper (str/snake (str prefix "_" (name file-key))))] + (assoc result key (get-key-file-value variable path)))) + result)) + config + key-file->key)) + (defn read-config "Reads the configuration from environment variables and decodes all known values." [& {:keys [prefix default] :or {prefix "penpot"}}] (->> (read-env prefix) (merge default) + (#(resolve-key-files % prefix)) (normalize-tenant) (decode-config) (normalize-file-data-backend))) diff --git a/backend/src/app/setup.clj b/backend/src/app/setup.clj index 2afb5955b4..12eb395508 100644 --- a/backend/src/app/setup.clj +++ b/backend/src/app/setup.clj @@ -8,6 +8,7 @@ "Initial data setup of instance." (:require [app.common.data :as d] + [app.common.exceptions :as ex] [app.common.logging :as l] [app.common.schema :as sm] [app.common.uuid :as uuid] @@ -18,15 +19,9 @@ [app.setup.keys :as keys] [app.setup.templates] [buddy.core.codecs :as bc] - [buddy.core.nonce :as bn] [cuerdas.core :as str] [integrant.core :as ig])) -(defn- generate-random-key - [] - (-> (bn/random-bytes 64) - (bc/bytes->b64-str true))) - (defn- get-all-props [conn] (->> (db/query conn :server-prop {:preload true}) @@ -72,12 +67,22 @@ (db/run! system (fn [{:keys [::db/conn]}] (db/exec-one! conn [sql:add-prop prop value false value false]))))) +(defn- require-secret-key + [key] + (when (or (nil? key) (str/blank? key)) + (ex/raise :type :validation + :code :missing-secret-key + :hint "PENPOT_SECRET_KEY or PENPOT_SECRET_KEY_FILE is required")) + key) + (defmethod ig/assert-key ::props [_ params] (assert (db/pool? (::db/pool params)) "expected valid database pool")) (defmethod ig/init-key ::props [_ {:keys [::key] :as cfg}] + (require-secret-key key) + (audit/submit cfg {:type "trigger" :name "instance-start" :props {:version (:full cf/version) @@ -86,17 +91,10 @@ (db/tx-run! cfg (fn [{:keys [::db/conn]}] (db/xact-lock! conn 0) - (when-not key - (l/wrn :hint (str "using autogenerated secret-key, it will change " - "on each restart and will invalidate " - "all sessions on each restart, it is highly " - "recommended setting up the " - "PENPOT_SECRET_KEY environment variable"))) - (let [secret (or key (generate-random-key))] - (-> (get-all-props conn) - (assoc :secret-key secret) - (assoc :tokens-key (keys/derive secret :salt "tokens")) - (update :instance-id handle-instance-id conn)))))) + (-> (get-all-props conn) + (assoc :secret-key key) + (assoc :tokens-key (keys/derive key :salt "tokens")) + (update :instance-id handle-instance-id conn))))) (defmethod ig/init-key ::shared-keys [_ {:keys [::props] :as cfg}] diff --git a/backend/test/backend_tests/config_test.clj b/backend/test/backend_tests/config_test.clj index 3e6181fb4a..0f379f1acd 100644 --- a/backend/test/backend_tests/config_test.clj +++ b/backend/test/backend_tests/config_test.clj @@ -10,6 +10,8 @@ [app.common.schema :as sm] [app.common.time :as ct] [app.config :as cf] + [app.setup.keys :as keys] + [buddy.core.codecs :as bc] [clojure.core :as c] [clojure.test :as t])) @@ -186,3 +188,147 @@ (t/is (not (contains? flags :audit-log))) (t/is (contains? flags :nexus)) (t/is (cf/persist-audit-events? flags))))) + +;; Key files are the delivery channel for the per-service shared keys written +;; by an external generator. A direct environment value still wins. + +(defn- with-key-file + [content f] + (let [file (java.io.File/createTempFile "penpot-key" ".txt")] + (spit file content) + (try + (f (.getAbsolutePath file)) + (finally (.delete file))))) + +(defn- with-temp-dir + [f] + (let [dir (java.nio.file.Files/createTempDirectory + "penpot-key" + (into-array java.nio.file.attribute.FileAttribute []))] + (try + (f (str dir)) + (finally (java.nio.file.Files/deleteIfExists dir))))) + +(defn- key-file-error + [config] + (try + (read-config config) + nil + (catch Exception e e))) + +(t/deftest read-config-reads-key-files + (with-key-file "from-file\n" + (fn [path] + (let [cfg (read-config {:secret-key-file path + :exporter-shared-key-file path + :admin-console-shared-key-file path + :nexus-shared-key-file path + :media-processor-shared-key-file path})] + (t/testing "all five key files are read and trimmed" + (t/is (= "from-file" (:secret-key cfg))) + (t/is (= "from-file" (:exporter-shared-key cfg))) + (t/is (= "from-file" (:admin-console-shared-key cfg))) + (t/is (= "from-file" (:nexus-shared-key cfg))) + (t/is (= "from-file" (:media-processor-shared-key cfg)))))))) + +(t/deftest read-config-removes-internal-whitespace + (with-key-file "from-\n file \tkey" + (fn [path] + (t/is (= "from-filekey" (:secret-key (read-config {:secret-key-file path}))))))) + +(def ^:private key-file-whitespace + (concat (range 0x0009 0x000e) [0x0020 0x0085 0x00a0 0x1680] + (range 0x2000 0x200b) [0x2028 0x2029 0x202f 0x205f 0x3000 0xfeff])) + +(t/deftest read-config-normalizes-key-file-whitespace + (doseq [codepoint key-file-whitespace] + (t/testing (format "U+%04X at both edges and inside master and service keys" codepoint) + (let [space (str (char codepoint))] + (with-key-file (str space "mas" space "ter" space) + (fn [path] + (let [cfg (read-config {:secret-key-file path + :exporter-shared-key-file path})] + (t/is (= "master" (:secret-key cfg))) + (t/is (= "master" (:exporter-shared-key cfg)))))))))) + +(t/deftest read-config-rejects-unicode-whitespace-only-key-files + (with-key-file (apply str (map char key-file-whitespace)) + (fn [path] + (doseq [key [:secret-key-file :media-processor-shared-key-file]] + (t/testing (str key) + (t/is (= :invalid-key-file (:code (ex-data (key-file-error {key path})))))))))) + +(t/deftest read-config-preserves-other-key-file-characters + (with-key-file "\u0000é\u200b中\u0000" + (fn [path] + (let [cfg (read-config {:secret-key-file path + :media-processor-shared-key-file path})] + (t/is (= "\u0000é\u200b中\u0000" (:secret-key cfg))) + (t/is (= "\u0000é\u200b中\u0000" (:media-processor-shared-key cfg))))))) + +(t/deftest read-config-does-not-normalize-direct-keys + (let [value "\u00a0mas\u00a0ter\ufeff" + cfg (read-config {:secret-key value :exporter-shared-key value})] + (t/is (= value (:secret-key cfg))) + (t/is (= value (:exporter-shared-key cfg))))) + +(t/deftest read-config-checks-key-file-size-in-bytes-before-normalization + (with-key-file (str "a" (apply str (repeat 2048 "\u00a0"))) + (fn [path] + (t/is (= :invalid-key-file + (:code (ex-data (key-file-error {:secret-key-file path})))))))) + +(t/deftest read-config-derives-keys-from-normalized-master-file + (with-key-file "\ufeffmas\u00a0ter\u0085" + (fn [path] + (let [master (:secret-key (read-config {:secret-key-file path}))] + (t/is (= "GIFntVZnqcaOnDmD-Ii09n8wkajiOfVXI-RTJGyjKxg" + (bc/bytes->b64-str (keys/derive master :salt "exporter") true))) + (t/is (= "xNYzcEWx3FaEOA0hM_-CqfYPHv_bjbDfncqkAE2wJzM" + (bc/bytes->b64-str (keys/derive master :salt "media-processor") true))))))) + +(t/deftest read-config-prefers-direct-env-key-over-file + (with-temp-dir + (fn [dir] + (let [cfg (read-config {:exporter-shared-key "direct" + :exporter-shared-key-file (str dir "/missing")})] + (t/is (= "direct" (:exporter-shared-key cfg))))))) + +(t/deftest read-config-rejects-a-missing-key-file + (with-temp-dir + (fn [dir] + (let [path (str dir "/missing") + err (key-file-error {:secret-key-file path})] + (t/is (some? err)) + (t/is (= "PENPOT_SECRET_KEY_FILE" (:variable (ex-data err)))) + (t/is (= path (:path (ex-data err)))))))) + +(t/deftest read-config-rejects-a-directory-as-key-file + (with-temp-dir + (fn [dir] + (let [err (key-file-error {:secret-key-file dir})] + (t/is (some? err)) + (t/is (= "PENPOT_SECRET_KEY_FILE" (:variable (ex-data err)))))))) + +(t/deftest read-config-rejects-an-empty-key-file + (with-key-file " \n\t" + (fn [path] + (let [err (key-file-error {:nexus-shared-key-file path})] + (t/is (some? err)) + (t/is (= "PENPOT_NEXUS_SHARED_KEY_FILE" (:variable (ex-data err)))))))) + +(t/deftest read-config-rejects-an-oversized-key-file + (with-key-file (apply str (repeat 5000 "a")) + (fn [path] + (let [err (key-file-error {:secret-key-file path})] + (t/is (some? err)) + (t/is (= "PENPOT_SECRET_KEY_FILE" (:variable (ex-data err)))))))) + +(t/deftest read-config-without-key-files-is-unchanged + (let [cfg (read-config {})] + (t/is (nil? (:secret-key cfg))) + (t/is (nil? (:exporter-shared-key cfg))))) + +(t/deftest read-config-keeps-a-blank-direct-key + (let [cfg (read-config {:exporter-shared-key ""})] + (t/is (= "" (:exporter-shared-key cfg))))) diff --git a/backend/test/backend_tests/helpers.clj b/backend/test/backend_tests/helpers.clj index c1397d023c..fe6b1adeff 100644 --- a/backend/test/backend_tests/helpers.clj +++ b/backend/test/backend_tests/helpers.clj @@ -151,6 +151,7 @@ :thumbnail-uri "test" :path (-> "backend_tests/test_files/template.penpot" io/resource fs/path)}] system (-> (merge main/system-config main/worker-config) + (assoc-in [:app.setup/props :app.setup/key] "test-secret-key") (assoc-in [:app.redis/client :app.redis/uri] (:redis-uri config)) (assoc-in [::db/pool ::db/uri] (:database-uri config)) (assoc-in [::db/pool ::db/username] (:database-username config)) diff --git a/backend/test/backend_tests/setup_test.clj b/backend/test/backend_tests/setup_test.clj new file mode 100644 index 0000000000..26b7126d86 --- /dev/null +++ b/backend/test/backend_tests/setup_test.clj @@ -0,0 +1,52 @@ +;; 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.setup-test + (:require + [app.db :as db] + [app.db :as-alias db] + [app.loggers.audit :as audit] + [app.setup :as setup] + [app.setup.keys :as keys] + [backend-tests.helpers :as th] + [clojure.test :as t] + [integrant.core :as ig])) + +(t/use-fixtures :once th/state-init) +(t/use-fixtures :each th/database-reset) + +(t/deftest secret-key-is-required + (t/testing "a missing key is rejected with the environment variable names" + (let [err (try + (#'setup/require-secret-key nil) + nil + (catch Exception e e)) + edata (ex-data err)] + (t/is (some? err)) + (t/is (= :missing-secret-key (:code edata))) + (t/is (= "PENPOT_SECRET_KEY or PENPOT_SECRET_KEY_FILE is required" + (:hint edata))))) + (t/testing "a blank key is rejected" + (let [err (try + (#'setup/require-secret-key " \n\t") + nil + (catch Exception e e))] + (t/is (some? err)))) + (t/testing "a configured key is returned unchanged" + (t/is (= "configured" (#'setup/require-secret-key "configured"))))) + +(t/deftest props-derive-the-token-key-from-the-configured-secret + (with-redefs [audit/submit (constantly nil)] + (let [props (ig/init-key :app.setup/props + {::db/pool th/*pool* + :app.setup/key "configured-secret"})] + (t/testing "the configured secret is used verbatim" + (t/is (= "configured-secret" (:secret-key props)))) + (t/testing "the token key derives from the configured secret" + (t/is (= (vec (keys/derive "configured-secret" :salt "tokens")) + (vec (:tokens-key props))))) + (t/testing "the instance id is initialized" + (t/is (some? (:instance-id props))))))) diff --git a/docs/technical-guide/configuration.md b/docs/technical-guide/configuration.md index 5e9731badd..76c94c4e51 100644 --- a/docs/technical-guide/configuration.md +++ b/docs/technical-guide/configuration.md @@ -676,28 +676,40 @@ run `(app.srepl.main/set-online)`. Drain one instance at a time. ## Backend -This section enumerates the backend only configuration variables. +This section covers backend configuration variables. Some secret key settings also apply to other services, as noted below. ### Secret key -The PENPOT_SECRET_KEY envvar serves a master key from which other keys -for subsystems (eg http sessions, or invitations) are derived. +The backend requires a stable master key in `PENPOT_SECRET_KEY` or `PENPOT_SECRET_KEY_FILE`. It fails to start if the key is missing or blank; it does not generate or persist one. The backend derives keys for subsystems such as sessions and invitations from this master key. Keep the existing key across upgrades and restarts: changing it can invalidate existing sessions, invitations, and other tokens. -If you don't use it, all created sessions and invitations will become invalid on container restart -or service restart. - -To use it, we recommend using a truly randomly generated 512 bits base64 encoded string here. -You can generate one with: +For a new installation, generate a random 512-bit key with: ```bash python3 -c "import secrets; print(secrets.token_urlsafe(64))" ``` -And configure it: -```bash -# Backend -PENPOT_SECRET_KEY: my-super-secure-key -``` +Store the result securely and provide it to the backend through `PENPOT_SECRET_KEY`, or set `PENPOT_SECRET_KEY_FILE` to a path readable by the backend process. If the direct variable is present, it takes priority over the file even when it is empty; an empty master key makes the backend fail to start. + +**Security warning:** The included Docker Compose file sets `PENPOT_SECRET_KEY` to `change-this-insecure-key`. This is a public, insecure value. Replace it with a random secret in every service that must share the master key. For an existing installation, changing this value can invalidate existing tokens. + +#### Service shared keys + +The backend accepts independent shared keys for these services. Each direct variable also has the corresponding `_FILE` variant: + +| Service | Backend direct variable | Backend file variable | +| --- | --- | --- | +| Exporter | `PENPOT_EXPORTER_SHARED_KEY` | `PENPOT_EXPORTER_SHARED_KEY_FILE` | +| Media processor | `PENPOT_MEDIA_PROCESSOR_SHARED_KEY` | `PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE` | +| Admin Console | `PENPOT_ADMIN_CONSOLE_SHARED_KEY` | `PENPOT_ADMIN_CONSOLE_SHARED_KEY_FILE` | +| Nexus | `PENPOT_NEXUS_SHARED_KEY` | `PENPOT_NEXUS_SHARED_KEY_FILE` | + +If a service key is not set, the backend derives it from the master key. An explicit service key must match between the backend and its consumer. Prefer an independent service key over giving a consumer the master key: access to the master exposes all keys derived from it. Check each other service's own configuration for its supported variables; the backend's support does not imply that every consumer supports the same file variables. + +Exporter and media processor accept their respective direct and `_FILE` service variables shown above. When neither is present, they can derive their service key from `PENPOT_SECRET_KEY` or `PENPOT_SECRET_KEY_FILE`. They need access to the master key only when derivation is required. A present direct service variable takes priority over its file and the master, even if empty or whitespace-only. A blank explicit service key disables it on the backend; exporter fails to start with a blank explicit key, while media processor starts without a shared key and rejects protected requests. Media processor also rejects protected requests if no key source is configured. + +For each key, a present direct variable takes priority over its `_FILE` variable, even when blank. When used, key files must be readable regular files of at most 4096 bytes. An empty master file path, a missing or invalid file, or a file whose content becomes empty causes a startup error when that source is selected. A consumer ignores the master file when it has a higher-priority service key or direct master key. File paths must exist and be readable inside each process or container that uses them; configure the backend and consumer separately. + +The backend, exporter, and media processor remove Unicode whitespace and the byte order mark `U+FEFF` from key file contents. This covers `U+0009–U+000D`, `U+0020`, `U+0085`, `U+00A0`, `U+1680`, `U+2000–U+200A`, `U+2028`, `U+2029`, `U+202F`, `U+205F`, and `U+3000`. They apply this rule to file contents, not direct environment variables. For Admin Console and Nexus, configure the same key without whitespace on both sides; do not assume the consumer normalizes files in the same way. ### Session expiration diff --git a/docs/technical-guide/getting-started/docker.md b/docs/technical-guide/getting-started/docker.md index 24b4ba8cb0..49f75575e6 100644 --- a/docs/technical-guide/getting-started/docker.md +++ b/docs/technical-guide/getting-started/docker.md @@ -122,6 +122,14 @@ This will fetch the latest images. When you do docke It is strongly recommended to update the Penpot version in small increments, rather than updating between two distant versions.

+#### Upgrade to 2.20 + +The backend now requires a stable master key and fails to start without one. Keep your existing `PENPOT_SECRET_KEY` when you upgrade. If you do not have a stable key, configure one before upgrading; setting a new key can invalidate existing sessions, invitations, and other tokens. + +Key files now remove the same Unicode whitespace in the backend, exporter, and media processor. If an existing key file contains such characters, the resulting key can change: a master key change can invalidate tokens, and a service key mismatch can break authentication. Before upgrading, review key files, configure the same key without whitespace on both sides of each service connection, and coordinate service restarts. + +The included Docker Compose file sets `PENPOT_SECRET_KEY` to `change-this-insecure-key`, a public and insecure value. Replace it with a random secret in every service that must share the master key. If you already use that value, changing it can invalidate existing tokens. See [Secret key configuration](/technical-guide/configuration/#secret-key) for file-based secrets, service keys, and their precedence. + #### Upgrade to 2.19 The Admin Console is now enabled by default, so the `enable-admin-console` flag is no longer needed and can be removed from `PENPOT_FLAGS`. diff --git a/exporter/src/app/config.cljs b/exporter/src/app/config.cljs index 4f94887ce0..5586ad9e30 100644 --- a/exporter/src/app/config.cljs +++ b/exporter/src/app/config.cljs @@ -9,6 +9,7 @@ (:require ["node:buffer" :as buffer] ["node:crypto" :as crypto] + ["node:fs" :as fs] ["node:os" :as os] ["node:process" :as process] [app.common.data :as d] @@ -41,10 +42,12 @@ (def ^:private schema:config [:map {:title "config"} - [:secret-key :string] + [:secret-key {:optional true} :string] + [:secret-key-file {:optional true} :string] [:public-uri {:optional true} ::sm/uri] [:internal-uri {:optional true} ::sm/uri] [:exporter-shared-key {:optional true} :string] + [:exporter-shared-key-file {:optional true} :string] [:host {:optional true} :string] [:tenant {:optional true} :string] [:flags {:optional true} [::sm/set :keyword]] @@ -90,22 +93,85 @@ {} (js/Object.keys env)))) -(defn- prepare-config - [] - (let [env (read-env "penpot") - env (d/without-nils env) - data (merge defaults env) - data (decode-config data)] +(defn- present? + [value] + (and (string? value) (not (str/blank? value)))) - (when-not (valid-config? data) - (let [explain (explain-config data)] - (println (sm/humanize-explain explain)) - (process/exit -1))) +(defn- has-key-source? + [config] + (or (present? (c/get config :exporter-shared-key)) + (present? (c/get config :secret-key)))) - data)) +(def ^:private max-key-file-size 4096) + +(defn- get-key-file-value + [variable path] + (let [info (try + (fs/statSync path) + (catch :default cause + (l/warn :hint "unable to read configuration key file" + :variable variable + :path path + :cause cause) + nil))] + (when (or (nil? info) (not (.isFile info))) + (l/warn :hint "configuration key file is not a regular file" + :variable variable + :path path) + (throw (js/Error. (str variable " key file is missing or empty: " path)))) + (when (> (.-size info) max-key-file-size) + (throw (js/Error. (str variable " key file is too large: " path)))) + (let [value (try + (some-> (fs/readFileSync path "utf8") + (str/replace #"[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+" "")) + (catch :default cause + (l/warn :hint "unable to read configuration key file" + :variable variable + :path path + :cause cause) + nil))] + (when (or (nil? value) (empty? value)) + (throw (js/Error. (str variable " key file is missing or empty: " path)))) + value))) + +(defn prepare-config + ([] (prepare-config (read-env "penpot"))) + ([env] + (let [env (d/without-nils env) + _ (when (and (contains? env :exporter-shared-key) + (not (present? (c/get env :exporter-shared-key)))) + (throw (js/Error. "Either PENPOT_EXPORTER_SHARED_KEY or PENPOT_SECRET_KEY is required; blank PENPOT_EXPORTER_SHARED_KEY disables the exporter"))) + env (if (and (present? (c/get env :exporter-shared-key-file)) + (not (contains? env :exporter-shared-key))) + (assoc env :exporter-shared-key + (get-key-file-value "PENPOT_EXPORTER_SHARED_KEY_FILE" + (c/get env :exporter-shared-key-file))) + env) + env (if (and (not (contains? env :exporter-shared-key)) + (not (contains? env :secret-key)) + (or (= "" (c/get env :secret-key-file)) + (present? (c/get env :secret-key-file)))) + (assoc env :secret-key + (get-key-file-value "PENPOT_SECRET_KEY_FILE" + (c/get env :secret-key-file))) + env) + data (merge defaults env) + data (decode-config data)] + + (when-not (valid-config? data) + (throw (js/Error. (sm/humanize-explain (explain-config data))))) + + (when-not (has-key-source? data) + (throw (js/Error. "Either PENPOT_EXPORTER_SHARED_KEY or PENPOT_SECRET_KEY is required"))) + + data))) (def config - (prepare-config)) + (try + (prepare-config) + (catch :default e + (println (.-message e)) + (process/exit -1)))) (def version (v/parse "%version%")) @@ -132,11 +198,22 @@ (or (c/get config :exporter-replica-id) (os/hostname))) +(defn get-management-key + [config] + (let [explicit (c/get config :exporter-shared-key) + secret-key (c/get config :secret-key)] + (cond + (present? explicit) explicit + (contains? config :exporter-shared-key) + (throw (js/Error. "Blank PENPOT_EXPORTER_SHARED_KEY disables the exporter")) + (present? secret-key) + (let [derived-key (crypto/hkdfSync "blake2b512" secret-key "exporter" "" 32)] + (-> (.from buffer/Buffer derived-key) + (.toString "base64url"))) + :else + (throw (js/Error. "Either PENPOT_EXPORTER_SHARED_KEY or PENPOT_SECRET_KEY is required"))))) + (def management-key - (let [key (or (c/get config :exporter-shared-key) - (let [secret-key (c/get config :secret-key) - derived-key (crypto/hkdfSync "blake2b512" secret-key, "exporter" "" 32)] - (-> (.from buffer/Buffer derived-key) - (.toString "base64url"))))] + (let [key (get-management-key config)] (l/inf :hint "exporter key initialized" :key (d/obfuscate-string key)) key)) diff --git a/exporter/test/exporter_tests/config_test.cljs b/exporter/test/exporter_tests/config_test.cljs new file mode 100644 index 0000000000..daf21d80c2 --- /dev/null +++ b/exporter/test/exporter_tests/config_test.cljs @@ -0,0 +1,214 @@ +;; 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 exporter-tests.config-test + (:require + ["node:fs" :as fs] + ["node:os" :as os] + ["node:path" :as path] + [app.config :as cf] + [cljs.test :as t :include-macros true] + [clojure.string :as str])) + +(defn- with-temp-dir + [f] + (let [dir (fs/mkdtempSync (path/join (os/tmpdir) "penpot-exporter-key-"))] + (try + (f dir) + (finally (fs/rmSync dir #js {:recursive true :force true}))))) + +(defn- write-key! + [dir content] + (let [file (path/join dir "key")] + (fs/writeFileSync file content) + file)) + +(defn- error-of + [f] + (try + (f) + nil + (catch :default e e))) + +(defn- message + [err] + (.-message err)) + +(t/deftest explicit-shared-key-without-master-is-valid + (let [cfg (cf/prepare-config {:exporter-shared-key "explicit"})] + (t/is (= "explicit" (:exporter-shared-key cfg))) + (t/is (nil? (:secret-key cfg))) + (t/is (= "explicit" (cf/get-management-key cfg))))) + +(t/deftest key-file-is-read-trimmed-and-unwrapped + (with-temp-dir + (fn [dir] + (let [file (write-key! dir "from-\n file \tkey") + cfg (cf/prepare-config {:exporter-shared-key-file file})] + (t/is (= "from-filekey" (:exporter-shared-key cfg))) + (t/is (= "from-filekey" (cf/get-management-key cfg))))))) + +(t/deftest key-file-beats-derivation + (with-temp-dir + (fn [dir] + (let [file (write-key! dir "from-file") + cfg (cf/prepare-config {:secret-key "master" + :exporter-shared-key-file file})] + (t/is (= "from-file" (:exporter-shared-key cfg))))))) + +(t/deftest direct-env-key-wins-over-file + (with-temp-dir + (fn [dir] + (let [cfg (cf/prepare-config {:exporter-shared-key "direct" + :exporter-shared-key-file + (path/join dir "missing")})] + (t/is (= "direct" (:exporter-shared-key cfg))))))) + +(t/deftest missing-key-file-names-the-variable + (with-temp-dir + (fn [dir] + (let [err (error-of #(cf/prepare-config {:exporter-shared-key-file + (path/join dir "missing")}))] + (t/is (some? err)) + (t/is (str/includes? (message err) "PENPOT_EXPORTER_SHARED_KEY_FILE")) + (t/is (str/includes? (message err) "missing or empty")))))) + +(t/deftest empty-key-file-is-rejected + (with-temp-dir + (fn [dir] + (let [err (error-of #(cf/prepare-config {:exporter-shared-key-file + (write-key! dir " \n\t")}))] + (t/is (some? err)) + (t/is (str/includes? (message err) "PENPOT_EXPORTER_SHARED_KEY_FILE")) + (t/is (str/includes? (message err) "missing or empty")))))) + +(t/deftest directory-as-key-file-is-rejected + (with-temp-dir + (fn [dir] + (let [err (error-of #(cf/prepare-config {:exporter-shared-key-file dir}))] + (t/is (some? err)) + (t/is (str/includes? (message err) "missing or empty")))))) + +(t/deftest oversized-key-file-is-rejected + (with-temp-dir + (fn [dir] + (let [err (error-of #(cf/prepare-config {:exporter-shared-key-file + (write-key! dir (apply str (repeat 5000 "a")))}))] + (t/is (some? err)) + (t/is (str/includes? (message err) "too large")))))) + +(t/deftest blank-explicit-key-disables-the-exporter + (let [err (error-of #(cf/prepare-config {:exporter-shared-key ""}))] + (t/is (some? err)) + (t/is (str/includes? (message err) "Either PENPOT_EXPORTER_SHARED_KEY")))) + +(t/deftest get-management-key-without-a-source-is-rejected + (let [err (error-of #(cf/get-management-key {}))] + (t/is (some? err)) + (t/is (str/includes? (message err) "PENPOT_SECRET_KEY")))) + +(t/deftest blank-explicit-key-never-falls-back + (with-temp-dir + (fn [dir] + (let [file (write-key! dir "file-key") + missing (path/join dir "missing")] + (doseq [key ["" " \t"] + env [{:secret-key "master"} + {:exporter-shared-key-file file} + {:secret-key "master" :exporter-shared-key-file file} + {:secret-key "master" :exporter-shared-key-file missing}]] + (let [err (error-of #(cf/prepare-config (assoc env :exporter-shared-key key)))] + (t/is (some? err)) + (when err + (t/is (str/includes? (message err) "PENPOT_EXPORTER_SHARED_KEY"))))) + (t/is (some? (error-of #(cf/get-management-key {:exporter-shared-key "" + :secret-key "master"})))))))) + +(t/deftest master-key-file-derives-exporter-key + (with-temp-dir + (fn [dir] + (let [cfg (cf/prepare-config {:secret-key-file (write-key! dir " mas\n ter \t")})] + (t/is (= "master" (:secret-key cfg))) + ;; app.setup.keys/derive with secret "master" and salt "exporter". + (t/is (= "GIFntVZnqcaOnDmD-Ii09n8wkajiOfVXI-RTJGyjKxg" + (cf/get-management-key cfg))))))) + +(t/deftest master-key-file-precedence + (with-temp-dir + (fn [dir] + (let [missing (path/join dir "missing") + file (write-key! dir "service-key")] + (t/is (= "direct" (:exporter-shared-key + (cf/prepare-config {:exporter-shared-key "direct" + :secret-key-file missing})))) + (t/is (= "service-key" (:exporter-shared-key + (cf/prepare-config {:exporter-shared-key-file file + :secret-key-file missing})))) + (t/is (= "master" (:secret-key + (cf/prepare-config {:secret-key "master" :secret-key-file missing})))) + (t/is (some? (error-of #(cf/prepare-config {:secret-key "" :secret-key-file file})))))))) + +(t/deftest invalid-master-key-files + (with-temp-dir + (fn [dir] + (let [missing (path/join dir "missing")] + (doseq [file [missing dir (write-key! dir " \n\t")]] + (let [err (error-of #(cf/prepare-config {:secret-key-file file}))] + (t/is (some? err)) + (when err + (t/is (str/includes? (message err) "PENPOT_SECRET_KEY_FILE"))))) + (let [file (write-key! dir (apply str (repeat 4096 "a")))] + (t/is (= 4096 (count (:secret-key (cf/prepare-config {:secret-key-file file})))))) + (let [file (write-key! dir (apply str (repeat 4097 "a"))) + err (error-of #(cf/prepare-config {:secret-key-file file}))] + (t/is (some? err)) + (when err + (t/is (str/includes? (message err) "PENPOT_SECRET_KEY_FILE")) + (t/is (str/includes? (message err) "too large")))))))) + +(t/deftest empty-master-file-path-is-rejected-only-when-selected + (with-temp-dir + (fn [dir] + (let [err (error-of #(cf/prepare-config {:secret-key-file ""})) + file (write-key! dir "service")] + (t/is (and err (str/includes? (message err) "PENPOT_SECRET_KEY_FILE"))) + (t/is (= "direct" (:exporter-shared-key + (cf/prepare-config {:exporter-shared-key "direct" :secret-key-file ""})))) + (t/is (= "service" (:exporter-shared-key + (cf/prepare-config {:exporter-shared-key-file file :secret-key-file ""})))) + (t/is (= "master" (:secret-key + (cf/prepare-config {:secret-key "master" :secret-key-file ""})))) + (doseq [env [{:secret-key "" :secret-key-file ""} + {:exporter-shared-key "" :secret-key-file ""} + {}]] + (let [err (error-of #(cf/prepare-config env))] + (t/is (and err (not (str/includes? (message err) "PENPOT_SECRET_KEY_FILE")))))))))) + +(t/deftest key-file-normalization-contract + (with-temp-dir + (fn [dir] + (let [points (concat (range 0x09 0x0e) [0x20 0x85 0xa0 0x1680] + (range 0x2000 0x200b) [0x2028 0x2029 0x202f 0x205f 0x3000 0xfeff])] + (doseq [point points] + (let [ch (js/String.fromCodePoint point) + file (write-key! dir (str ch "mas" ch "ter" ch)) + cfg (cf/prepare-config {:exporter-shared-key-file file})] + (t/is (= "master" (:exporter-shared-key cfg)) (str "code point " point)))) + (let [whitespace (apply str (map js/String.fromCodePoint points)) + file (write-key! dir whitespace) + err (error-of #(cf/prepare-config {:exporter-shared-key-file file}))] + (t/is (and err (str/includes? (message err) "missing or empty")))) + (let [file (write-key! dir "\u0085mas\u00a0ter\ufeff") + cfg (cf/prepare-config {:secret-key-file file})] + (t/is (= "master" (:secret-key cfg))) + (t/is (= "GIFntVZnqcaOnDmD-Ii09n8wkajiOfVXI-RTJGyjKxg" (cf/get-management-key cfg)))) + (let [value "\u200b café\u180e" + file (write-key! dir value) + cfg (cf/prepare-config {:exporter-shared-key-file file})] + (t/is (= "\u200bcafé\u180e" (:exporter-shared-key cfg)))) + (let [file (write-key! dir (str "a" (apply str (repeat 2048 "\u00a0")))) + err (error-of #(cf/prepare-config {:exporter-shared-key-file file}))] + (t/is (and err (str/includes? (message err) "too large")))))))) diff --git a/exporter/test/exporter_tests/runner.cljs b/exporter/test/exporter_tests/runner.cljs index 82c3e4c46f..bf96a99775 100644 --- a/exporter/test/exporter_tests/runner.cljs +++ b/exporter/test/exporter_tests/runner.cljs @@ -10,6 +10,7 @@ [cljs.test :as t] [clojure.string :as str] [clojure.tools.cli :refer [parse-opts]] + [exporter-tests.config-test] [exporter-tests.export-shapes-test] [exporter-tests.jobs-test] [exporter-tests.renderer-svg-test] @@ -21,7 +22,8 @@ (enable-console-print!) (def test-namespaces - ['exporter-tests.export-shapes-test + ['exporter-tests.config-test + 'exporter-tests.export-shapes-test 'exporter-tests.jobs-test 'exporter-tests.renderer-svg-test 'exporter-tests.scheduler-test diff --git a/media-processor/src/config.ts b/media-processor/src/config.ts index c6229ae343..5d1710903f 100644 --- a/media-processor/src/config.ts +++ b/media-processor/src/config.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import { hkdfSync } from "node:crypto"; +import { readFileSync, statSync } from "node:fs"; import type { AppConfig } from "./types.js"; const envSchema = z.object({ @@ -16,7 +17,9 @@ const envSchema = z.object({ PENPOT_MEDIA_PROCESSOR_FONT_PROCESS_CPU_TIME: z.coerce.number().int().positive().default(30), PENPOT_MEDIA_PROCESSOR_FONT_TIMEOUT: z.coerce.number().int().positive().default(120000), PENPOT_MEDIA_PROCESSOR_SHARED_KEY: z.string().optional(), + PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE: z.string().optional(), PENPOT_SECRET_KEY: z.string().optional(), + PENPOT_SECRET_KEY_FILE: z.string().optional(), PENPOT_MEDIA_PROCESSOR_LOG_LEVEL: z .enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"]) .default("info"), @@ -31,14 +34,59 @@ function deriveSharedKey(secret: string): string { return Buffer.from(key).toString("base64url"); } +const MAX_KEY_FILE_SIZE = 4096; + +function readSharedKeyFile(variable: string, path: string): string { + let info; + try { + info = statSync(path); + } catch (error) { + console.error("unable to read configuration key file", variable, path, error); + } + if (!info || !info.isFile()) { + console.error("configuration key file is not a regular file", variable, path); + throw new Error(`${variable} key file is missing or empty: ${path}`); + } + if (info.size > MAX_KEY_FILE_SIZE) { + throw new Error(`${variable} key file is too large: ${path}`); + } + let value: string | undefined; + try { + value = readFileSync(path, "utf8").replace( + /[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/g, + "" + ); + } catch (error) { + console.error("unable to read configuration key file", variable, path, error); + } + if (!value) { + throw new Error(`${variable} key file is missing or empty: ${path}`); + } + return value; +} + export function loadConfig(): AppConfig { const parsed = envSchema.parse(process.env); let sharedKey: string | null = null; - if (parsed.PENPOT_MEDIA_PROCESSOR_SHARED_KEY) { - sharedKey = parsed.PENPOT_MEDIA_PROCESSOR_SHARED_KEY; - } else if (parsed.PENPOT_SECRET_KEY) { - sharedKey = deriveSharedKey(parsed.PENPOT_SECRET_KEY); + const explicitKey = parsed.PENPOT_MEDIA_PROCESSOR_SHARED_KEY; + if (explicitKey !== undefined) { + sharedKey = explicitKey.trim() === "" ? null : explicitKey.trim(); + } else if (parsed.PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE) { + sharedKey = readSharedKeyFile( + "PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", + parsed.PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE + ); + } else { + const secret = + parsed.PENPOT_SECRET_KEY !== undefined + ? parsed.PENPOT_SECRET_KEY + : parsed.PENPOT_SECRET_KEY_FILE !== undefined + ? readSharedKeyFile("PENPOT_SECRET_KEY_FILE", parsed.PENPOT_SECRET_KEY_FILE) + : undefined; + if (secret && (parsed.PENPOT_SECRET_KEY === undefined || secret.trim())) { + sharedKey = deriveSharedKey(secret); + } } return { diff --git a/media-processor/test/config.test.ts b/media-processor/test/config.test.ts index 019cbd4947..dde1f4df0e 100644 --- a/media-processor/test/config.test.ts +++ b/media-processor/test/config.test.ts @@ -1,17 +1,12 @@ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { loadConfig } from "../src/config.js"; +afterEach(() => vi.unstubAllEnvs()); + describe("loadConfig", () => { - const originalEnv = process.env; - - beforeEach(() => { - process.env = { ...originalEnv }; - }); - - afterEach(() => { - process.env = originalEnv; - }); - it("uses defaults when env vars not set", () => { const config = loadConfig(); expect(config.port).toBe(6065); @@ -23,13 +18,13 @@ describe("loadConfig", () => { }); it("accepts valid config with all fields set", () => { - process.env.PENPOT_MEDIA_PROCESSOR_PORT = "8080"; - process.env.PENPOT_MEDIA_PROCESSOR_HOST = "127.0.0.1"; - process.env.PENPOT_MEDIA_PROCESSOR_MAX_CONCURRENT_REQUESTS = "20"; - process.env.PENPOT_MEDIA_PROCESSOR_REQUEST_TIMEOUT = "30000"; - process.env.PENPOT_MEDIA_PROCESSOR_MAX_FILE_SIZE = "104857600"; - process.env.PENPOT_MEDIA_PROCESSOR_MEMORY_THRESHOLD = "5242880"; - process.env.PENPOT_MEDIA_PROCESSOR_SHARED_KEY = "test-key"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_PORT", "8080"); + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_HOST", "127.0.0.1"); + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_MAX_CONCURRENT_REQUESTS", "20"); + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_REQUEST_TIMEOUT", "30000"); + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_MAX_FILE_SIZE", "104857600"); + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_MEMORY_THRESHOLD", "5242880"); + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY", "test-key"); const config = loadConfig(); expect(config.port).toBe(8080); @@ -42,89 +37,314 @@ describe("loadConfig", () => { }); it("rejects concurrency=0", () => { - process.env.PENPOT_MEDIA_PROCESSOR_MAX_CONCURRENT_REQUESTS = "0"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_MAX_CONCURRENT_REQUESTS", "0"); expect(() => loadConfig()).toThrow(); }); it("rejects negative concurrency", () => { - process.env.PENPOT_MEDIA_PROCESSOR_MAX_CONCURRENT_REQUESTS = "-5"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_MAX_CONCURRENT_REQUESTS", "-5"); expect(() => loadConfig()).toThrow(); }); it("rejects fractional concurrency", () => { - process.env.PENPOT_MEDIA_PROCESSOR_MAX_CONCURRENT_REQUESTS = "2.5"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_MAX_CONCURRENT_REQUESTS", "2.5"); expect(() => loadConfig()).toThrow(); }); it("rejects negative timeout", () => { - process.env.PENPOT_MEDIA_PROCESSOR_REQUEST_TIMEOUT = "-1000"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_REQUEST_TIMEOUT", "-1000"); expect(() => loadConfig()).toThrow(); }); it("rejects fractional timeout", () => { - process.env.PENPOT_MEDIA_PROCESSOR_REQUEST_TIMEOUT = "1000.5"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_REQUEST_TIMEOUT", "1000.5"); expect(() => loadConfig()).toThrow(); }); it("rejects fractional port", () => { - process.env.PENPOT_MEDIA_PROCESSOR_PORT = "8080.5"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_PORT", "8080.5"); expect(() => loadConfig()).toThrow(); }); it("rejects negative port", () => { - process.env.PENPOT_MEDIA_PROCESSOR_PORT = "-8080"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_PORT", "-8080"); expect(() => loadConfig()).toThrow(); }); it("rejects negative max file size", () => { - process.env.PENPOT_MEDIA_PROCESSOR_MAX_FILE_SIZE = "-100"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_MAX_FILE_SIZE", "-100"); expect(() => loadConfig()).toThrow(); }); it("rejects negative memory threshold", () => { - process.env.PENPOT_MEDIA_PROCESSOR_MEMORY_THRESHOLD = "-100"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_MEMORY_THRESHOLD", "-100"); expect(() => loadConfig()).toThrow(); }); it("rejects negative image max pixels", () => { - process.env.PENPOT_MEDIA_PROCESSOR_IMAGE_MAX_PIXELS = "-100"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_IMAGE_MAX_PIXELS", "-100"); expect(() => loadConfig()).toThrow(); }); it("rejects fractional image max width", () => { - process.env.PENPOT_MEDIA_PROCESSOR_IMAGE_MAX_WIDTH = "100.5"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_IMAGE_MAX_WIDTH", "100.5"); expect(() => loadConfig()).toThrow(); }); it("rejects fractional image max height", () => { - process.env.PENPOT_MEDIA_PROCESSOR_IMAGE_MAX_HEIGHT = "100.5"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_IMAGE_MAX_HEIGHT", "100.5"); expect(() => loadConfig()).toThrow(); }); it("rejects negative font process mem", () => { - process.env.PENPOT_MEDIA_PROCESSOR_FONT_PROCESS_MEM = "-512"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_FONT_PROCESS_MEM", "-512"); expect(() => loadConfig()).toThrow(); }); it("rejects negative font process cpu time", () => { - process.env.PENPOT_MEDIA_PROCESSOR_FONT_PROCESS_CPU_TIME = "-30"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_FONT_PROCESS_CPU_TIME", "-30"); expect(() => loadConfig()).toThrow(); }); it("rejects negative font timeout", () => { - process.env.PENPOT_MEDIA_PROCESSOR_FONT_TIMEOUT = "-120000"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_FONT_TIMEOUT", "-120000"); expect(() => loadConfig()).toThrow(); }); it("accepts concurrency=1 (minimum valid)", () => { - process.env.PENPOT_MEDIA_PROCESSOR_MAX_CONCURRENT_REQUESTS = "1"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_MAX_CONCURRENT_REQUESTS", "1"); const config = loadConfig(); expect(config.maxConcurrentRequests).toBe(1); }); it("accepts timeout=0 (edge case, might be valid for testing)", () => { - process.env.PENPOT_MEDIA_PROCESSOR_REQUEST_TIMEOUT = "0"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_REQUEST_TIMEOUT", "0"); const config = loadConfig(); expect(config.requestTimeout).toBe(0); }); }); + +describe("shared key file", () => { + const keyVars = [ + "PENPOT_MEDIA_PROCESSOR_SHARED_KEY", + "PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", + "PENPOT_SECRET_KEY", + "PENPOT_SECRET_KEY_FILE", + ]; + + beforeEach(() => { + for (const variable of keyVars) vi.stubEnv(variable, undefined); + }); + + function withTempDir(f: (dir: string) => void): void { + const dir = mkdtempSync(join(tmpdir(), "penpot-mp-key-")); + try { + f(dir); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + } + + function writeKey(dir: string, content: string): string { + const path = join(dir, "shared-key"); + writeFileSync(path, content); + return path; + } + + it("reads, trims and unwraps the key file", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", writeKey(dir, "from-\n file \tkey")); + expect(loadConfig().sharedKey).toBe("from-filekey"); + }); + }); + + const whitespaceCodePoints = [ + ...Array.from({ length: 5 }, (_, i) => 0x09 + i), + 0x20, + 0x85, + 0xa0, + 0x1680, + ...Array.from({ length: 11 }, (_, i) => 0x2000 + i), + 0x2028, + 0x2029, + 0x202f, + 0x205f, + 0x3000, + 0xfeff, + ]; + + it.each(whitespaceCodePoints)("removes U+%s at both edges and inside a service key file", (codePoint) => { + withTempDir((dir) => { + const character = String.fromCodePoint(codePoint); + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", writeKey(dir, `${character}mas${character}ter${character}`)); + expect(loadConfig().sharedKey).toBe("master"); + }); + }); + + it("rejects a file containing only the specified Unicode whitespace", () => { + withTempDir((dir) => { + vi.stubEnv( + "PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", + writeKey(dir, String.fromCodePoint(...whitespaceCodePoints)) + ); + expect(() => loadConfig()).toThrow(/PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE key file is missing or empty/); + }); + }); + + it("preserves Unicode characters outside the specified list", () => { + withTempDir((dir) => { + const key = "\u180e\u200b café\u2060\u3001"; + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", writeKey(dir, key)); + expect(loadConfig().sharedKey).toBe("\u180e\u200bcafé\u2060\u3001"); + }); + }); + + it("checks original byte size before removing whitespace", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", writeKey(dir, "a" + "\u00a0".repeat(2048))); + expect(() => loadConfig()).toThrow(/too large/); + }); + }); + + it("rejects an empty selected master file path", () => { + vi.stubEnv("PENPOT_SECRET_KEY_FILE", ""); + expect(() => loadConfig()).toThrow(/PENPOT_SECRET_KEY_FILE/); + }); + + it.each(["master", "", " "])("prefers direct master %j over an empty master file path", (master) => { + vi.stubEnv("PENPOT_SECRET_KEY", master); + vi.stubEnv("PENPOT_SECRET_KEY_FILE", ""); + expect(loadConfig().sharedKey).toBe(master === "master" ? "xNYzcEWx3FaEOA0hM_-CqfYPHv_bjbDfncqkAE2wJzM" : null); + }); + + it.each(["explicit", "", " "])("prefers direct service key %j over an empty master file path", (key) => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY", key); + vi.stubEnv("PENPOT_SECRET_KEY_FILE", ""); + expect(loadConfig().sharedKey).toBe(key.trim() || null); + }); + + it("prefers a service key file over an empty master file path", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", writeKey(dir, "service")); + vi.stubEnv("PENPOT_SECRET_KEY_FILE", ""); + expect(loadConfig().sharedKey).toBe("service"); + }); + }); + + it("prefers the key file over derivation", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_SECRET_KEY", "master"); + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", writeKey(dir, "from-file")); + expect(loadConfig().sharedKey).toBe("from-file"); + }); + }); + + it("prefers the explicit key over the file", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY", "explicit"); + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", join(dir, "missing")); + expect(loadConfig().sharedKey).toBe("explicit"); + }); + }); + + it("rejects a missing key file with its variable name", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", join(dir, "missing")); + expect(() => loadConfig()).toThrow(/PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE key file is missing or empty/); + }); + }); + + it("rejects an empty key file", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", writeKey(dir, " \n\t")); + expect(() => loadConfig()).toThrow(/missing or empty/); + }); + }); + + it("rejects a directory as key file", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", dir); + expect(() => loadConfig()).toThrow(/missing or empty/); + }); + }); + + it("rejects an oversized key file", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", writeKey(dir, "a".repeat(5000))); + expect(() => loadConfig()).toThrow(/too large/); + }); + }); + + it("treats a blank explicit key as disabled", () => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY", ""); + expect(loadConfig().sharedKey).toBeNull(); + }); + + it("keeps sharedKey null when no source is configured", () => { + expect(loadConfig().sharedKey).toBeNull(); + }); + + it("derives from a normalized master key file", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_SECRET_KEY_FILE", writeKey(dir, "\u0085ma\u00a0s\u2003ter\ufeff")); + // Verified with backend app.setup.keys/derive using secret "master" and salt "media-processor". + expect(loadConfig().sharedKey).toBe("xNYzcEWx3FaEOA0hM_-CqfYPHv_bjbDfncqkAE2wJzM"); + }); + }); + + it.each(["master", "", " "])("prefers direct master %j over a missing master file", (master) => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_SECRET_KEY", master); + vi.stubEnv("PENPOT_SECRET_KEY_FILE", join(dir, "missing")); + expect(loadConfig().sharedKey).toBe(master === "master" ? "xNYzcEWx3FaEOA0hM_-CqfYPHv_bjbDfncqkAE2wJzM" : null); + }); + }); + + it.each(["master", ""])("prefers direct master %j over a valid master file", (master) => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_SECRET_KEY", master); + vi.stubEnv("PENPOT_SECRET_KEY_FILE", writeKey(dir, "different")); + expect(loadConfig().sharedKey).toBe(master ? "xNYzcEWx3FaEOA0hM_-CqfYPHv_bjbDfncqkAE2wJzM" : null); + }); + }); + + it.each(["explicit", "", " "])("prefers direct service key %j over a missing master file", (key) => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY", key); + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", join(dir, "missing-service")); + vi.stubEnv("PENPOT_SECRET_KEY", "master"); + vi.stubEnv("PENPOT_SECRET_KEY_FILE", join(dir, "missing-master")); + expect(loadConfig().sharedKey).toBe(key.trim() || null); + }); + }); + + it("prefers the service key file over a missing master file", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_MEDIA_PROCESSOR_SHARED_KEY_FILE", writeKey(dir, "service")); + vi.stubEnv("PENPOT_SECRET_KEY_FILE", join(dir, "missing")); + expect(loadConfig().sharedKey).toBe("service"); + }); + }); + + it.each([ + ["missing", (dir: string) => join(dir, "missing"), /PENPOT_SECRET_KEY_FILE key file is missing or empty/], + ["empty", (dir: string) => writeKey(dir, " \n\t"), /PENPOT_SECRET_KEY_FILE key file is missing or empty/], + ["directory", (dir: string) => dir, /PENPOT_SECRET_KEY_FILE key file is missing or empty/], + ["4097 bytes", (dir: string) => writeKey(dir, "a".repeat(4097)), /PENPOT_SECRET_KEY_FILE key file is too large/], + ])("rejects a master key file that is %s", (_label, path, error) => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_SECRET_KEY_FILE", path(dir)); + expect(() => loadConfig()).toThrow(error); + }); + }); + + it("accepts a master key file of exactly 4096 bytes", () => { + withTempDir((dir) => { + vi.stubEnv("PENPOT_SECRET_KEY_FILE", writeKey(dir, "a".repeat(4096))); + const fromFile = loadConfig().sharedKey; + vi.stubEnv("PENPOT_SECRET_KEY", "a".repeat(4096)); + expect(fromFile).not.toBeNull(); + expect(fromFile).toBe(loadConfig().sharedKey); + }); + }); +});