mirror of
https://github.com/penpot/penpot.git
synced 2026-11-27 13:32:28 +00:00
* ✨ 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
399 lines
18 KiB
Clojure
399 lines
18 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.rpc-auth-test
|
|
(:require
|
|
[app.auth.ldap :as ldap]
|
|
[app.auth.login-lockout :as lol]
|
|
[app.auth.oidc :as oidc]
|
|
[app.common.flags :as flags]
|
|
[app.common.generic-pool :as gpool]
|
|
[app.common.time :as ct]
|
|
[app.common.uri :as u]
|
|
[app.common.uuid :as uuid]
|
|
[app.config :as cf]
|
|
[app.http :as-alias http]
|
|
[app.http.session :as session]
|
|
[app.loggers.audit :as-alias audit]
|
|
[app.redis :as rds]
|
|
[app.rpc :as-alias rpc]
|
|
[app.rpc.commands.auth :as auth]
|
|
[app.rpc.commands.ldap :as ldap-cmd]
|
|
[app.storage :as sto]
|
|
[app.tokens :as tokens]
|
|
[backend-tests.helpers :as th]
|
|
[clojure.test :as t]
|
|
[datoteka.io :as io]
|
|
[mockery.core :refer [with-mocks]]
|
|
[yetti.response :as yres])
|
|
(:import
|
|
java.lang.AutoCloseable))
|
|
|
|
(t/use-fixtures :once th/state-init)
|
|
(t/use-fixtures :each th/database-reset)
|
|
|
|
(t/deftest recover-profile-invalidates-existing-sessions
|
|
"Regression: password recovery must delete the victim's server-side
|
|
sessions, otherwise a previously captured cookie keeps working
|
|
(GHSA-3j2p-qr45-q365)."
|
|
(let [prof (th/create-profile* 1)
|
|
manager (::session/manager th/*system*)
|
|
sid1 (uuid/random)
|
|
sid2 (uuid/random)
|
|
_ (th/db-exec-one! ["INSERT INTO http_session_v2 (id, profile_id, user_agent) VALUES (?, ?, ?)"
|
|
sid1 (:id prof) "agent-1"])
|
|
_ (th/db-exec-one! ["INSERT INTO http_session_v2 (id, profile_id, user_agent) VALUES (?, ?, ?)"
|
|
sid2 (:id prof) "agent-2"])
|
|
token (tokens/generate th/*system*
|
|
{:iss :password-recovery
|
|
:exp (ct/in-future "15m")
|
|
:profile-id (:id prof)})]
|
|
(with-mocks [_ {:target 'app.email/send-template :return nil}]
|
|
(let [out (th/command! {::th/type :recover-profile
|
|
:token token
|
|
:password "Foobar12!"})]
|
|
(t/is (nil? (:error out)))))
|
|
(t/is (nil? (session/read-session manager sid1))
|
|
"recover-profile must delete the victim's sessions (GHSA-3j2p-qr45-q365)")
|
|
(t/is (nil? (session/read-session manager sid2))
|
|
"recover-profile must delete the victim's sessions (GHSA-3j2p-qr45-q365)")))
|
|
|
|
(t/deftest recover-profile-keeps-other-profiles-sessions
|
|
(let [prof-a (th/create-profile* 1)
|
|
prof-b (th/create-profile* 2)
|
|
manager (::session/manager th/*system*)
|
|
sid-a (uuid/random)
|
|
sid-b (uuid/random)
|
|
_ (th/db-exec-one! ["INSERT INTO http_session_v2 (id, profile_id, user_agent) VALUES (?, ?, ?)"
|
|
sid-a (:id prof-a) "agent-a"])
|
|
_ (th/db-exec-one! ["INSERT INTO http_session_v2 (id, profile_id, user_agent) VALUES (?, ?, ?)"
|
|
sid-b (:id prof-b) "agent-b"])
|
|
token (tokens/generate th/*system*
|
|
{:iss :password-recovery
|
|
:exp (ct/in-future "15m")
|
|
:profile-id (:id prof-a)})]
|
|
(with-mocks [_ {:target 'app.email/send-template :return nil}]
|
|
(let [out (th/command! {::th/type :recover-profile
|
|
:token token
|
|
:password "Foobar12!"})]
|
|
(t/is (nil? (:error out)))))
|
|
(t/is (nil? (session/read-session manager sid-a)))
|
|
(t/is (some? (session/read-session manager sid-b))
|
|
"sessions of other profiles must survive the recovery")))
|
|
|
|
(t/deftest recover-profile-rollback-keeps-password-and-sessions
|
|
"A failure after the password UPDATE rolls the transaction back, so the
|
|
captured session and the old password both survive
|
|
(GHSA-3j2p-qr45-q365)."
|
|
(let [prof (th/create-profile* 1)
|
|
manager (::session/manager th/*system*)
|
|
sid (uuid/random)
|
|
_ (th/db-exec-one! ["INSERT INTO http_session_v2 (id, profile_id, user_agent) VALUES (?, ?, ?)"
|
|
sid (:id prof) "agent-1"])
|
|
before (:password (th/db-exec-one! ["SELECT password FROM profile WHERE id = ?" (:id prof)]))
|
|
token (tokens/generate th/*system*
|
|
{:iss :password-recovery
|
|
:exp (ct/in-future "15m")
|
|
:profile-id (:id prof)})]
|
|
(with-mocks [_ {:target 'app.email/send-template
|
|
:throw (ex-info "smtp down" {})}]
|
|
(let [out (th/command! {::th/type :recover-profile
|
|
:token token
|
|
:password "Foobar12!"})]
|
|
(t/is (some? (:error out)))))
|
|
(t/is (some? (session/read-session manager sid))
|
|
"a rolled-back recovery must not delete sessions")
|
|
(t/is (= before (:password (th/db-exec-one! ["SELECT password FROM profile WHERE id = ?" (:id prof)])))
|
|
"a rolled-back recovery must not change the password")))
|
|
|
|
(t/deftest logout-invalidates-current-session
|
|
(let [prof (th/create-profile* 1)
|
|
manager (::session/manager th/*system*)
|
|
sid (uuid/random)
|
|
_ (th/db-exec-one! ["INSERT INTO http_session_v2 (id, profile_id, user_agent) VALUES (?, ?, ?)"
|
|
sid (:id prof) "test-agent"])
|
|
session (session/read-session manager sid)]
|
|
|
|
;; Arrange: session exists before logout
|
|
(t/is (some? session) "session should exist before logout")
|
|
(t/is (= sid (:id session)))
|
|
|
|
;; Act: simulate Ring request as produced by wrap-authz (has ::session/session)
|
|
;; delete-fn is used as response transform via rph/with-transform in auth/logout
|
|
(let [request {::session/session session}
|
|
response {}
|
|
delete-fn (session/delete-fn th/*system*)
|
|
result (delete-fn request response)]
|
|
|
|
;; Assert: server-side session is deleted (CWE-613)
|
|
(t/is (nil? (session/read-session manager sid))
|
|
"session must be deleted server-side after logout (GHSA-mj9f-5cwq-7p3q)")
|
|
|
|
;; Assert: cookie is cleared
|
|
(t/is (= "" (get-in result [::yres/cookies "auth-token" :value]))
|
|
"auth-token cookie should be cleared")
|
|
(t/is (= 0 (get-in result [::yres/cookies "auth-token" :max-age]))
|
|
"auth-token cookie max-age should be 0"))))
|
|
|
|
(t/deftest logout-clears-cookie-even-when-session-missing
|
|
(let [manager (::session/manager th/*system*)
|
|
sid (uuid/random)
|
|
;; No session inserted, read should be nil
|
|
_ (t/is (nil? (session/read-session manager sid)))
|
|
request {}
|
|
response {}
|
|
delete-fn (session/delete-fn th/*system*)
|
|
result (delete-fn request response)]
|
|
|
|
;; Should still clear cookie (idempotent)
|
|
(t/is (= "" (get-in result [::yres/cookies "auth-token" :value])))
|
|
(t/is (= 0 (get-in result [::yres/cookies "auth-token" :max-age])))))
|
|
|
|
(t/deftest logout-does-not-invalidate-other-sessions
|
|
(let [prof (th/create-profile* 1)
|
|
manager (::session/manager th/*system*)
|
|
sid1 (uuid/random)
|
|
sid2 (uuid/random)
|
|
_ (th/db-exec-one! ["INSERT INTO http_session_v2 (id, profile_id, user_agent) VALUES (?, ?, ?)"
|
|
sid1 (:id prof) "agent-1"])
|
|
_ (th/db-exec-one! ["INSERT INTO http_session_v2 (id, profile_id, user_agent) VALUES (?, ?, ?)"
|
|
sid2 (:id prof) "agent-2"])
|
|
s1 (session/read-session manager sid1)
|
|
s2 (session/read-session manager sid2)]
|
|
|
|
(t/is (some? s1))
|
|
(t/is (some? s2))
|
|
|
|
;; Logout only sid1
|
|
(let [request {::session/session s1}
|
|
response {}
|
|
delete-fn (session/delete-fn th/*system*)]
|
|
(delete-fn request response))
|
|
|
|
;; sid1 deleted, sid2 intact
|
|
(t/is (nil? (session/read-session manager sid1)) "current session should be deleted")
|
|
(t/is (some? (session/read-session manager sid2)) "other sessions should remain")))
|
|
|
|
(t/deftest replay-after-logout-cannot-authenticate
|
|
(let [prof (th/create-profile* 1)
|
|
manager (::session/manager th/*system*)
|
|
sid (uuid/random)
|
|
_ (th/db-exec-one! ["INSERT INTO http_session_v2 (id, profile_id, user_agent) VALUES (?, ?, ?)"
|
|
sid (:id prof) "test-agent"])
|
|
session (session/read-session manager sid)]
|
|
|
|
(t/is (some? session) "session exists before logout")
|
|
|
|
;; Simulate logout
|
|
(let [request {::session/session session}
|
|
response {}
|
|
delete-fn (session/delete-fn th/*system*)]
|
|
(delete-fn request response))
|
|
|
|
;; Replay: attempt to read session with same sid should fail (no profile attached)
|
|
(t/is (nil? (session/read-session manager sid))
|
|
"replayed token must not resolve to a valid session after logout")))
|
|
|
|
(defn- cleanup-redis
|
|
[profile-id]
|
|
(let [pool (get-in th/*system* [:app.redis/pool])
|
|
conn (gpool/get pool)]
|
|
(try
|
|
(rds/del @conn (str "penpot.login-lockout." profile-id))
|
|
(finally
|
|
(.close ^AutoCloseable conn)))))
|
|
|
|
(t/deftest login-with-password-locks-after-max-attempts
|
|
(with-redefs [app.config/flags (flags/parse flags/default [:enable-account-lockout :disable-admin-console])]
|
|
(let [profile (th/create-profile* 200 {:is-active true})]
|
|
(cleanup-redis (:id profile))
|
|
;; 4 failed attempts — not yet locked
|
|
(dotimes [i 4]
|
|
(let [data {::th/type :login-with-password
|
|
:email (:email profile)
|
|
:password "wrongpassword"}
|
|
out (th/command! data)]
|
|
(t/is (th/ex-of-code? (:error out) :wrong-credentials))))
|
|
;; 5th attempt — should trigger lockout
|
|
(let [data {::th/type :login-with-password
|
|
:email (:email profile)
|
|
:password "wrongpassword"}
|
|
out (th/command! data)]
|
|
(t/is (th/ex-of-type? (:error out) :rate-limit))
|
|
(t/is (th/ex-of-code? (:error out) :account-locked))))))
|
|
|
|
(t/deftest login-with-password-returns-rate-limit-when-locked
|
|
(with-redefs [app.config/flags (flags/parse flags/default [:enable-account-lockout :disable-admin-console])]
|
|
(let [profile (th/create-profile* 201 {:is-active true})]
|
|
(cleanup-redis (:id profile))
|
|
;; Trigger lockout
|
|
(dotimes [i 5]
|
|
(th/command! {::th/type :login-with-password
|
|
:email (:email profile)
|
|
:password "wrongpassword"}))
|
|
;; Next attempt with correct password — still blocked
|
|
(let [data {::th/type :login-with-password
|
|
:email (:email profile)
|
|
:password "Test123!"}
|
|
out (th/command! data)]
|
|
(t/is (th/ex-of-type? (:error out) :rate-limit))
|
|
(t/is (th/ex-of-code? (:error out) :account-locked))
|
|
(let [ttl (:ttl (ex-data (:error out)))]
|
|
(t/is (some? ttl) "ttl should be present in ex-data")
|
|
(t/is (pos? ttl) "ttl should be a positive number"))))))
|
|
|
|
(t/deftest successful-login-clears-failed-attempts
|
|
(with-redefs [app.config/flags (flags/parse flags/default [:enable-account-lockout :disable-admin-console])]
|
|
(let [profile (th/create-profile* 202 {:is-active true})]
|
|
(cleanup-redis (:id profile))
|
|
;; 3 failed attempts
|
|
(dotimes [i 3]
|
|
(th/command! {::th/type :login-with-password
|
|
:email (:email profile)
|
|
:password "wrongpassword"}))
|
|
;; Successful login
|
|
(let [data {::th/type :login-with-password
|
|
:email (:email profile)
|
|
:password "Test123!"}
|
|
out (th/command! data)]
|
|
(t/is (nil? (:error out))))
|
|
;; 4 more failed attempts should NOT trigger lockout (counter was reset)
|
|
(dotimes [i 4]
|
|
(let [data {::th/type :login-with-password
|
|
:email (:email profile)
|
|
:password "wrongpassword"}
|
|
out (th/command! data)]
|
|
(t/is (th/ex-of-code? (:error out) :wrong-credentials)))))))
|
|
|
|
(t/deftest lockout-does-not-apply-when-flag-disabled
|
|
(with-redefs [app.config/flags (flags/parse flags/default [:disable-admin-console])]
|
|
(let [profile (th/create-profile* 203 {:is-active true})]
|
|
(cleanup-redis (:id profile))
|
|
;; 10 failed attempts — no lockout without the flag
|
|
(dotimes [i 10]
|
|
(let [data {::th/type :login-with-password
|
|
:email (:email profile)
|
|
:password "wrongpassword"}
|
|
out (th/command! data)]
|
|
(t/is (th/ex-of-code? (:error out) :wrong-credentials)))))))
|
|
|
|
(t/deftest login-with-ldap-returns-rate-limit-when-locked
|
|
"Verify that login-with-ldap short-circuits when account is locked,
|
|
without attempting LDAP authentication. Calls the actual command
|
|
function with a mock provider to test the full flow."
|
|
(with-redefs [app.config/flags (flags/parse flags/default [:enable-account-lockout :login-with-ldap :disable-admin-console])
|
|
ldap/authenticate (constantly nil)]
|
|
(let [profile (th/create-profile* 204 {:is-active true})
|
|
cfg (assoc th/*system* ::ldap/provider {})]
|
|
(cleanup-redis (:id profile))
|
|
;; Lock account with 5 failed attempts
|
|
(dotimes [i 5]
|
|
(lol/record-failed-attempt! cfg (:id profile)))
|
|
;; Call actual command function — should be blocked without calling authenticate
|
|
(let [out (th/try-on! (#'ldap-cmd/sm$login-with-ldap
|
|
cfg
|
|
{:email (:email profile)
|
|
:password "wrongpassword"}))]
|
|
(t/is (th/ex-of-type? (:error out) :rate-limit))
|
|
(t/is (th/ex-of-code? (:error out) :account-locked))))))
|
|
|
|
(t/deftest recover-profile-clears-lockout
|
|
"Verify that clearing attempts (e.g. after password reset) unlocks the account."
|
|
(with-redefs [app.config/flags (flags/parse flags/default [:enable-account-lockout :disable-admin-console])]
|
|
(let [profile (th/create-profile* 205 {:is-active true})
|
|
cfg th/*system*]
|
|
(cleanup-redis (:id profile))
|
|
;; Lock the account
|
|
(dotimes [i 5]
|
|
(lol/record-failed-attempt! cfg (:id profile)))
|
|
(t/is (:locked? (lol/locked? cfg (:id profile))))
|
|
;; Simulate password reset clearing
|
|
(lol/clear-attempts! cfg (:id profile))
|
|
;; Verify unlocked
|
|
(t/is (false? (:locked? (lol/locked? cfg (:id profile))))))))
|
|
|
|
(t/deftest login-with-ldap-binds-session-to-directory-identity
|
|
"Regression: the session must be bound to the profile resolved from the
|
|
LDAP-returned email, never to the profile matching the typed email.
|
|
Both can differ with aliases, UPNs or multi-valued mail attributes."
|
|
(let [typed (th/create-profile* 206 {:is-active true})
|
|
directory (th/create-profile* 207 {:is-active true})
|
|
cfg (assoc th/*system* ::ldap/provider {})]
|
|
(with-redefs [ldap/authenticate
|
|
(fn [_ _]
|
|
{:email (:email directory)
|
|
:fullname (:fullname directory)
|
|
:backend "ldap"})]
|
|
(let [result (#'ldap-cmd/sm$login-with-ldap
|
|
cfg
|
|
{:email (:email typed)
|
|
:password "whatever"})]
|
|
(t/is (some? result))
|
|
(t/is (= (:id directory) (::audit/profile-id (meta result)))
|
|
"session must be bound to the directory-verified profile")
|
|
(t/is (not= (:id typed) (::audit/profile-id (meta result)))
|
|
"session must not be bound to the typed-email profile")))))
|
|
|
|
(t/deftest logout-uses-trusted-origin-for-post-logout-redirect
|
|
(let [profile-id (uuid/random)
|
|
provider {:logout-uri "https://idp.example.com/logout"
|
|
:client-id "test-client"}
|
|
data {::th/type :logout
|
|
::rpc/profile-id profile-id
|
|
:profile-id profile-id}
|
|
attrs {::http/auth-data {:claims {:sso-provider-id "oidc"
|
|
:sso-session-id "sid"}}}
|
|
config (assoc cf/config
|
|
:public-uri "http://localhost:3449"
|
|
:trusted-origins #{"https://alt.example.com"})]
|
|
|
|
(with-redefs [oidc/get-provider (fn [_ _] provider)]
|
|
(t/testing "trusted origin becomes the post-logout redirect"
|
|
(with-redefs [cf/config config]
|
|
(let [out (th/command-through-middleware
|
|
data {:headers {"origin" "https://alt.example.com"}
|
|
:request-attrs attrs})
|
|
q (u/query-string->map (:query (:redirect-uri (:result out))))]
|
|
(t/is (= "https://alt.example.com" (get q :post_logout_redirect_uri))))))
|
|
|
|
(t/testing "without a trusted origin the canonical base is used"
|
|
(with-redefs [cf/config config]
|
|
(let [out (th/command-through-middleware
|
|
data {:headers {"origin" "https://evil.example.com"}
|
|
:request-attrs attrs})
|
|
q (u/query-string->map (:query (:redirect-uri (:result out))))]
|
|
(t/is (= "http://localhost:3449" (get q :post_logout_redirect_uri)))))))))
|
|
|
|
|
|
;; --- Profile picture import
|
|
|
|
(def ^:private avatar-svg
|
|
"An SVG that smuggles a script element."
|
|
"<svg xmlns=\"http://www.w3.org/2000/svg\"><script>alert(1)</script></svg>")
|
|
|
|
(defn- mock-download
|
|
"Mock the http client so that any url answers with `body` and `mtype`."
|
|
[mtype body]
|
|
{:target 'app.http.client/req-with-redirects
|
|
:return {:status 200
|
|
:headers {"content-type" mtype
|
|
"content-length" (str (alength ^bytes body))}
|
|
:body (java.io.ByteArrayInputStream. ^bytes body)}})
|
|
|
|
(t/deftest import-profile-picture-rejects-svg
|
|
(t/testing "an svg profile picture is not imported"
|
|
(with-mocks [http-mock (mock-download "image/svg+xml"
|
|
(.getBytes ^String avatar-svg "UTF-8"))]
|
|
(let [result (auth/import-profile-picture th/*system* "https://example.com/avatar.svg")]
|
|
(t/is (nil? result)))))
|
|
|
|
(t/testing "a png profile picture is imported"
|
|
(let [body (io/read* (io/resource "backend_tests/test_files/sample.png"))]
|
|
(with-mocks [http-mock (mock-download "image/png" body)]
|
|
(let [result (auth/import-profile-picture th/*system* "https://example.com/avatar.png")]
|
|
(t/is (some? result))
|
|
(t/is (some? (sto/get-object (:app.storage/storage th/*system*) result))))))))
|