mirror of
https://github.com/penpot/penpot.git
synced 2026-11-26 21:00:32 +00:00
✨ 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
This commit is contained in:
parent
f3baec6658
commit
a7f66b18f9
@ -3,6 +3,7 @@
|
||||
- Start at `app.auth.oidc`, `app.rpc.commands.auth` and `app.rpc.commands.ldap`. For HTTP session and token boundaries see `mem:backend/http-rpc` and `mem:backend/auth-tokens`.
|
||||
- LDAP binds the session to the directory-returned email, not the typed login: aliases and multi-valued attributes can resolve to a different profile. Redis-backed account lockout checks use the typed identity, but successful login clears the counter for the profile actually logged in. Lockout and RPC rate limits use the `app.http.errors` 429 path; keep `retry-after` and rate-limit headers available through CORS.
|
||||
- `check-nitrate-sso` receives the client route as a query string, not an absolute URL. `build-dest-url` validates parameter keys and builds the destination under `public-uri`; invalid input falls back there. Accept root routes without `screen`, and keep callback revalidation for older state tokens. The state token binds the SSO grant to the profile that initiated it: a different session must not receive that grant.
|
||||
- Generic OIDC authorization stores only the trusted alternate origin (request `:app.http/trusted-origin`, see `mem:backend/http-rpc`) as `:origin` in signed state, not the full public URI or path. The callback applies that origin to the configured public URI without re-normalizing it or consulting the allowlist, so removing an entry does not revoke an in-flight login. Authorization and token exchange build `redirect_uri` from the effective base, including the configured path, which must stay the same across the flow. Organization SSO carries the same claim via `build-organization-sso-auth-redirect-uri :origin` and still checks the destination and profile. MCP OAuth (`app.http.mcp-oauth`) has no trusted-origin support: `authorize` is a top-level GET navigation with no usable origin, so the whole flow keeps the canonical public URI.
|
||||
- A client-supplied organization ID requires `app.nitrate/organization-access?` before SSO; callers without organization access get the no-access short circuit, not an SSO challenge.
|
||||
- When public registration is disabled, a matching invitation can allow registration. Password registration rechecks the non-expired invitation row under lock. OIDC registration requires `:registration`, `:oidc-registration` or an invitation whose member email matches the provider email after `clean-email`; the callback verifies it and registration revalidates it under lock when the flags are off. Only recognized OIDC provider types take the SSO registration path. Keep invitation identity checks on authenticated login too.
|
||||
- Test both the root and workspace route forms, malformed redirect targets, changed sessions and invitation email mismatches. Frontend query-string construction: `mem:frontend/routing`. For test flags and setup see `mem:backend/testing`.
|
||||
|
||||
@ -7,3 +7,5 @@
|
||||
- A v1 package can list a file twice (legacy export included libraries without deduping). Consume both objects of every entry to keep the stream aligned, but import and report the first occurrence only.
|
||||
- v1/v3 import and v3 export's file read run inside long transactions. They extend the idle-in-transaction timeout without disabling it or extending the statement timeout; keep both limits distinct. See `app.binfile.common/transaction-idle-timeout-ms`.
|
||||
- v1/v3 import links must refer to files in the package and reject self-links and dependency cycles, using the same check as the live link command. Keep iteration deterministic so the first edge wins consistently.
|
||||
- The public export creation schema excludes `:public-uri`: the backend adds the effective full public base (including its path) as a string only after validating a trusted origin stamp. The worker uses that stored base for the download link without rechecking the allowlist; jobs with no such param use the worker's canonical base.
|
||||
- Upgrade every `binfile` worker before enabling trusted aliases. The runner validates stored params before invoking the handler, and an older worker's closed export schema rejects the private `:public-uri` key as a permanent validation failure. To roll back, disable aliases on frontend and all backend instances, then keep upgraded workers running until queued export jobs with a saved base finish. Changing the allowlist never rewrites persisted params.
|
||||
|
||||
@ -3,3 +3,4 @@
|
||||
- Start at `app.config` for environment coercion and boot validation. For duration settings use hours for whole days (e.g. `168h`, not `7d`). For checks that depend on Clojure assertions, see the startup flag in `mem:backend/testing`; redefining flags at runtime does not restore assertions compiled out at load.
|
||||
- `app.main` wires `PENPOT_DATABASE_*` into `app.db/create-datasource-config`. Keep driver properties as strings: pgjdbc uses `Properties.getProperty`. A parameter of the same name in `PENPOT_DATABASE_URI` takes precedence; check the URI before diagnosing an ignored setting.
|
||||
- `prepareThreshold=0` disables server-side prepares, not the driver's cache of parsed queries. A zero query or size limit disables that cache. The configured size is in bytes and rounds up to whole MiB for pgjdbc. Use the schemas and datasource builder for accepted ranges and property names.
|
||||
- `PENPOT_TRUSTED_ORIGINS` is shared with the frontend (see `mem:frontend/routing-app-shell-subtleties`) and sets the backend's public base for generated links, not CORS (`PENPOT_ALLOWED_ORIGINS`) or cookie flags. Normalize bare HTTP(S) origins on load (trim, lowercase, default port removal); reject paths, credentials, query, fragment and wildcards. Drop malformed entries with a warning (never log the raw value) and warn once for valid HTTP origins outside `localhost` without dropping them. Removing an alias does not rewrite queued mail or export jobs or revoke links and OIDC state; see the retirement steps in `docs/technical-guide/configuration.md`.
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
# HTTP and RPC boundaries
|
||||
|
||||
- Start at `app.rpc/resolve-methods` for command discovery and `wrap` / `wrap-management` for request order. A new command namespace must be registered. `GET` and `HEAD` require a `get-` name; auth is on unless explicitly disabled. Metrics wraps concurrency, so RPC timing includes time spent waiting for a permit. Transaction handling sits inside the wrappers and is controlled by `::db/transaction`.
|
||||
- `wrap-trusted-origin` picks the first normalized candidate in the prepared set: `X-Penpot-Origin` (added by Penpot API request builders, including RPC GETs), then `Origin`. It never uses `Host` or `X-Forwarded-Host`, and leaves the canonical binding alone when neither matches. The stamp `:app.http/trusted-origin` is only the origin string: the effective `:public-uri` keeps the canonical path while scheme, host and port change. SSE captures the binding with `bound-fn` because its body runs after the handler returns. OIDC carries only the origin in signed state (`mem:backend/auth-sso`); MCP OAuth stays canonical.
|
||||
- Workers that build links without a saved request base use the canonical `:public-uri`. Export saves the effective full base as a string; templated email jobs keep their recipe base as a string and render it later, normalizing the slash at the shared render boundary so both bases keep the subpath with one separator.
|
||||
- Strip qualified client params before merging server auth context; only the server supplies the profile, auth type and token permissions. Malli map schemas are open by default. Keep public creation schemas closed to reject client IDs while allowing internal creation helpers to accept IDs for imports or duplication. See `wrap-params-validation` for JSON coercion and legacy spec fallback.
|
||||
- A malformed body is a client error classified at the parse boundary, not by exception class. Preserve 400 `:malformed-json` for malformed input and 413 for oversized bodies. See `app.http.middleware` for parsing and `Accept`/`_fmt` response negotiation, and `mem:backend/metrics` for pre-dispatch counters.
|
||||
- Upload schemas validate shape, not path ownership. Declare `::sm/params` as well as file keys in `::rpc/multipart-only-params`: the multipart guard runs inside `wrap-params-validation` and is skipped without a schema. Run `media.v/check-upload-path` before reading the file; see `mem:backend/media` for processing and storage. The binfile job creation RPC instead takes a chunked upload ID; see `mem:backend/binfile`.
|
||||
|
||||
@ -19,7 +19,7 @@ Start at `app.main.ui` for Rumext components, `app.main.data` for Potok events,
|
||||
|
||||
## App shell
|
||||
|
||||
- Router, history, SSO destinations and team context: `mem:frontend/routing`.
|
||||
- Public URI selection for a shared frontend on trusted alternate origins, router, history, SSO destinations and team context: `mem:frontend/routing`.
|
||||
- Authentication event sources and invitations: `mem:frontend/auth-events`.
|
||||
- Error boundary, transport errors and reports: `mem:frontend/error-reporting`.
|
||||
- WebSocket lifetime, membership revocation, and job progress: `mem:frontend/websocket-notifications`.
|
||||
|
||||
@ -1,6 +1,9 @@
|
||||
# Routing and app shell
|
||||
|
||||
- Start at `app.main.ui.routes`, `app.main.router` and `app.util.browser-history`. The token is `location.search`, not a store field; preserve the configured `public-uri` origin and subpath. The route table and legacy hash compatibility live in `app.main.ui.routes`.
|
||||
- A shared frontend and backend use the same `PENPOT_TRUSTED_ORIGINS` list, serialized as data in `config.js`. `app.config` selects `location.origin` only on an exact match with a normalized entry: only scheme, host and port change, so the canonical path and trailing slash stay in `cf/public-uri`. With no match use the configured base; keep the browser-origin fallback when no public URI is configured. The reverse proxy must serve that same path on every alias.
|
||||
- `X-Penpot-Origin` carries the page origin only on Penpot backend API paths that opt in to public base selection (RPC, including GET and multipart, and OIDC initiation). Do not add it to `app.util.http` defaults: fonts, assets, exporter-only requests and external URLs do not use it. The backend validates it separately from CORS; see `mem:backend/http-rpc`.
|
||||
- Configure IPv6 aliases as the browser serializes the origin (e.g. `https://[::1]:9443`); expanded spellings do not match. After alias removal the frontend can reject the return URL while the backend still honors signed OIDC state: the user may need a new login on the canonical domain.
|
||||
- Push of the current token does not write or notify; replace always writes and notifies, even for the same token, so URL corrections reach the router. `app.util.dom/replace-history-state!` intentionally rewrites without routing; do not substitute a notifying replace.
|
||||
- Route data uses query params. A repeated param can decode as a vector; use `rt/get-query-param` for a scalar. Use `rt/token->query-string` at the SSO boundary: the server owns the destination origin. Use `rt/token->url` for a client-side absolute URL; do not require `screen`, since root flows can carry params such as a template without a route name. See `mem:backend/auth-sso`.
|
||||
- `rt/nav-raw` exits the router; tests observe its destination by dereferencing the event, not by looking for an app listener. Unknown or empty routes verify the profile and teams before redirecting so root and invitation flows do not race. See `mem:frontend/auth-events` for login and invitations.
|
||||
|
||||
@ -455,8 +455,7 @@
|
||||
|
||||
(defn- build-redirect-uri
|
||||
[]
|
||||
(let [public (u/uri (cf/get :public-uri))]
|
||||
(str (assoc public :path "/api/auth/oidc/callback"))))
|
||||
(cf/get-public-uri "api/auth/oidc/callback"))
|
||||
|
||||
(defn build-auth-redirect-uri
|
||||
[provider token]
|
||||
@ -1020,8 +1019,11 @@
|
||||
can never point outside the public URI.
|
||||
`profile-id` is the profile that started the flow; it travels in the
|
||||
state token so the callback only grants the organization SSO entry to that
|
||||
very session."
|
||||
[cfg sso & {:keys [query-string organization-id provider profile-id]}]
|
||||
very session.
|
||||
`origin` is the trusted alternate origin stamped by the http trusted-origin
|
||||
middleware; it travels in the state token so the callback, a navigation
|
||||
without Origin, can rebuild the links on the same base."
|
||||
[cfg sso & {:keys [query-string organization-id provider profile-id origin]}]
|
||||
(let [organization-id (or organization-id (:organization-id sso))
|
||||
issuer (organization-sso-discovery-uri sso)
|
||||
dest-url (build-dest-url query-string)]
|
||||
@ -1036,6 +1038,7 @@
|
||||
:organization-id organization-id
|
||||
:profile-id profile-id
|
||||
:issuer issuer
|
||||
:origin origin
|
||||
:exp (ct/in-future "4h")})]
|
||||
(build-auth-redirect-uri oidc-provider state-token))
|
||||
(catch Throwable cause
|
||||
@ -1119,6 +1122,11 @@
|
||||
:provider (:id provider)
|
||||
:invitation-token (:invitation-token params)
|
||||
:external-session-id esid
|
||||
;; Trusted alternate origin stamped by the http
|
||||
;; trusted-origin middleware; carried through the signed
|
||||
;; state so the callback (a navigation without Origin)
|
||||
;; can rebuild links and the token-exchange redirect_uri.
|
||||
:origin (:app.http/trusted-origin request)
|
||||
:props props
|
||||
:exp (ct/in-future "4h")}
|
||||
state (tokens/generate cfg (d/without-nils params))
|
||||
@ -1210,16 +1218,27 @@
|
||||
(profile/clean-email email)))))
|
||||
(catch Throwable _ false)))
|
||||
|
||||
(defn- callback-handler
|
||||
[cfg {:keys [params] :as request}]
|
||||
(defn- parse-state
|
||||
"Verifies the OIDC state token once. Returns `[state failure]` where
|
||||
exactly one of the two is non-nil: the decoded claims on success, or the
|
||||
verification error when the token is missing, invalid or expired."
|
||||
[cfg params]
|
||||
(try
|
||||
[(tokens/verify cfg {:token (:state params) :iss "oidc"}) nil]
|
||||
(catch Throwable cause
|
||||
[nil cause])))
|
||||
|
||||
(defn- handle-oidc-callback
|
||||
[cfg {:keys [params] :as request} state failure]
|
||||
(if-let [error (get params :error)]
|
||||
(do
|
||||
(submit-organization-sso-oauth-failed-event cfg request (:state params) error)
|
||||
(redirect-with-error "unable-to-auth" error))
|
||||
(try
|
||||
(let [code (get params :code)
|
||||
state (get params :state)
|
||||
state (tokens/verify cfg {:token state :iss "oidc"})]
|
||||
(when (some? failure)
|
||||
(throw failure))
|
||||
|
||||
(let [code (get params :code)]
|
||||
|
||||
;; Organization SSO flow: state carries :dest-url — exchange the authorization
|
||||
;; code with the OIDC provider to verify authentication actually occurred.
|
||||
@ -1294,6 +1313,17 @@
|
||||
(l/err :hint "error on process oidc callback" :cause cause))
|
||||
(redirect-with-error "unable-to-auth" (ex-message cause)))))))
|
||||
|
||||
(defn- callback-handler
|
||||
"Callback entrypoint. The IdP redirect is a browser navigation that
|
||||
normally carries no Origin, so the http trusted-origin middleware
|
||||
cannot help here; re-apply the trusted origin stored in the signed
|
||||
state for the whole callback (token exchange redirect_uri and every
|
||||
redirect target)."
|
||||
[cfg {:keys [params] :as request}]
|
||||
(let [[state failure] (parse-state cfg params)]
|
||||
(binding [cf/config (cf/with-public-origin (:origin state) cf/config)]
|
||||
(handle-oidc-callback cfg request state failure))))
|
||||
|
||||
(def ^:private schema:routes-params
|
||||
[:map
|
||||
::session/manager
|
||||
|
||||
@ -21,7 +21,10 @@
|
||||
[cuerdas.core :as str]
|
||||
[datoteka.fs :as fs]
|
||||
[environ.core :refer [env]]
|
||||
[integrant.core :as ig]))
|
||||
[integrant.core :as ig])
|
||||
(:import
|
||||
java.net.URI
|
||||
java.net.URISyntaxException))
|
||||
|
||||
(defmethod ig/init-key :default
|
||||
[_ data]
|
||||
@ -168,6 +171,14 @@
|
||||
;; separated list of origins (e.g. "https://plugins.example.com").
|
||||
[:allowed-origins {:optional true} [::sm/set :string]]
|
||||
|
||||
;; Explicit allowlist of alternate origins the backend may use as the
|
||||
;; public base for links generated while serving a request whose
|
||||
;; `Origin` header matches. Configured via PENPOT_TRUSTED_ORIGINS as a
|
||||
;; comma/whitespace separated list of bare origins
|
||||
;; (e.g. "https://alt.example.com"). Fail-closed: origins not listed
|
||||
;; keep using :public-uri.
|
||||
[:trusted-origins {:optional true} [::sm/set :string]]
|
||||
|
||||
[:exporter-shared-key {:optional true} :string]
|
||||
[:admin-console-shared-key {:optional true} :string]
|
||||
[:nexus-shared-key {:optional true} :string]
|
||||
@ -430,6 +441,54 @@
|
||||
(def explain-config
|
||||
(sm/explainer schema:config))
|
||||
|
||||
(defn- parse-origin
|
||||
[origin]
|
||||
(when (string? origin)
|
||||
(try
|
||||
(let [uri (URI. (-> origin str/trim str/lower))
|
||||
scheme (.getScheme uri)
|
||||
host (.getHost uri)
|
||||
port (.getPort uri)]
|
||||
(when (and (#{"http" "https"} scheme)
|
||||
(some? host)
|
||||
(<= -1 port 65535)
|
||||
(nil? (.getRawUserInfo uri))
|
||||
(empty? (.getRawPath uri))
|
||||
(nil? (.getRawQuery uri))
|
||||
(nil? (.getRawFragment uri))
|
||||
(not (str/ends-with? (.getRawAuthority uri) ":")))
|
||||
uri))
|
||||
(catch URISyntaxException _ nil))))
|
||||
|
||||
(defn- origin-string
|
||||
[^URI uri]
|
||||
(let [scheme (.getScheme uri)
|
||||
port (.getPort uri)]
|
||||
(str scheme "://" (.getHost uri)
|
||||
(when (and (not= -1 port)
|
||||
(not= port (if (= scheme "https") 443 80)))
|
||||
(str ":" port)))))
|
||||
|
||||
(defn- normalize-origin
|
||||
"Return the canonical string for a bare HTTP(S) origin, or nil."
|
||||
[origin]
|
||||
(some-> origin parse-origin origin-string))
|
||||
|
||||
(defn- prepare-trusted-origins
|
||||
[config]
|
||||
(if-some [origins (:trusted-origins config)]
|
||||
(let [parsed (mapv parse-origin origins)]
|
||||
(when (some nil? parsed)
|
||||
(l/wrn :hint "ignoring malformed entries in PENPOT_TRUSTED_ORIGINS (expected http(s)://host[:port])"))
|
||||
(when (some (fn [^URI uri]
|
||||
(and (some? uri)
|
||||
(= "http" (.getScheme uri))
|
||||
(not= "localhost" (.getHost uri))))
|
||||
parsed)
|
||||
(l/wrn :hint "unencrypted HTTP origins in PENPOT_TRUSTED_ORIGINS; use HTTPS outside localhost"))
|
||||
(assoc config :trusted-origins (into #{} (comp (remove nil?) (map origin-string)) parsed)))
|
||||
config))
|
||||
|
||||
(defn- normalize-file-data-backend
|
||||
"The file data moved to `file_data` (migration `0157-migrate-legacy-file-data`), so
|
||||
`file.data` and `file_change.data` are read-only leftovers and the `legacy-db`
|
||||
@ -454,7 +513,8 @@
|
||||
(merge default)
|
||||
(normalize-tenant)
|
||||
(decode-config)
|
||||
(normalize-file-data-backend)))
|
||||
(normalize-file-data-backend)
|
||||
(prepare-trusted-origins)))
|
||||
|
||||
(def version
|
||||
(v/parse (or (some-> (io/resource "version.txt")
|
||||
@ -547,6 +607,31 @@
|
||||
(or (c/get config :jobs-user-ttl)
|
||||
(ct/duration {:days 7})))
|
||||
|
||||
(defn get-trusted-origin
|
||||
"Return the normalized origin if it is in the prepared allowlist."
|
||||
[origin]
|
||||
(when-let [origin (normalize-origin origin)]
|
||||
(when (contains? (:trusted-origins config) origin)
|
||||
origin)))
|
||||
|
||||
(defn with-public-origin
|
||||
"Apply a trusted origin to the public URI without replacing its path."
|
||||
[origin config]
|
||||
(if (some? origin)
|
||||
(let [{:keys [scheme host port]} (u/uri origin)]
|
||||
(update config :public-uri
|
||||
#(assoc (u/uri %) :scheme scheme :host host :port port)))
|
||||
config))
|
||||
|
||||
(defn with-public-uri
|
||||
"Replace the full :public-uri with an already resolved `base`, as used
|
||||
by export jobs. Leave `config` unchanged when `base` is nil. Use
|
||||
`with-public-origin` to change only the origin and keep the public path."
|
||||
[base config]
|
||||
(if (some? base)
|
||||
(assoc config :public-uri (u/uri base))
|
||||
config))
|
||||
|
||||
(defn get
|
||||
"A configuration getter. Helps code be more testable."
|
||||
([key]
|
||||
|
||||
@ -228,9 +228,13 @@
|
||||
|
||||
(defn- build-email-template
|
||||
[id context]
|
||||
(let [subj (render-email-template-part :subj id context)
|
||||
text (render-email-template-part :txt id context)
|
||||
html (render-email-template-part :html id context)]
|
||||
;; Templates supply the slash before both links and assets.
|
||||
(let [context (cond-> context
|
||||
(some? (:public-uri context))
|
||||
(update :public-uri #(str/rtrim (str %) "/")))
|
||||
subj (render-email-template-part :subj id context)
|
||||
text (render-email-template-part :txt id context)
|
||||
html (render-email-template-part :html id context)]
|
||||
(when (or (not subj)
|
||||
(and (not text)
|
||||
(not html)))
|
||||
|
||||
@ -253,19 +253,27 @@
|
||||
[_ params]
|
||||
(assert (sm/check schema:router-params params)))
|
||||
|
||||
(defn- root-middleware
|
||||
"Middleware chain for routes under the root group. MCP OAuth uses its
|
||||
own chain. Defined as a function so tests can check that the trusted-origin
|
||||
middleware is registered and wraps the middleware that follows it."
|
||||
[cfg]
|
||||
[[mw/server-timing]
|
||||
[mw/trusted-origin]
|
||||
[sec/sec-fetch-metadata]
|
||||
[mw/params]
|
||||
[mw/format-response]
|
||||
[mw/auth {:bearer (partial session/decode-token cfg)
|
||||
:cookie (partial session/decode-token cfg)
|
||||
:token (partial actoken/decode-token cfg)}]
|
||||
[mw/parse-request (::mtx/metrics cfg)]
|
||||
[mw/errors errors/handle]
|
||||
[mw/restrict-methods]])
|
||||
|
||||
(defmethod ig/init-key ::router
|
||||
[_ cfg]
|
||||
(rr/router
|
||||
[["" {:middleware [[mw/server-timing]
|
||||
[sec/sec-fetch-metadata]
|
||||
[mw/params]
|
||||
[mw/format-response]
|
||||
[mw/auth {:bearer (partial session/decode-token cfg)
|
||||
:cookie (partial session/decode-token cfg)
|
||||
:token (partial actoken/decode-token cfg)}]
|
||||
[mw/parse-request (::mtx/metrics cfg)]
|
||||
[mw/errors errors/handle]
|
||||
[mw/restrict-methods]]}
|
||||
[["" {:middleware (root-middleware cfg)}
|
||||
|
||||
(::mtx/routes cfg)
|
||||
(::assets/routes cfg)
|
||||
|
||||
@ -35,6 +35,30 @@
|
||||
{:name ::server-timing
|
||||
:compile (constantly ymw/wrap-server-timing)})
|
||||
|
||||
(defn- resolve-trusted-origin
|
||||
"Prefer the `x-penpot-origin` header sent by the frontend; fall back to
|
||||
the browser's `origin` header. Both are checked against the same
|
||||
allowlist, so neither can widen the base on its own."
|
||||
[request]
|
||||
(or (cf/get-trusted-origin (yreq/get-header request "x-penpot-origin"))
|
||||
(cf/get-trusted-origin (yreq/get-header request "origin"))))
|
||||
|
||||
(defn wrap-trusted-origin
|
||||
"When the request carries a trusted origin, stamp it on the request and
|
||||
bind the config :public-uri to it for the dynamic extent of the request.
|
||||
Otherwise the request is left untouched and the canonical :public-uri
|
||||
is used."
|
||||
[handler]
|
||||
(fn [request]
|
||||
(if-let [origin (resolve-trusted-origin request)]
|
||||
(binding [cf/config (cf/with-public-origin origin cf/config)]
|
||||
(handler (assoc request ::http/trusted-origin origin)))
|
||||
(handler request))))
|
||||
|
||||
(def trusted-origin
|
||||
{:name ::trusted-origin
|
||||
:compile (constantly wrap-trusted-origin)})
|
||||
|
||||
(def params
|
||||
{:name ::params
|
||||
:compile (constantly ymw/wrap-params)})
|
||||
@ -298,7 +322,7 @@
|
||||
(assoc "access-control-allow-credentials" "true")
|
||||
(assoc "access-control-allow-methods" "GET,POST,DELETE,OPTIONS,PUT,HEAD,PATCH")
|
||||
(assoc "access-control-expose-headers" "content-type, retry-after, x-rate-limit-remaining, x-rate-limit-reset")
|
||||
(assoc "access-control-allow-headers" "x-frontend-version, x-client, content-type, accept"))))
|
||||
(assoc "access-control-allow-headers" "x-frontend-version, x-client, x-penpot-origin, content-type, accept"))))
|
||||
|
||||
(defn wrap-cors
|
||||
[handler allowed]
|
||||
|
||||
@ -52,7 +52,10 @@
|
||||
{::yres/headers default-headers
|
||||
::yres/status 200
|
||||
::yres/body (yres/stream-body
|
||||
(fn [_ output]
|
||||
;; The body runs after the request handler has returned, so
|
||||
;; capture its dynamic bindings (notably the effective
|
||||
;; :public-uri) to keep links on the requesting origin.
|
||||
(bound-fn [_ output]
|
||||
|
||||
(let [channel (sp/chan :buf buf :xf (keep encode))
|
||||
listener (events/spawn-listener
|
||||
|
||||
@ -21,6 +21,7 @@
|
||||
[app.common.exceptions :as ex]
|
||||
[app.common.logging :as l]
|
||||
[app.common.time :as ct]
|
||||
[app.common.uri :as u]
|
||||
[app.config :as cf]
|
||||
[app.db :as db]
|
||||
[app.storage :as sto]
|
||||
@ -28,9 +29,14 @@
|
||||
|
||||
(defn- resource-uri
|
||||
"The url a user downloads the artifact from. A string, because the
|
||||
descriptor ends up in the JSON result of the job."
|
||||
[id]
|
||||
(cf/get-public-uri "assets/by-id/" (str id)))
|
||||
descriptor ends up in the JSON result of the job. A base passed by the
|
||||
caller is bound as the effective public URI: the job runs outside the
|
||||
request that created it."
|
||||
[base id]
|
||||
(if (some? base)
|
||||
(binding [cf/config (cf/with-public-uri (u/uri base) cf/config)]
|
||||
(cf/get-public-uri "assets/by-id/" (str id)))
|
||||
(cf/get-public-uri "assets/by-id/" (str id))))
|
||||
|
||||
(defn put-resource
|
||||
"Store an artifact of a job in the `job-resource` bucket and return the
|
||||
@ -42,6 +48,8 @@
|
||||
temporary file or from bytes in memory
|
||||
- `:filename` the name the user will see
|
||||
- `:mtype` the content type of the artifact
|
||||
- `:public-uri` the base for the download URI, captured when the job was
|
||||
created (nil keeps the canonical base)
|
||||
|
||||
`profile-id` is the owner of the object: the profile that owns the job,
|
||||
for both the package a job consumes and the artifact it produces.
|
||||
@ -50,7 +58,7 @@
|
||||
row ever references (a crash between the upload and the completion) is
|
||||
reclaimed by the storage GC instead of leaking; while a row references
|
||||
it, `storage-gc-touched` freezes it."
|
||||
[cfg profile-id {:keys [content filename mtype]}]
|
||||
[cfg profile-id {:keys [content filename mtype public-uri]}]
|
||||
(assert (uuid? profile-id) "expected the profile that owns the resource")
|
||||
(assert (string? mtype) "expected the content type of the resource")
|
||||
(let [storage (sto/resolve cfg)
|
||||
@ -61,7 +69,7 @@
|
||||
:profile-id profile-id
|
||||
:content-type mtype})]
|
||||
{:resource-id (:id object)
|
||||
:resource-uri (resource-uri (:id object))
|
||||
:resource-uri (resource-uri public-uri (:id object))
|
||||
:filename filename
|
||||
:mtype mtype
|
||||
:size (:size object)}))
|
||||
|
||||
@ -7,10 +7,11 @@
|
||||
(ns app.rpc.commands.jobs
|
||||
"Creation of durable, user-facing jobs.
|
||||
|
||||
One command per job type: the body carries the business params its
|
||||
job-def declares and nothing else, and the job-def schema is the single
|
||||
place that says what those params are. Creating a job never runs it: it
|
||||
freezes what the job will do, and the work belongs to the runner."
|
||||
One command per job type. The creation schema defines what the caller may
|
||||
send; the job-def schema defines the params stored for the runner. A command
|
||||
may add server-owned params after validating the request. Creating a job
|
||||
never runs it: it freezes what the job will do, and the work belongs to the
|
||||
runner."
|
||||
(:require
|
||||
[app.binfile.common :as bfc]
|
||||
[app.binfile.v3 :as bf.v3]
|
||||
@ -39,10 +40,10 @@
|
||||
|
||||
(def ^:private schema:create-export-binfile-job
|
||||
"The `.penpot` package of the files frozen in the params, produced by
|
||||
the backend runner; the business params are what the `:export-binfile`
|
||||
job-def declares."
|
||||
the backend runner; the caller's params are the public subset of the
|
||||
`:export-binfile` job-def params."
|
||||
[:map {:title "create-export-binfile-job" :closed true}
|
||||
[:params export-binfile/schema:params]])
|
||||
[:params export-binfile/schema:create-params]])
|
||||
|
||||
(def ^:private schema:create-import-binfile-job
|
||||
"The `.penpot` package the caller uploaded, imported into a project by
|
||||
@ -147,11 +148,18 @@
|
||||
::sm/params schema:create-export-binfile-job
|
||||
::sm/result schema:job-summary}
|
||||
[cfg {:keys [::rpc/profile-id] :as envelope}]
|
||||
(let [job-def (resolve-job-def cfg :export :export-binfile)
|
||||
;; the RPC layer decoded the params against the job-def schema
|
||||
;; before the command ran
|
||||
params (jobs/validate-params job-def (:params envelope))
|
||||
file-ids (:file-ids params)]
|
||||
(let [job-def (resolve-job-def cfg :export :export-binfile)
|
||||
;; The job runs after the request, so the base its download link
|
||||
;; must use travels in the frozen params instead of a thread binding.
|
||||
base (when (-> (meta envelope)
|
||||
(get :app.http/request)
|
||||
(:app.http/trusted-origin))
|
||||
(str (cf/get :public-uri)))
|
||||
;; The RPC decoded the public creation params. Validate them against
|
||||
;; the stored job schema before adding the backend-owned base URI.
|
||||
params (cond-> (jobs/validate-params job-def (:params envelope))
|
||||
(some? base) (assoc :public-uri base))
|
||||
file-ids (:file-ids params)]
|
||||
|
||||
(when (empty? file-ids)
|
||||
(ex/raise :type :validation
|
||||
|
||||
@ -756,7 +756,10 @@
|
||||
cfg sso
|
||||
:query-string query-string
|
||||
:organization-id organization-id
|
||||
:profile-id profile-id)
|
||||
:profile-id profile-id
|
||||
;; Trusted alternate origin stamped by the
|
||||
;; http trusted-origin middleware.
|
||||
:origin (:app.http/trusted-origin request))
|
||||
organization-id (or organization-id (:organization-id sso))]
|
||||
(oidc/submit-organization-sso-auth-started-event
|
||||
cfg request profile-id organization-id)
|
||||
|
||||
@ -24,11 +24,18 @@
|
||||
|
||||
(def schema:params
|
||||
"Business params of an export: the files to export, frozen when the job
|
||||
was created, and how their libraries are handled."
|
||||
was created, how their libraries are handled, and the base URI the
|
||||
download link must use once the job runs outside the request."
|
||||
[:map {:title "export-binfile-params" :closed true}
|
||||
[:file-ids [::sm/set ::sm/uuid]]
|
||||
[:export-type [::sm/one-of #{:include-libraries :merge-libraries
|
||||
:detach-libraries :link-later}]]])
|
||||
:detach-libraries :link-later}]]
|
||||
[:public-uri {:optional true} ::sm/text]])
|
||||
|
||||
(def schema:create-params
|
||||
"Business params an export caller may provide. The backend adds the base
|
||||
URI after validating the request origin."
|
||||
(sm/dissoc-key schema:params :public-uri))
|
||||
|
||||
(def ^:private artifact
|
||||
"What the user sees of the package an export produces. A single name
|
||||
@ -73,7 +80,9 @@
|
||||
(try
|
||||
(bfj/check-active cfg context)
|
||||
(bfj/run cfg context bf.v3/export-files!)
|
||||
(let [resource (->> (assoc artifact :content (sto/content output))
|
||||
(let [resource (->> (assoc artifact
|
||||
:content (sto/content output)
|
||||
:public-uri (:public-uri params))
|
||||
(js/put-resource cfg profile-id))
|
||||
result (check-result (dissoc resource :resource-id))]
|
||||
{:result result
|
||||
|
||||
@ -13,7 +13,11 @@
|
||||
[app.common.uri :as u]
|
||||
[app.common.uuid :as uuid]
|
||||
[app.config :as cf]
|
||||
[app.http :as-alias http]
|
||||
[app.http.middleware :as mw]
|
||||
[app.http.session :as session]
|
||||
[app.rpc :as-alias rpc]
|
||||
[app.rpc.commands.nitrate :as nitrate-rpc]
|
||||
[app.setup :as-alias setup]
|
||||
[app.tokens :as tokens]
|
||||
[clojure.test :as t]
|
||||
@ -158,6 +162,13 @@
|
||||
(t/is (.contains loc "error=auth-error"))
|
||||
(t/is (not (.contains loc "hint=")))))))
|
||||
|
||||
(t/deftest redirect-with-error-preserves-public-uri-subpath
|
||||
(binding [cf/config {:public-uri "http://localhost:3449/penpot"}]
|
||||
(let [result (#'oidc/redirect-with-error "auth-error")
|
||||
loc (get-in result [::yres/headers "location"])]
|
||||
(t/is (.contains loc "http://localhost:3449/penpot?screen=auth-login&"))
|
||||
(t/is (.contains loc "error=auth-error")))))
|
||||
|
||||
(t/deftest redirect-to-verify-token-builds-verify-url
|
||||
(binding [cf/config {:public-uri "http://localhost:3449"}]
|
||||
(let [result (#'oidc/redirect-to-verify-token "test-token-value")
|
||||
@ -166,11 +177,67 @@
|
||||
(t/is (.contains loc "http://localhost:3449?screen=auth-verify-token&"))
|
||||
(t/is (.contains loc "token=test-token-value")))))
|
||||
|
||||
(t/deftest redirect-to-verify-token-preserves-public-uri-subpath
|
||||
(binding [cf/config {:public-uri "http://localhost:3449/penpot"}]
|
||||
(let [result (#'oidc/redirect-to-verify-token "test-token-value")
|
||||
loc (get-in result [::yres/headers "location"])]
|
||||
(t/is (.contains loc "http://localhost:3449/penpot?screen=auth-verify-token&")))))
|
||||
|
||||
(t/deftest build-redirect-uri-constructs-redirect
|
||||
(binding [cf/config {:public-uri "http://localhost:3449"}]
|
||||
(t/is (= "http://localhost:3449/api/auth/oidc/callback"
|
||||
(#'oidc/build-redirect-uri)))))
|
||||
|
||||
(t/deftest build-redirect-uri-preserves-public-uri-subpath
|
||||
(binding [cf/config {:public-uri "http://localhost:3449/penpot"}]
|
||||
(t/is (= "http://localhost:3449/penpot/api/auth/oidc/callback"
|
||||
(#'oidc/build-redirect-uri)))))
|
||||
|
||||
(t/deftest build-redirect-uri-with-subpath-and-trailing-slash
|
||||
(binding [cf/config {:public-uri "http://localhost:3449/penpot/"}]
|
||||
(t/is (= "http://localhost:3449/penpot/api/auth/oidc/callback"
|
||||
(#'oidc/build-redirect-uri)))))
|
||||
|
||||
(t/deftest redirect-with-error-subpath-screen-query
|
||||
(binding [cf/config {:public-uri "http://localhost:3449/penpot"}]
|
||||
(let [result (#'oidc/redirect-with-error "auth-error" "hint message")
|
||||
loc (get-in result [::yres/headers "location"])]
|
||||
(t/is (.contains loc "http://localhost:3449/penpot?screen=auth-login&"))
|
||||
(t/is (.contains loc "error=auth-error"))
|
||||
(t/is (.contains loc "hint=hint"))
|
||||
;; Screen routing lives in the query string, not the fragment
|
||||
(t/is (not (.contains loc "#"))))))
|
||||
|
||||
(t/deftest redirect-to-register-subpath
|
||||
(let [test-key (byte-array (map byte (range 32)))
|
||||
cfg {::setup/props {:tokens-key test-key}}]
|
||||
(binding [cf/config {:public-uri "http://localhost:3449/penpot"}]
|
||||
(let [info {:email "u@e.com" :fullname "U" :backend "oidc"
|
||||
:email-verified false :props {}}
|
||||
provider {:type "oidc" :id "oidc"}
|
||||
result (#'oidc/redirect-to-register cfg info provider)
|
||||
loc (get-in result [::yres/headers "location"])]
|
||||
(t/is (.contains loc "http://localhost:3449/penpot?screen=auth-register-validate&"))
|
||||
(t/is (.contains loc "token="))))))
|
||||
|
||||
(t/deftest redirect-to-register-no-subpath
|
||||
(let [test-key (byte-array (map byte (range 32)))
|
||||
cfg {::setup/props {:tokens-key test-key}}]
|
||||
(binding [cf/config {:public-uri "http://localhost:3449"}]
|
||||
(let [info {:email "u@e.com" :fullname "U" :backend "oidc"
|
||||
:email-verified false :props {}}
|
||||
provider {:type "oidc" :id "oidc"}
|
||||
result (#'oidc/redirect-to-register cfg info provider)
|
||||
loc (get-in result [::yres/headers "location"])]
|
||||
(t/is (.contains loc "http://localhost:3449?screen=auth-register-validate&"))
|
||||
(t/is (.contains loc "token="))))))
|
||||
|
||||
(t/deftest redirect-to-verify-token-subpath-no-trailing-slash
|
||||
(binding [cf/config {:public-uri "http://localhost:3449/my-app"}]
|
||||
(let [result (#'oidc/redirect-to-verify-token "test-token-value")
|
||||
loc (get-in result [::yres/headers "location"])]
|
||||
(t/is (.contains loc "http://localhost:3449/my-app?screen=auth-verify-token&")))))
|
||||
|
||||
(t/deftest fetch-user-info-returns-decoded-body-on-success
|
||||
(let [cfg {}
|
||||
provider {:user-uri "https://provider.example.com/userinfo"}
|
||||
@ -553,7 +620,7 @@
|
||||
(let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist)
|
||||
state (make-state-token cfg {})
|
||||
request (default-request cfg :state state)]
|
||||
(binding [cf/config {:public-uri "http://localhost:3449"}
|
||||
(binding [cf/config {:public-uri "http://localhost:3449/penpot"}
|
||||
cf/flags #{:registration}]
|
||||
(with-redefs [app.auth.oidc/resolve-provider (constantly {:type "oidc" :id "oidc"})
|
||||
app.auth.oidc/get-info (constantly {:email "u@e.com" :fullname "U"
|
||||
@ -562,7 +629,7 @@
|
||||
app.auth.oidc/get-profile (constantly (assoc test-profile :is-active false))]
|
||||
(let [result (#'oidc/callback-handler cfg request)
|
||||
loc (redirect-location result)]
|
||||
(t/is (.contains loc "http://localhost:3449?screen=auth-register-validate&"))
|
||||
(t/is (.contains loc "http://localhost:3449/penpot?screen=auth-register-validate&"))
|
||||
(t/is (.contains loc "token=")))))))
|
||||
|
||||
(t/deftest callback-success-flow
|
||||
@ -1032,3 +1099,333 @@
|
||||
(t/is (ex/error? e))
|
||||
(t/is (= :validation (:type (ex-data e))))
|
||||
(t/is (= :invalid-sso-config (:code (ex-data e))))))))
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; trusted alternate origins
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
(def ^:private trusted-origin-provider
|
||||
{:id "oidc"
|
||||
:type "oidc"
|
||||
:auth-uri "https://idp.example.com/auth"
|
||||
:client-id "test-client"
|
||||
:scopes ["openid"]})
|
||||
|
||||
(t/deftest auth-handler-carries-trusted-origin-in-state
|
||||
(with-redefs [app.auth.oidc/resolve-provider (constantly trusted-origin-provider)
|
||||
app.loggers.audit/extract-utm-params (constantly {})
|
||||
app.loggers.audit/get-external-session-id (constantly nil)]
|
||||
(t/testing "trusted origin is stored in the state and used for redirect_uri"
|
||||
(let [request (assoc {:params {}} :app.http/trusted-origin "https://alt.example.com")
|
||||
result (binding [cf/config {:public-uri "https://alt.example.com"
|
||||
:trusted-origins #{"https://alt.example.com"}}]
|
||||
(#'oidc/auth-handler base-cfg request))
|
||||
uri (get-in result [::yres/body :redirect-uri])
|
||||
query (u/query-string->map (:query (u/uri uri)))
|
||||
claims (tokens/verify base-cfg {:token (:state query) :iss "oidc"})]
|
||||
(t/is (= "https://alt.example.com" (:origin claims)))
|
||||
(t/is (= "https://alt.example.com/api/auth/oidc/callback" (:redirect_uri query)))))
|
||||
|
||||
(t/testing "without a trusted origin no :origin claim is stored"
|
||||
(let [result (binding [cf/config {:public-uri "http://localhost:3449"
|
||||
:trusted-origins #{"https://alt.example.com"}}]
|
||||
(#'oidc/auth-handler base-cfg {:params {}}))
|
||||
uri (get-in result [::yres/body :redirect-uri])
|
||||
query (u/query-string->map (:query (u/uri uri)))
|
||||
claims (tokens/verify base-cfg {:token (:state query) :iss "oidc"})]
|
||||
(t/is (not (contains? claims :origin)))
|
||||
(t/is (= "http://localhost:3449/api/auth/oidc/callback" (:redirect_uri query)))))))
|
||||
|
||||
(t/deftest build-organization-sso-auth-redirect-uri-stores-trusted-origin
|
||||
(let [sso {:organization-id test-organization-id
|
||||
:issuer "https://idp.example.com"
|
||||
:client-id "test-client"
|
||||
:client-secret "test-secret"}
|
||||
provider trusted-origin-provider
|
||||
uri (binding [cf/config {:public-uri "https://alt.example.com"
|
||||
:trusted-origins #{"https://alt.example.com"}}]
|
||||
(oidc/build-organization-sso-auth-redirect-uri
|
||||
base-cfg sso
|
||||
:query-string "screen=dashboard"
|
||||
:organization-id test-organization-id
|
||||
:provider provider
|
||||
:origin "https://alt.example.com"))
|
||||
query (u/query-string->map (:query (u/uri uri)))
|
||||
claims (tokens/verify base-cfg {:token (:state query) :iss "oidc"})]
|
||||
(t/is (= "https://alt.example.com" (:origin claims)))
|
||||
(t/is (= "https://alt.example.com/?screen=dashboard" (:dest-url claims)))
|
||||
(t/is (= "https://alt.example.com/api/auth/oidc/callback" (:redirect_uri query)))))
|
||||
|
||||
(t/deftest callback-applies-stored-trusted-origin
|
||||
(let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist)
|
||||
seen (atom nil)
|
||||
state (make-state-token cfg {:origin "https://alt.example.com"})
|
||||
request (default-request cfg :state state)]
|
||||
(binding [cf/config {:public-uri "http://localhost:3449"
|
||||
:trusted-origins #{"https://alt.example.com"}}]
|
||||
(with-redefs [app.auth.oidc/resolve-provider (constantly {:type "oidc" :id "oidc"})
|
||||
app.auth.oidc/get-info (fn [_ _ _ _]
|
||||
(reset! seen (cf/get :public-uri))
|
||||
{:email "u@e.com" :fullname "U"
|
||||
:backend "oidc" :email-verified false
|
||||
:props {}})
|
||||
app.auth.oidc/get-profile (constantly test-profile)
|
||||
app.auth.oidc/update-profile-with-info (fn [_ profile _] profile)
|
||||
app.loggers.audit/submit (constantly nil)]
|
||||
(let [result (#'oidc/callback-handler cfg request)
|
||||
loc (redirect-location result)]
|
||||
(t/is (= "https://alt.example.com" (str @seen)))
|
||||
(t/is (.contains loc "https://alt.example.com?screen=auth-verify-token&")))))))
|
||||
|
||||
(t/deftest callback-token-exchange-uses-stored-trusted-origin
|
||||
;; Unlike callback-applies-stored-trusted-origin, this drives the real
|
||||
;; token exchange (mocking app.http.client/req instead of get-info) so
|
||||
;; the redirect_uri sent to the provider is asserted, not only the
|
||||
;; auth-request one and the post-exchange redirect.
|
||||
(let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist)
|
||||
bodies (atom [])
|
||||
provider {:type "oidc" :id "oidc"
|
||||
:user-info-source "userinfo"
|
||||
:token-uri "https://idp.example.com/token"
|
||||
:user-uri "https://idp.example.com/userinfo"}
|
||||
state (make-state-token cfg {:origin "https://alt.example.com"})
|
||||
request (default-request cfg :state state)]
|
||||
(binding [cf/config {:public-uri "http://localhost:3449"
|
||||
:trusted-origins #{"https://alt.example.com"}}]
|
||||
(with-redefs [app.auth.oidc/resolve-provider (constantly provider)
|
||||
app.auth.oidc/get-profile (constantly test-profile)
|
||||
app.auth.oidc/update-profile-with-info (fn [_ profile _] profile)
|
||||
app.loggers.audit/submit (constantly nil)]
|
||||
(with-mocks [http-mock {:target 'app.http.client/req
|
||||
:return (fn [_ request & _]
|
||||
(swap! bodies conj request)
|
||||
(if (= (:uri request) (:token-uri provider))
|
||||
{:status 200
|
||||
:body "{\"access_token\":\"at\",\"token_type\":\"Bearer\"}"}
|
||||
{:status 200
|
||||
:body "{\"email\":\"u@e.com\",\"name\":\"U\"}"}))}]
|
||||
(let [result (#'oidc/callback-handler cfg request)
|
||||
token-body (->> @bodies
|
||||
(filter #(= (:uri %) (:token-uri provider)))
|
||||
(first)
|
||||
(:body)
|
||||
(u/query-string->map))]
|
||||
(t/is (= "https://alt.example.com/api/auth/oidc/callback"
|
||||
(:redirect_uri token-body)))
|
||||
(t/is (.contains (redirect-location result)
|
||||
"https://alt.example.com?screen=auth-verify-token&"))))))))
|
||||
|
||||
(t/deftest callback-token-exchange-keeps-stored-origin-after-removal
|
||||
;; Mirror of callback-token-exchange-uses-stored-trusted-origin with the
|
||||
;; origin removed from :trusted-origins: the signed state was trusted when
|
||||
;; the flow started, so the token exchange still uses it (up to its
|
||||
;; expiry), matching the documented operator contract.
|
||||
(let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist)
|
||||
bodies (atom [])
|
||||
provider {:type "oidc" :id "oidc"
|
||||
:user-info-source "userinfo"
|
||||
:token-uri "https://idp.example.com/token"
|
||||
:user-uri "https://idp.example.com/userinfo"}
|
||||
state (make-state-token cfg {:origin "https://alt.example.com"})
|
||||
request (default-request cfg :state state)]
|
||||
(binding [cf/config {:public-uri "http://localhost:3449"
|
||||
:trusted-origins #{}}]
|
||||
(with-redefs [app.auth.oidc/resolve-provider (constantly provider)
|
||||
app.auth.oidc/get-profile (constantly test-profile)
|
||||
app.auth.oidc/update-profile-with-info (fn [_ profile _] profile)
|
||||
app.loggers.audit/submit (constantly nil)]
|
||||
(with-mocks [http-mock {:target 'app.http.client/req
|
||||
:return (fn [_ request & _]
|
||||
(swap! bodies conj request)
|
||||
(if (= (:uri request) (:token-uri provider))
|
||||
{:status 200
|
||||
:body "{\"access_token\":\"at\",\"token_type\":\"Bearer\"}"}
|
||||
{:status 200
|
||||
:body "{\"email\":\"u@e.com\",\"name\":\"U\"}"}))}]
|
||||
(let [result (#'oidc/callback-handler cfg request)
|
||||
token-body (->> @bodies
|
||||
(filter #(= (:uri %) (:token-uri provider)))
|
||||
(first)
|
||||
(:body)
|
||||
(u/query-string->map))]
|
||||
(t/is (= "https://alt.example.com/api/auth/oidc/callback"
|
||||
(:redirect_uri token-body)))
|
||||
(t/is (.contains (redirect-location result)
|
||||
"https://alt.example.com?screen=auth-verify-token&"))))))))
|
||||
|
||||
(t/deftest callback-error-uses-stored-trusted-origin
|
||||
(let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist)
|
||||
state (make-state-token cfg {:origin "https://alt.example.com"})
|
||||
request (assoc (default-request cfg :state state)
|
||||
:params {:state state :error "access_denied"})]
|
||||
(binding [cf/config {:public-uri "http://localhost:3449"
|
||||
:trusted-origins #{"https://alt.example.com"}}]
|
||||
(let [result (#'oidc/callback-handler cfg request)
|
||||
loc (redirect-location result)]
|
||||
(t/is (.contains loc "https://alt.example.com?screen=auth-login&"))
|
||||
(t/is (.contains loc "error=unable-to-auth"))))))
|
||||
|
||||
(t/deftest callback-honors-state-origin-even-when-not-in-config
|
||||
;; The signed state origin was trusted when the flow started; it is used
|
||||
;; as-is for the lifetime of the token, even if the operator removed it.
|
||||
(let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist)
|
||||
state (make-state-token cfg {:origin "https://alt.example.com"})
|
||||
request (default-request cfg :state state)]
|
||||
(binding [cf/config {:public-uri "http://localhost:3449"
|
||||
:trusted-origins #{}}]
|
||||
(with-redefs [app.auth.oidc/resolve-provider (constantly {:type "oidc" :id "oidc"})
|
||||
app.auth.oidc/get-info (constantly {:email "u@e.com" :fullname "U"
|
||||
:backend "oidc" :email-verified false
|
||||
:props {}})
|
||||
app.auth.oidc/get-profile (constantly test-profile)
|
||||
app.auth.oidc/update-profile-with-info (fn [_ profile _] profile)
|
||||
app.loggers.audit/submit (constantly nil)]
|
||||
(let [result (#'oidc/callback-handler cfg request)
|
||||
loc (redirect-location result)]
|
||||
(t/is (.contains loc "https://alt.example.com?screen=auth-verify-token&")))))))
|
||||
|
||||
(t/deftest callback-without-state-redirects-to-canonical-error
|
||||
(let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist)
|
||||
request {:params {}}]
|
||||
(binding [cf/config {:public-uri "http://localhost:3449"
|
||||
:trusted-origins #{"https://alt.example.com"}}]
|
||||
(let [result (#'oidc/callback-handler cfg request)
|
||||
loc (redirect-location result)]
|
||||
(t/is (= 302 (::yres/status result)))
|
||||
(t/is (.contains loc "http://localhost:3449?screen=auth-login&"))
|
||||
(t/is (.contains loc "error=unable-to-auth"))))))
|
||||
|
||||
(defn- get-uri-query
|
||||
[uri]
|
||||
(u/query-string->map (:query (u/uri uri))))
|
||||
|
||||
(t/deftest oidc-round-trip-preserves-the-alternate-public-subpath
|
||||
(let [cfg (-> base-cfg
|
||||
(dissoc :app.email/blacklist :app.email/whitelist)
|
||||
(assoc ::session/manager (session/inmemory-manager)))
|
||||
provider (assoc trusted-origin-provider
|
||||
:user-info-source "userinfo"
|
||||
:token-uri "https://idp.example.com/token"
|
||||
:user-uri "https://idp.example.com/userinfo")
|
||||
public-config {:public-uri "http://localhost:3449/penpot"
|
||||
:trusted-origins #{"https://alt.example.com"}}
|
||||
authorize (mw/wrap-trusted-origin (partial #'oidc/auth-handler cfg))
|
||||
callback (mw/wrap-trusted-origin (partial #'oidc/callback-handler cfg))
|
||||
token-request (atom nil)]
|
||||
(with-redefs [app.auth.oidc/resolve-provider (constantly provider)
|
||||
app.auth.oidc/get-profile (constantly test-profile)
|
||||
app.auth.oidc/update-profile-with-info (fn [_ profile _] profile)
|
||||
app.loggers.audit/submit (constantly nil)]
|
||||
(with-mocks [http-mock {:target 'app.http.client/req
|
||||
:return (fn [_ request & _]
|
||||
(case (:uri request)
|
||||
"https://idp.example.com/token"
|
||||
(do (reset! token-request request)
|
||||
{:status 200
|
||||
:body "{\"access_token\":\"at\",\"token_type\":\"Bearer\"}"})
|
||||
|
||||
"https://idp.example.com/userinfo"
|
||||
{:status 200
|
||||
:body "{\"email\":\"u@e.com\",\"name\":\"U\"}"}))}]
|
||||
(let [auth-response (binding [cf/config public-config]
|
||||
(authorize {:params {}
|
||||
:headers {"x-penpot-origin" "https://alt.example.com"}}))
|
||||
auth-query (get-uri-query (get-in auth-response [::yres/body :redirect-uri]))
|
||||
state (:state auth-query)
|
||||
claims (tokens/verify cfg {:token state :iss "oidc"})
|
||||
request (default-request cfg :state state)]
|
||||
(t/is (= "https://alt.example.com" (:origin claims)))
|
||||
(t/is (= "https://alt.example.com/penpot/api/auth/oidc/callback"
|
||||
(:redirect_uri auth-query)))
|
||||
|
||||
(t/testing "the headerless callback uses the same redirect_uri even after alias removal"
|
||||
(binding [cf/config (assoc public-config :trusted-origins #{})]
|
||||
(let [response (callback request)
|
||||
location (redirect-location response)
|
||||
token-form (u/query-string->map (:body @token-request))]
|
||||
(t/is (= :post (:method @token-request)))
|
||||
(t/is (= (:redirect_uri auth-query) (:redirect_uri token-form)))
|
||||
(t/is (= 302 (::yres/status response)))
|
||||
(t/is (= "https://alt.example.com/penpot"
|
||||
(str (assoc (u/uri location) :query nil))))
|
||||
(t/is (= "auth-verify-token" (:screen (get-uri-query location)))))))
|
||||
|
||||
(t/testing "a provider error still redirects under the alias subpath"
|
||||
(binding [cf/config public-config]
|
||||
(let [response (callback (assoc-in request [:params :error] "access_denied"))
|
||||
location (redirect-location response)]
|
||||
(t/is (= 302 (::yres/status response)))
|
||||
(t/is (= "https://alt.example.com/penpot"
|
||||
(str (assoc (u/uri location) :query nil))))
|
||||
(t/is (= {:screen "auth-login" :error "unable-to-auth" :hint "access_denied"}
|
||||
(get-uri-query location))))))
|
||||
|
||||
(t/testing "without state or origin headers the error keeps the canonical subpath"
|
||||
(binding [cf/config public-config]
|
||||
(let [response (callback (update request :params dissoc :state))
|
||||
location (redirect-location response)]
|
||||
(t/is (= 302 (::yres/status response)))
|
||||
(t/is (= "http://localhost:3449/penpot"
|
||||
(str (assoc (u/uri location) :query nil))))
|
||||
(t/is (= "auth-login" (:screen (get-uri-query location))))
|
||||
(t/is (= "unable-to-auth" (:error (get-uri-query location))))))))))))
|
||||
|
||||
(t/deftest organization-sso-round-trip-preserves-the-alternate-public-subpath
|
||||
(let [manager (session/inmemory-manager)
|
||||
cfg (assoc base-cfg ::session/manager manager)
|
||||
sso {:active true
|
||||
:organization-id test-organization-id
|
||||
:issuer "https://idp.example.com"
|
||||
:client-id "test-client"
|
||||
:client-secret "test-secret"}
|
||||
params {::rpc/profile-id test-profile-id
|
||||
::rpc/request-at (ct/now)
|
||||
:organization-id test-organization-id
|
||||
:query-string "screen=workspace&team-id=0e5f"}
|
||||
start-sso (mw/wrap-trusted-origin
|
||||
(fn [request]
|
||||
(nitrate-rpc/sm$check-nitrate-sso
|
||||
cfg (with-meta params {::http/request request}))))
|
||||
callback (mw/wrap-trusted-origin (partial #'oidc/callback-handler cfg))
|
||||
events (atom [])]
|
||||
(binding [cf/config {:public-uri "http://localhost:3449/penpot/"
|
||||
:trusted-origins #{"https://alt.example.com"}}
|
||||
cf/flags (conj cf/flags :admin-console)]
|
||||
(with-redefs [app.nitrate/organization-access? (constantly true)
|
||||
app.nitrate/sso-session-authorized? (constantly {:authorized false :sso sso})
|
||||
app.nitrate/call (constantly sso)
|
||||
app.auth.oidc/prepare-organization-sso-provider (constantly trusted-origin-provider)
|
||||
app.auth.oidc/get-info (constantly {})
|
||||
app.loggers.audit/submit (fn [_cfg event] (swap! events conj event))]
|
||||
(let [result (start-sso {:headers {"origin" "https://alt.example.com"}})
|
||||
auth-query (get-uri-query (:redirect-uri result))
|
||||
state (:state auth-query)
|
||||
claims (tokens/verify cfg {:token state :iss "oidc"})
|
||||
destination (:dest-url claims)
|
||||
sess {:id (uuid/next) :profile-id test-profile-id :props {}}
|
||||
request (assoc (default-request cfg :state state) ::session/session sess)]
|
||||
(t/is (false? (:authorized result)))
|
||||
(t/is (= "https://alt.example.com" (:origin claims)))
|
||||
(t/is (= "https://alt.example.com/penpot/api/auth/oidc/callback" (:redirect_uri auth-query)))
|
||||
(t/is (= "https://alt.example.com/penpot/" (str (assoc (u/uri destination) :query nil))))
|
||||
(t/is (= {:screen "workspace" :team-id "0e5f"} (get-uri-query destination)))
|
||||
|
||||
(t/testing "the headerless callback accepts the server-built destination and grants the session entry"
|
||||
(let [response (callback request)
|
||||
stored (session/read-session manager (:id sess))]
|
||||
(t/is (= 302 (::yres/status response)))
|
||||
(t/is (= destination (redirect-location response)))
|
||||
(t/is (contains? (get-in stored [:props :sso]) test-organization-id))))
|
||||
|
||||
(t/testing "a different profile returns to the same destination without an SSO entry"
|
||||
(let [other (assoc sess :id (uuid/next) :profile-id (uuid/next))
|
||||
response (callback (assoc request ::session/session other))
|
||||
stored (session/read-session manager (:id other))]
|
||||
(t/is (= destination (redirect-location response)))
|
||||
(t/is (nil? (get-in stored [:props :sso])))
|
||||
(t/is (= "session-mismatch" (get-in (last @events) [:props :failure-reason])))))
|
||||
|
||||
(t/testing "a legacy destination outside the public subpath falls back to the alias base"
|
||||
(let [legacy (tokens/generate cfg (assoc claims :dest-url "https://alt.example.com/other/?screen=workspace"))
|
||||
response (callback (default-request cfg :state legacy))]
|
||||
(t/is (= "https://alt.example.com/penpot/" (redirect-location response))))))))))
|
||||
|
||||
@ -9,6 +9,7 @@
|
||||
[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]))
|
||||
@ -169,3 +170,60 @@
|
||||
(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))))
|
||||
|
||||
@ -37,6 +37,24 @@
|
||||
[result]
|
||||
(get-in result [:body "text/plain"]))
|
||||
|
||||
(t/deftest password-recovery-renders-links-under-the-public-subpath
|
||||
(doseq [[public-uri expected-base]
|
||||
[["https://canonical.example.com/penpot" "https://canonical.example.com/penpot"]
|
||||
["https://canonical.example.com/penpot/" "https://canonical.example.com/penpot"]
|
||||
["https://alternate.example.com/penpot" "https://alternate.example.com/penpot"]
|
||||
["https://alternate.example.com/penpot/" "https://alternate.example.com/penpot"]]]
|
||||
(t/testing public-uri
|
||||
(let [result (emails/render-template "password-recovery"
|
||||
{:to "member@example.com"
|
||||
:name "Member"
|
||||
:token "test-token"
|
||||
:public-uri public-uri})
|
||||
html (get-in result [:body "text/html"])
|
||||
link (str expected-base "/?screen=auth-recovery&token=test-token")]
|
||||
(t/is (str/includes? (email-text-body result) link))
|
||||
(t/is (str/includes? html (str "href=\"" link "\"")))
|
||||
(t/is (str/includes? html (str "src=\"" expected-base "/images/email/logo-penpot.svg\"")))))))
|
||||
|
||||
(defn- invite-email-params
|
||||
[organization]
|
||||
{:to "invitee@example.com"
|
||||
|
||||
@ -21,6 +21,7 @@
|
||||
[app.common.uuid :as uuid]
|
||||
[app.config :as cf]
|
||||
[app.db :as db]
|
||||
[app.http.middleware :as mw]
|
||||
[app.jobs :as jobs]
|
||||
[app.main :as main]
|
||||
[app.media]
|
||||
@ -531,61 +532,62 @@
|
||||
remote-addr server-name server-port
|
||||
scheme protocol path query ssl-client-cert)))
|
||||
|
||||
(defn- prepare-rpc-params
|
||||
[data]
|
||||
(let [params (reduce-kv (fn [params k v]
|
||||
(if (qualified-keyword? k)
|
||||
(assoc params k v)
|
||||
params))
|
||||
{}
|
||||
(dissoc data ::type))
|
||||
;; Honor a caller-supplied request map from the data metadata so
|
||||
;; tests can inject headers, remote address and auth context (e.g.
|
||||
;; :app.http/auth-key-id). Non-map requests (reify IRequest stubs)
|
||||
;; fall back to the dummy request, which carries the body params
|
||||
;; the validation wrapper reads.
|
||||
supplied (-> data meta :app.http/request)
|
||||
request (if (map? supplied)
|
||||
(assoc supplied :params (merge (:params supplied)
|
||||
(d/without-qualified data)))
|
||||
(assoc (make-dummy-request)
|
||||
:params (d/without-qualified data)))]
|
||||
|
||||
(defn- build-rpc-params
|
||||
"Builds the params map for a command from `data` and the final request."
|
||||
[data request]
|
||||
(let [params (reduce-kv (fn [params k v]
|
||||
(if (qualified-keyword? k)
|
||||
(assoc params k v)
|
||||
params))
|
||||
{}
|
||||
(dissoc data ::type))
|
||||
request (update request :params merge (d/without-qualified data))]
|
||||
(-> params
|
||||
(assoc :app.rpc/request-at (ct/now))
|
||||
;; Mirror of the production flag in `app.rpc/make-rpc-handler`:
|
||||
;; upload maps are only trusted over multipart. Tests declare it
|
||||
;; with a content-type header on the supplied request map.
|
||||
;; upload maps are only trusted over multipart.
|
||||
(assoc ::rpc/is-multipart
|
||||
(str/starts-with?
|
||||
(str (yreq/get-header request "content-type"))
|
||||
"multipart/"))
|
||||
(with-meta {:app.http/request request}))))
|
||||
|
||||
(defn command!
|
||||
[{:keys [::type] :as data}]
|
||||
(let [[mdata method-fn] (get-in *system* [:app.rpc/methods type])]
|
||||
(defn- get-supplied-request
|
||||
[data]
|
||||
(let [request (-> data meta :app.http/request)]
|
||||
;; Non-map IRequest stubs cannot carry the body params.
|
||||
(when (map? request)
|
||||
request)))
|
||||
|
||||
(defn- prepare-rpc-params
|
||||
[data]
|
||||
(build-rpc-params data (or (get-supplied-request data) (make-dummy-request))))
|
||||
|
||||
(defn- resolve-method
|
||||
"Resolve a registered method fn from a method registry, raising the
|
||||
standard `rpc-method-not-found` error when missing."
|
||||
[registry type label]
|
||||
(let [[mdata method-fn] (get-in *system* [registry type])]
|
||||
(when-not method-fn
|
||||
(ex/raise :type :assertion
|
||||
:code :rpc-method-not-found
|
||||
:hint (str/ffmt "rpc method '%' not found" (name type))))
|
||||
:hint (str label " '" (name type) "' not found")))
|
||||
[mdata method-fn]))
|
||||
|
||||
(let [params (prepare-rpc-params data)]
|
||||
(try-on! (method-fn params)))))
|
||||
(defn command!
|
||||
[{:keys [::type] :as data}]
|
||||
(let [[_ method-fn] (resolve-method :app.rpc/methods type "rpc method")
|
||||
params (prepare-rpc-params data)]
|
||||
(try-on! (method-fn params))))
|
||||
|
||||
(defn command-raw!
|
||||
"Like `command!`, but returns the raw result without unwrapping it, so a test
|
||||
can read the result metadata (for example the audit props a command sets on a
|
||||
nil result). The HTTP layer unwraps it the same way in production."
|
||||
[{:keys [::type] :as data}]
|
||||
(let [[_ method-fn] (get-in *system* [:app.rpc/methods type])]
|
||||
(when-not method-fn
|
||||
(ex/raise :type :assertion
|
||||
:code :rpc-method-not-found
|
||||
:hint (str/ffmt "rpc method '%' not found" (name type))))
|
||||
|
||||
(let [params (prepare-rpc-params data)]
|
||||
(method-fn params))))
|
||||
(let [[_ method-fn] (resolve-method :app.rpc/methods type "rpc method")
|
||||
params (prepare-rpc-params data)]
|
||||
(method-fn params)))
|
||||
|
||||
(defn management-command!
|
||||
"Invokes a management RPC method.
|
||||
@ -596,11 +598,7 @@
|
||||
tests exercise the allowed path without repeating the key; a test that
|
||||
checks a rejection declares the key explicitly, including `nil`."
|
||||
[{:keys [::type] :as data}]
|
||||
(let [[mdata method-fn] (get-in *system* [:app.rpc/management-methods type])]
|
||||
(when-not method-fn
|
||||
(ex/raise :type :assertion
|
||||
:code :rpc-method-not-found
|
||||
:hint (str/ffmt "management rpc method '%' not found" (name type))))
|
||||
(let [[mdata method-fn] (resolve-method :app.rpc/management-methods type "management rpc method")]
|
||||
(let [request (-> data meta :app.http/request)
|
||||
key-id (cond
|
||||
(contains? data ::rpc/auth-key-id)
|
||||
@ -622,6 +620,25 @@
|
||||
params (prepare-rpc-params data)]
|
||||
(try-on! (method-fn params)))))
|
||||
|
||||
(defn command-through-middleware
|
||||
"Runs an RPC method wrapped in the HTTP trusted-origin middleware, so
|
||||
the request origin can override the config :public-uri.
|
||||
|
||||
Accepts the same data map as `command!`. Its request metadata and the
|
||||
optional `:headers` and `:request-attrs` are merged into the dummy
|
||||
request before middleware runs. Explicit options take precedence."
|
||||
([data]
|
||||
(command-through-middleware data {}))
|
||||
([{:keys [::type] :as data} {:keys [headers request-attrs]}]
|
||||
(let [[_ method-fn] (resolve-method :app.rpc/methods type "rpc method")
|
||||
supplied (get-supplied-request data)
|
||||
request (-> (make-dummy-request)
|
||||
(merge supplied request-attrs)
|
||||
(assoc :headers (merge {} (:headers supplied) headers (:headers request-attrs))))
|
||||
handler (fn [request]
|
||||
(try-on! (method-fn (build-rpc-params data request))))]
|
||||
((mw/wrap-trusted-origin handler) request))))
|
||||
|
||||
(def multipart-headers
|
||||
{"content-type" "multipart/form-data; boundary=test"})
|
||||
|
||||
|
||||
@ -13,6 +13,7 @@
|
||||
the helper fails loudly here instead of as a flood of unrelated
|
||||
test errors."
|
||||
(:require
|
||||
[app.config :as cf]
|
||||
[backend-tests.helpers :as th]
|
||||
[clojure.test :as t]
|
||||
[yetti.request :as yreq]))
|
||||
@ -151,3 +152,28 @@
|
||||
request (:app.http/request (meta params))]
|
||||
(t/is (instance? backend_tests.helpers.DummyRequest request))
|
||||
(t/is (= {:events [{:name "event"}]} (:params request)))))
|
||||
|
||||
(t/deftest command-through-middleware-preserves-processed-request
|
||||
(let [origin "https://alt.example.com"
|
||||
data (with-meta {::th/type :dummy :name "new"}
|
||||
{:app.http/request {:headers th/multipart-headers
|
||||
:params {:name "old" :description "kept"}
|
||||
:remote-addr "192.0.2.1"}})
|
||||
method (fn [params]
|
||||
(let [request (:app.http/request (meta params))]
|
||||
{:origin (:app.http/trusted-origin request)
|
||||
:remote-addr (:remote-addr request)
|
||||
:auth-data (:app.http/auth-data request)
|
||||
:body (:params request)
|
||||
:multipart (:app.rpc/is-multipart params)}))
|
||||
options {:headers {"origin" origin}
|
||||
:request-attrs {:app.http/auth-data {:provider "test"}}}]
|
||||
(binding [cf/config (assoc cf/config :trusted-origins #{origin})
|
||||
th/*system* {:app.rpc/methods {:dummy [{} method]}}]
|
||||
(t/is (= {:error nil
|
||||
:result {:origin origin
|
||||
:remote-addr "192.0.2.1"
|
||||
:auth-data {:provider "test"}
|
||||
:body {:name "new" :description "kept"}
|
||||
:multipart true}}
|
||||
(th/command-through-middleware data options))))))
|
||||
|
||||
@ -197,12 +197,20 @@
|
||||
(let [handler (#'app.http.middleware/wrap-cors
|
||||
(fn [_] {::yres/status 200 ::yres/headers {}})
|
||||
#{"https://trusted.example"})
|
||||
resp (handler (->MethodAwareDummyRequest :options {"origin" "https://trusted.example"}))
|
||||
headers (::yres/headers resp)]
|
||||
resp (handler (->MethodAwareDummyRequest
|
||||
:options
|
||||
{"origin" "https://trusted.example"
|
||||
"access-control-request-headers"
|
||||
"x-frontend-version, x-client, x-penpot-origin, content-type, x-unrecognized"}))
|
||||
headers (::yres/headers resp)
|
||||
allowed (into #{} (map str/trim)
|
||||
(str/split (get headers "access-control-allow-headers" "") #","))]
|
||||
|
||||
(t/is (= 204 (::yres/status resp)))
|
||||
(t/is (= "https://trusted.example" (get headers "access-control-allow-origin")))
|
||||
(t/is (= "true" (get headers "access-control-allow-credentials")))))
|
||||
(t/is (= "true" (get headers "access-control-allow-credentials")))
|
||||
(t/is (= #{"x-frontend-version" "x-client" "x-penpot-origin" "content-type" "accept"}
|
||||
allowed))))
|
||||
|
||||
(t/deftest cors-middleware-preflight-non-allowlisted
|
||||
(let [handler (#'app.http.middleware/wrap-cors
|
||||
@ -761,3 +769,93 @@
|
||||
decoded (json/decode encoded :key-fn json/read-kebab-key)]
|
||||
(t/is (str/includes? encoded "invalid-storage-metadata"))
|
||||
(t/is (string? (:explain decoded))))))
|
||||
(t/deftest trusted-origin-middleware-binds-public-uri
|
||||
(let [seen (atom nil)
|
||||
handler (mw/wrap-trusted-origin
|
||||
(fn [request]
|
||||
(reset! seen {:public-uri (cf/get :public-uri)
|
||||
:stamp (:app.http/trusted-origin request)})
|
||||
{}))]
|
||||
(with-redefs [cf/config (assoc cf/config
|
||||
:public-uri "http://localhost:3449"
|
||||
:trusted-origins #{"https://alt.example.com"
|
||||
"https://other.example.com"})]
|
||||
(t/testing "trusted origin overrides the public base and stamps the request"
|
||||
(reset! seen nil)
|
||||
(handler (th/make-dummy-request {:headers {"origin" "https://alt.example.com"}}))
|
||||
(t/is (= "https://alt.example.com" (str (:public-uri @seen))))
|
||||
(t/is (= "https://alt.example.com" (:stamp @seen))))
|
||||
|
||||
(t/testing "origin is normalized before matching and use"
|
||||
(reset! seen nil)
|
||||
(handler (th/make-dummy-request {:headers {"origin" " HTTPS://Alt.Example.com "}}))
|
||||
(t/is (= "https://alt.example.com" (str (:public-uri @seen))))
|
||||
(t/is (= "https://alt.example.com" (:stamp @seen))))
|
||||
|
||||
(t/testing "untrusted origin is ignored"
|
||||
(reset! seen nil)
|
||||
(handler (th/make-dummy-request {:headers {"origin" "https://evil.example.com"}}))
|
||||
(t/is (= "http://localhost:3449" (str (:public-uri @seen))))
|
||||
(t/is (nil? (:stamp @seen))))
|
||||
|
||||
(t/testing "missing origin is ignored"
|
||||
(reset! seen nil)
|
||||
(handler (th/make-dummy-request {}))
|
||||
(t/is (= "http://localhost:3449" (str (:public-uri @seen))))
|
||||
(t/is (nil? (:stamp @seen))))
|
||||
|
||||
(t/testing "trusted x-penpot-origin is used without an origin header"
|
||||
(reset! seen nil)
|
||||
(handler (th/make-dummy-request {:headers {"x-penpot-origin" "https://alt.example.com"}}))
|
||||
(t/is (= "https://alt.example.com" (str (:public-uri @seen))))
|
||||
(t/is (= "https://alt.example.com" (:stamp @seen))))
|
||||
|
||||
(t/testing "trusted x-penpot-origin wins over a different origin header"
|
||||
(reset! seen nil)
|
||||
(handler (th/make-dummy-request {:headers {"x-penpot-origin" "https://alt.example.com"
|
||||
"origin" "https://other.example.com"}}))
|
||||
(t/is (= "https://alt.example.com" (str (:public-uri @seen)))))
|
||||
|
||||
(t/testing "an untrusted x-penpot-origin falls back to a trusted origin"
|
||||
(reset! seen nil)
|
||||
(handler (th/make-dummy-request {:headers {"x-penpot-origin" "https://evil.example.com"
|
||||
"origin" "https://other.example.com"}}))
|
||||
(t/is (= "https://other.example.com" (str (:public-uri @seen)))))
|
||||
|
||||
(t/testing "a null custom header never matches"
|
||||
(reset! seen nil)
|
||||
(handler (th/make-dummy-request {:headers {"x-penpot-origin" "null"}}))
|
||||
(t/is (= "http://localhost:3449" (str (:public-uri @seen))))
|
||||
(t/is (nil? (:stamp @seen))))
|
||||
|
||||
(t/testing "the binding does not leak past the request"
|
||||
(handler (th/make-dummy-request {:headers {"origin" "https://alt.example.com"}}))
|
||||
(t/is (= "http://localhost:3449" (str (cf/get :public-uri))))))))
|
||||
|
||||
(t/deftest trusted-origin-middleware-preserves-the-public-path
|
||||
(let [handler (mw/wrap-trusted-origin
|
||||
(fn [request]
|
||||
[(:app.http/trusted-origin request)
|
||||
(cf/get-public-uri "assets/by-id/example")]))]
|
||||
(doseq [path ["/penpot" "/penpot/"]]
|
||||
(binding [cf/config (assoc cf/config
|
||||
:public-uri (str "http://localhost:3449" path)
|
||||
:trusted-origins #{"https://alt.example.com"})]
|
||||
(t/is (= ["https://alt.example.com" "https://alt.example.com/penpot/assets/by-id/example"]
|
||||
(handler (th/make-dummy-request
|
||||
{:headers {"x-penpot-origin" "HTTPS://ALT.EXAMPLE.COM:443"}}))))
|
||||
(t/is (= [nil "http://localhost:3449/penpot/assets/by-id/example"]
|
||||
(handler (th/make-dummy-request
|
||||
{:headers {"origin" "https://other.example.com"}}))))))))
|
||||
|
||||
(t/deftest root-middleware-registers-trusted-origin-before-auth
|
||||
;; The feature only works if `mw/trusted-origin` is part of the root chain
|
||||
;; and ordered so it wraps auth and errors; guard against silent removal or
|
||||
;; reordering.
|
||||
(let [names (mapv (comp :name first) (#'app.http/root-middleware {}))
|
||||
pos (fn [n] (first (keep-indexed (fn [i x] (when (= n x) i)) names)))]
|
||||
(t/is (some? (pos ::mw/trusted-origin)))
|
||||
(t/is (some? (pos ::mw/auth)))
|
||||
(t/is (some? (pos ::mw/errors)))
|
||||
(t/is (apply < (remove nil? [(pos ::mw/trusted-origin) (pos ::mw/auth)])))
|
||||
(t/is (apply < (remove nil? [(pos ::mw/trusted-origin) (pos ::mw/errors)])))))
|
||||
|
||||
55
backend/test/backend_tests/http_sse_test.clj
Normal file
55
backend/test/backend_tests/http_sse_test.clj
Normal file
@ -0,0 +1,55 @@
|
||||
;; 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.http-sse-test
|
||||
(:require
|
||||
[app.config :as cf]
|
||||
[app.http.middleware :as mw]
|
||||
[app.http.sse :as sse]
|
||||
[clojure.test :as t]
|
||||
[cuerdas.core :as str]
|
||||
[yetti.response :as yres])
|
||||
(:import
|
||||
java.io.ByteArrayOutputStream))
|
||||
|
||||
(defn- run-stream
|
||||
"Build an SSE response under `base`, then run its body after the
|
||||
request scope has ended."
|
||||
[base]
|
||||
(let [seen (atom nil)
|
||||
handler (fn []
|
||||
(reset! seen (str (cf/get :public-uri)))
|
||||
{::result true})
|
||||
endpoint (sse/response handler)
|
||||
response (if base
|
||||
(binding [cf/config (cf/with-public-uri base cf/config)]
|
||||
(endpoint {}))
|
||||
(endpoint {}))
|
||||
body (::yres/body response)]
|
||||
(with-redefs [cf/config (assoc cf/config :public-uri "http://localhost:3449")]
|
||||
(yres/write-body-to-stream body response (ByteArrayOutputStream.)))
|
||||
@seen))
|
||||
|
||||
(t/deftest stream-uses-the-origin-of-the-request
|
||||
(t/is (= "https://alt.example.com"
|
||||
(run-stream "https://alt.example.com"))))
|
||||
|
||||
(t/deftest stream-keeps-the-canonical-origin-without-a-trusted-base
|
||||
(t/is (= "http://localhost:3449" (run-stream nil))))
|
||||
|
||||
(t/deftest stream-writes-the-alternate-public-subpath-after-the-request
|
||||
(let [public-config {:public-uri "http://localhost:3449/penpot/"
|
||||
:trusted-origins #{"https://alt.example.com"}}
|
||||
endpoint (mw/wrap-trusted-origin
|
||||
(sse/response #(str (cf/get-public-uri "download"))))
|
||||
response (binding [cf/config public-config]
|
||||
(endpoint {:headers {"x-penpot-origin" "https://alt.example.com"}}))
|
||||
output (ByteArrayOutputStream.)]
|
||||
(binding [cf/config public-config]
|
||||
(yres/write-body-to-stream (::yres/body response) response output))
|
||||
(let [body (.toString output "UTF-8")]
|
||||
(t/is (str/includes? body "event: end\n"))
|
||||
(t/is (str/includes? body "https://alt.example.com/penpot/download")))))
|
||||
@ -70,6 +70,21 @@
|
||||
(t/is (str/includes? (str (:resource-uri result))
|
||||
(str (:resource-id result)))))))
|
||||
|
||||
(t/deftest put-resource-uses-the-base-passed-by-the-caller
|
||||
(let [cfg (make-cfg)
|
||||
profile-id (:id (th/create-profile* 1))]
|
||||
(t/testing "the download uri is built on the alternate base"
|
||||
(let [result (js/put-resource cfg profile-id
|
||||
{:content (sto/content "x")
|
||||
:filename "x.penpot"
|
||||
:mtype "application/zip"
|
||||
:public-uri "https://alt.example.com"})]
|
||||
(t/is (str/starts-with? (:resource-uri result)
|
||||
"https://alt.example.com/"))))
|
||||
(t/testing "without a base the canonical public uri is used"
|
||||
(let [result (put-artifact cfg profile-id "y")]
|
||||
(t/is (str/starts-with? (:resource-uri result) "http://"))))))
|
||||
|
||||
(t/deftest put-resource-requires-an-owner
|
||||
(let [cfg (make-cfg)]
|
||||
(t/testing "an artifact without an owner is a caller bug"
|
||||
|
||||
@ -107,6 +107,36 @@
|
||||
;; artifact produced is what proves the call does not wait
|
||||
(t/is (= before (count-storage-objects)))))))
|
||||
|
||||
(t/deftest create-export-binfile-job-freezes-the-effective-public-uri
|
||||
(let [profile (th/create-profile* 1)
|
||||
file-id (first (:file-ids (import-fixture! profile)))
|
||||
data {::th/type :create-export-binfile-job
|
||||
::rpc/profile-id (:id profile)
|
||||
:params {:file-ids #{file-id}
|
||||
:export-type :detach-libraries}}
|
||||
out (binding [cf/config (assoc cf/config
|
||||
:public-uri "https://canonical.example.com/penpot"
|
||||
:trusted-origins #{"https://alt.example.com"})]
|
||||
(th/command-through-middleware
|
||||
data {:headers {"x-penpot-origin" "https://alt.example.com"}}))]
|
||||
(t/is (th/success? out))
|
||||
(let [job (jobs/get-job th/*system* (:id (:result out)))
|
||||
job-def (jobs/get-job-def (::jobs/defs th/*system*) :export-binfile)
|
||||
params (jobs/decode-params job-def (:params job))]
|
||||
(t/is (= "https://alt.example.com/penpot" (:public-uri params))))))
|
||||
|
||||
(t/deftest create-export-binfile-job-rejects-client-public-uri
|
||||
(let [profile (th/create-profile* 1)
|
||||
file-id (first (:file-ids (import-fixture! profile)))
|
||||
out (th/command! {::th/type :create-export-binfile-job
|
||||
::rpc/profile-id (:id profile)
|
||||
:params {:file-ids #{file-id}
|
||||
:export-type :detach-libraries
|
||||
:public-uri "https://client.example.com"}})]
|
||||
(t/is (not (th/success? out)))
|
||||
(t/is (= :params-validation (th/ex-code (:error out))))
|
||||
(t/is (zero? (count-jobs)))))
|
||||
|
||||
(t/deftest create-export-binfile-job-requires-the-export-type
|
||||
;; the type is part of the contract of the job: a caller that does not
|
||||
;; say how to handle the libraries gets an error, not a package it did
|
||||
|
||||
@ -8,13 +8,18 @@
|
||||
(: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]
|
||||
@ -332,6 +337,36 @@
|
||||
(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
|
||||
|
||||
|
||||
@ -184,14 +184,44 @@
|
||||
(t/is (= {:authorized false
|
||||
:redirect-uri redirect-uri}
|
||||
(:result out)))
|
||||
(t/is (= #{:query-string :organization-id :profile-id} (set (keys @redirect-options))))
|
||||
(t/is (= #{:query-string :organization-id :profile-id :origin} (set (keys @redirect-options))))
|
||||
(t/is (= "screen=workspace&team-id=0e5f-1a2b" (:query-string @redirect-options)))
|
||||
(t/is (= (:id team-owner) (:profile-id @redirect-options)))
|
||||
(t/is (nil? (:organization-id @redirect-options)))
|
||||
(t/is (nil? (:origin @redirect-options)))
|
||||
(t/is (= {:profile-id (:id team-owner)
|
||||
:organization-id organization-id}
|
||||
@started-event)))))))
|
||||
|
||||
(t/deftest check-nitrate-sso-passes-trusted-origin
|
||||
(let [team-owner (th/create-profile* 1 {:is-active true})
|
||||
team (th/create-team* 1 {:profile-id (:id team-owner)})
|
||||
organization-id (uuid/random)
|
||||
redirect-options (atom nil)
|
||||
params {::th/type :check-nitrate-sso
|
||||
::rpc/profile-id (:id team-owner)
|
||||
:team-id (:id team)
|
||||
:query-string "screen=workspace"}]
|
||||
(binding [cf/flags (conj cf/flags :admin-console)]
|
||||
(with-redefs [cf/config (assoc cf/config
|
||||
:public-uri "http://localhost:3449"
|
||||
:trusted-origins #{"https://alt.example.com"})
|
||||
nitrate/call
|
||||
(active-sso-call-mock
|
||||
(:id team)
|
||||
organization-id
|
||||
(:id team-owner))
|
||||
oidc/build-organization-sso-auth-redirect-uri
|
||||
(fn [_cfg _sso & options]
|
||||
(reset! redirect-options (apply hash-map options))
|
||||
"https://idp.example.com/authorize")
|
||||
oidc/submit-organization-sso-auth-started-event
|
||||
(constantly nil)]
|
||||
(let [out (th/command-through-middleware
|
||||
params {:headers {"origin" "https://alt.example.com"}})]
|
||||
(t/is (th/success? out))
|
||||
(t/is (= "https://alt.example.com" (:origin @redirect-options))))))))
|
||||
|
||||
(t/deftest check-nitrate-sso-reports-redirect-failure
|
||||
(let [profile (th/create-profile* 1 {:is-active true})
|
||||
organization-id (uuid/random)
|
||||
|
||||
@ -2106,3 +2106,85 @@
|
||||
:path (fs/path "/etc/passwd")
|
||||
:mtype "image/jpeg"}})]
|
||||
(t/is (th/ex-of-code? (:error out) :params-validation))))
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Trusted origin on the sensitive email links
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
(def ^:private canonical-public-uri "http://localhost:3449/penpot")
|
||||
|
||||
(def ^:private trusted-link-cases
|
||||
[{:headers {"x-penpot-origin" "https://alt.example.com"}
|
||||
:expected "https://alt.example.com/penpot"}
|
||||
{:headers {"origin" "https://alt.example.com"}
|
||||
:expected "https://alt.example.com/penpot"}
|
||||
{:headers {"x-penpot-origin" "https://evil.example.com"}
|
||||
:expected canonical-public-uri}
|
||||
{:headers {"x-penpot-origin" "null"}
|
||||
:expected canonical-public-uri}
|
||||
{:headers {}
|
||||
:expected canonical-public-uri}])
|
||||
|
||||
(defn- with-trusted-link-config
|
||||
[f]
|
||||
(binding [cf/config (assoc cf/config
|
||||
:public-uri canonical-public-uri
|
||||
:trusted-origins #{"https://alt.example.com"})]
|
||||
(f)))
|
||||
|
||||
(defn- sent-public-uri
|
||||
[mock]
|
||||
(some-> mock deref :call-args-list first second :public-uri str))
|
||||
|
||||
(t/deftest recovery-link-base-follows-trusted-origins
|
||||
(doseq [[i {:keys [headers expected]}] (map-indexed vector trusted-link-cases)]
|
||||
(with-trusted-link-config
|
||||
#(with-mocks [mock {:target 'app.email/send-template :return nil}
|
||||
_ {:target 'app.rpc.commands.auth/elapsed-verify-threshold?
|
||||
:return true}]
|
||||
(let [profile (th/create-profile* (inc i) {:is-active true})
|
||||
out (th/command-through-middleware
|
||||
{::th/type :request-profile-recovery
|
||||
:email (:email profile)}
|
||||
{:headers headers})]
|
||||
(t/is (th/success? out) headers)
|
||||
(t/is (= expected (sent-public-uri mock)) headers))))))
|
||||
|
||||
(t/deftest email-change-link-base-follows-trusted-origins
|
||||
(doseq [[i {:keys [headers expected]}] (map-indexed vector trusted-link-cases)]
|
||||
(with-trusted-link-config
|
||||
#(with-mocks [mock {:target 'app.email/send-template :return nil}]
|
||||
(let [profile (th/create-profile* (inc i))
|
||||
out (th/command-through-middleware
|
||||
{::th/type :request-email-change
|
||||
::rpc/profile-id (:id profile)
|
||||
:email (str "changed-" i "@example.com")}
|
||||
{:headers headers})]
|
||||
(t/is (th/success? out) headers)
|
||||
(t/is (= expected (sent-public-uri mock)) headers))))))
|
||||
|
||||
(t/deftest verification-link-base-follows-trusted-origins
|
||||
(doseq [[i {:keys [headers expected]}] (map-indexed vector trusted-link-cases)]
|
||||
(with-trusted-link-config
|
||||
#(with-mocks [mock {:target 'app.email/send-template :return nil}]
|
||||
(let [email (str "verify-" (uuid/next) "@example.com")
|
||||
itoken (tokens/generate th/*system*
|
||||
{:iss :team-invitation
|
||||
:exp (ct/in-future "48h")
|
||||
:role :editor
|
||||
:team-id uuid/zero
|
||||
:member-email email})
|
||||
prep (th/command-through-middleware
|
||||
{::th/type :prepare-register-profile
|
||||
:invitation-token itoken
|
||||
:fullname "foobar"
|
||||
:email email
|
||||
:password "Foobar12!"}
|
||||
{:headers headers})
|
||||
reg (th/command-through-middleware
|
||||
{::th/type :register-profile
|
||||
:token (:token (:result prep))}
|
||||
{:headers headers})]
|
||||
(t/is (th/success? prep) headers)
|
||||
(t/is (th/success? reg) headers)
|
||||
(t/is (= expected (sent-public-uri mock)) headers))))))
|
||||
|
||||
@ -2678,3 +2678,26 @@
|
||||
:role :owner})
|
||||
props (:app.loggers.audit/props (meta out))]
|
||||
(t/is (= (:id owner) (:prev-owner-id props))))))
|
||||
(t/deftest create-team-invitations-link-base-follows-trusted-origins
|
||||
(let [owner (th/create-profile* 1 {:is-active true})
|
||||
team (th/create-team* 1 {:profile-id (:id owner)})
|
||||
cases [{:origin "https://alt.example.com"
|
||||
:email "trusted@example.com"
|
||||
:expected "https://alt.example.com"}
|
||||
{:origin "https://evil.example.com"
|
||||
:email "untrusted@example.com"
|
||||
:expected "http://localhost:3449"}]]
|
||||
(doseq [{:keys [origin email expected]} cases]
|
||||
(with-mocks [mock {:target 'app.email/send-template :return nil}]
|
||||
(with-redefs [cf/config (assoc cf/config
|
||||
:public-uri "http://localhost:3449"
|
||||
:trusted-origins #{"https://alt.example.com"})]
|
||||
(let [data {::th/type :create-team-invitations
|
||||
::rpc/profile-id (:id owner)
|
||||
:team-id (:id team)
|
||||
:role :editor
|
||||
:emails [email]}
|
||||
out (th/command-through-middleware data {:headers {"origin" origin}})
|
||||
sent (-> @mock :call-args-list first second)]
|
||||
(t/is (th/success? out) origin)
|
||||
(t/is (= expected (str (:public-uri sent))) origin)))))))
|
||||
|
||||
@ -141,6 +141,29 @@
|
||||
:name "imported"}
|
||||
:upload-id (upload-chunked! profile)}))
|
||||
|
||||
(t/deftest export-job-keeps-the-request-public-uri-in-the-runner
|
||||
(let [profile (th/create-profile* 1)
|
||||
file-id (first (:file-ids (import-fixture! profile)))
|
||||
out (binding [cf/config (assoc cf/config
|
||||
:public-uri "https://canonical.example.com/penpot"
|
||||
:trusted-origins #{"https://alt.example.com"})]
|
||||
(th/command-through-middleware
|
||||
{::th/type :create-export-binfile-job
|
||||
::rpc/profile-id (:id profile)
|
||||
:params {:file-ids #{file-id}
|
||||
:export-type :detach-libraries}}
|
||||
{:headers {"x-penpot-origin" "https://alt.example.com"}}))
|
||||
job-id (get-in out [:result :id])]
|
||||
(t/is (th/success? out))
|
||||
(wdisp/run-batch (dispatcher-cfg))
|
||||
(binding [cf/config (assoc cf/config :public-uri "https://worker.example.com/another-path")]
|
||||
(run-one (runner-cfg "binfile")))
|
||||
(let [row (job-row job-id)]
|
||||
(t/is (= "completed" (:status row)))
|
||||
(t/is (some? (:resource-id row)))
|
||||
(t/is (= (str "https://alt.example.com/penpot/assets/by-id/" (:resource-id row))
|
||||
(get-in row [:result :resource-uri]))))))
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; TESTS
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
@ -32,6 +32,15 @@ x-flags: &penpot-flags
|
||||
x-uri: &penpot-public-uri
|
||||
PENPOT_PUBLIC_URI: http://localhost:9001
|
||||
|
||||
## Optional alternate origins shared by the frontend and backend.
|
||||
## Set PENPOT_TRUSTED_ORIGINS in your environment or .env to a list of bare
|
||||
## origins (no path), separated by commas or whitespace. Use HTTPS in production.
|
||||
## Route each alias to the same frontend and public path. Register the OIDC
|
||||
## callback for each alias, including the public subpath, if any.
|
||||
## This setting does not grant CORS access.
|
||||
x-trusted-origins: &penpot-trusted-origins
|
||||
PENPOT_TRUSTED_ORIGINS: "${PENPOT_TRUSTED_ORIGINS:-}"
|
||||
|
||||
x-body-size: &penpot-http-body-size
|
||||
# Max body size
|
||||
PENPOT_HTTP_SERVER_MAX_BODY_SIZE: 367001600
|
||||
@ -120,7 +129,7 @@ services:
|
||||
# - "traefik.http.routers.penpot-https.tls=true"
|
||||
|
||||
environment:
|
||||
<< : [*penpot-flags, *penpot-http-body-size, *penpot-public-uri]
|
||||
<< : [*penpot-flags, *penpot-http-body-size, *penpot-public-uri, *penpot-trusted-origins]
|
||||
|
||||
# Don't touch it; this uses an internal docker network to
|
||||
# communicate with the admin-console.
|
||||
@ -149,7 +158,7 @@ services:
|
||||
|
||||
|
||||
environment:
|
||||
<< : [*penpot-flags, *penpot-public-uri, *penpot-http-body-size, *penpot-secret-key, *penpot-database]
|
||||
<< : [*penpot-flags, *penpot-public-uri, *penpot-trusted-origins, *penpot-http-body-size, *penpot-secret-key, *penpot-database]
|
||||
|
||||
# Don't touch it; this uses an internal docker network to
|
||||
# communicate with the admin-console.
|
||||
|
||||
@ -44,8 +44,18 @@ update_oidc_name() {
|
||||
fi
|
||||
}
|
||||
|
||||
update_trusted_origins() {
|
||||
if [ -n "${PENPOT_TRUSTED_ORIGINS:-}" ]; then
|
||||
local encoded
|
||||
# Encode the UTF-8 bytes on one line so the value cannot end the JS string.
|
||||
encoded="$(printf '%s' "$PENPOT_TRUSTED_ORIGINS" | base64 -w 0)" || return 1
|
||||
printf 'var penpotTrustedOrigins = "%s";\n' "$encoded" >> "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
update_flags /var/www/app/js/config.js
|
||||
update_oidc_name /var/www/app/js/config.js
|
||||
update_trusted_origins /var/www/app/js/config.js || exit 1
|
||||
|
||||
#########################################
|
||||
## Nginx Config
|
||||
|
||||
54
docker/images/tests/nginx-entrypoint.test.mjs
Normal file
54
docker/images/tests/nginx-entrypoint.test.mjs
Normal file
@ -0,0 +1,54 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { test } from "node:test";
|
||||
|
||||
const files = new URL("../files/", import.meta.url);
|
||||
const config = readFileSync(new URL("config.js", files), "utf8");
|
||||
|
||||
function renderConfig(t, trustedOrigins) {
|
||||
const root = mkdtempSync(join(tmpdir(), "penpot-entrypoint-test-"));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
|
||||
for (const dir of ["etc/nginx/overrides/http.d", "etc/nginx/overrides/server.d", "tmp", "var/www/app/js"]) {
|
||||
mkdirSync(join(root, dir), { recursive: true });
|
||||
}
|
||||
for (const name of ["nginx.conf", "nginx-security-headers.conf", "nginx-admin-console-locations.conf"]) {
|
||||
copyFileSync(new URL(`${name}.template`, files), join(root, "tmp", `${name}.template`));
|
||||
}
|
||||
copyFileSync(new URL("nginx-resolvers.conf.template", files), join(root, "tmp/resolvers.conf.template"));
|
||||
const configPath = join(root, "var/www/app/js/config.js");
|
||||
writeFileSync(configPath, config);
|
||||
|
||||
// Run the real entrypoint with its container paths under a temporary root.
|
||||
const script = readFileSync(new URL("nginx-entrypoint.sh", files), "utf8")
|
||||
.replace(/\/(?:etc\/nginx|var\/www\/app|tmp\/[\w.-]+\.template)\b/g, (path) => root + path);
|
||||
const scriptPath = join(root, "entrypoint.sh");
|
||||
writeFileSync(scriptPath, script);
|
||||
const env = { PATH: process.env.PATH };
|
||||
if (trustedOrigins !== undefined) {
|
||||
env.PENPOT_TRUSTED_ORIGINS = trustedOrigins;
|
||||
}
|
||||
execFileSync("bash", [scriptPath, "true"], { env });
|
||||
return readFileSync(configPath, "utf8");
|
||||
}
|
||||
|
||||
for (const [name, value] of [
|
||||
["a list of origins", "https://alias.example, https://second.example:9443"],
|
||||
["invalid input with quotes, backslashes and UTF-8", "\"'\\\nnot an origin ☃\n"],
|
||||
["a list longer than one Base64 line", "https://alias.example ".repeat(12)],
|
||||
]) {
|
||||
test(`config.js stores ${name} in one Base64 string`, (t) => {
|
||||
const result = renderConfig(t, value);
|
||||
const expected = Buffer.from(value, "utf8").toString("base64");
|
||||
assert.equal(result, `${config}var penpotTrustedOrigins = "${expected}";\n`);
|
||||
});
|
||||
}
|
||||
|
||||
for (const [name, value] of [["unset", undefined], ["empty", ""]]) {
|
||||
test(`config.js stays unchanged when trusted origins are ${name}`, (t) => {
|
||||
assert.equal(renderConfig(t, value), config);
|
||||
});
|
||||
}
|
||||
@ -123,11 +123,14 @@ To configure the authentication with third-party auth providers you will need to
|
||||
configure Penpot and set the correct callback of your Penpot instance in the auth-provider
|
||||
configuration.
|
||||
|
||||
The callback has the following format:
|
||||
Append `api/auth/oidc/callback` to the public URL with a single `/` between
|
||||
them. Register the exact URL, including any configured subpath:
|
||||
|
||||
```html
|
||||
https://<your_domain>/api/auth/oidc/callback
|
||||
```
|
||||
- Public URL `https://mycompany.com/`: `https://mycompany.com/api/auth/oidc/callback`
|
||||
- Public URL `https://mycompany.com/penpot/`: `https://mycompany.com/penpot/api/auth/oidc/callback`
|
||||
|
||||
If you configure [trusted alternate origins](#trusted-alternate-origins), register
|
||||
the callback for each alias as well.
|
||||
|
||||
#### Google
|
||||
|
||||
@ -413,6 +416,10 @@ Existing bookmarks and integrations that use the previous root URL must be
|
||||
updated. You may also configure a redirect from the previous URL. If the scheme
|
||||
or hostname changes in addition to the path, review your authentication provider
|
||||
callback URLs and cookie settings. Active users may need to sign in again.
|
||||
After upgrading, register the callback with the subpath at the identity provider
|
||||
even when the scheme and hostname stay the same. For example, register
|
||||
`https://mycompany.com/penpot/api/auth/oidc/callback` for
|
||||
`https://mycompany.com/penpot/`.
|
||||
|
||||
<p class="advice">
|
||||
If you plan to serve Penpot under different domain than `localhost` without HTTPS,
|
||||
@ -422,6 +429,114 @@ callback URLs and cookie settings. Active users may need to sign in again.
|
||||
may limit the usage of Penpot; as an example, the clipboard does not work with HTTP.
|
||||
</p>
|
||||
|
||||
### Trusted alternate origins
|
||||
|
||||
Use `PENPOT_TRUSTED_ORIGINS` to serve the same Penpot installation on more than
|
||||
one domain with a single frontend and a common backend. Give both services the
|
||||
same list of aliases. With the official Docker Compose file, set the
|
||||
canonical URL in the `x-uri` block. The separate `x-trusted-origins` block
|
||||
passes the alias list only to the frontend and backend:
|
||||
|
||||
```yaml
|
||||
x-uri: &penpot-public-uri
|
||||
PENPOT_PUBLIC_URI: https://mycompany.com/penpot/
|
||||
|
||||
x-trusted-origins: &penpot-trusted-origins
|
||||
PENPOT_TRUSTED_ORIGINS: "${PENPOT_TRUSTED_ORIGINS:-}"
|
||||
```
|
||||
|
||||
Set the alias once in your environment or Compose `.env` file:
|
||||
|
||||
```dotenv
|
||||
PENPOT_TRUSTED_ORIGINS=https://alt.mycompany.com
|
||||
```
|
||||
|
||||
Set up DNS and TLS for both names. Configure your reverse proxy or Ingress to
|
||||
route `https://mycompany.com/penpot/` and `https://alt.mycompany.com/penpot/` to
|
||||
the same frontend, without rewriting the path. Follow the [subpath proxy
|
||||
requirements](#serve-penpot-from-a-subpath) for both names. This setting does
|
||||
not configure the proxy or share browser sessions between the two domains.
|
||||
|
||||
**Only list aliases you control.** Penpot can put the alias in sensitive links,
|
||||
such as password reset links. Use HTTPS in production.
|
||||
|
||||
- Separate entries with commas or whitespace. Each is a bare HTTP(S) origin
|
||||
(`scheme://host[:port]`): no path (not even a trailing slash), query, fragment,
|
||||
credentials, or wildcard. Matching ignores case and surrounding whitespace.
|
||||
HTTPS with or without `:443` matches the same origin, as does HTTP with or
|
||||
without `:80`. Other ports must match exactly. For IPv6, use the origin
|
||||
as the browser reports it, without a path. For example, use
|
||||
`https://[::1]:9443`, not `https://[0:0:0:0:0:0:0:1]:9443`.
|
||||
- At startup, the backend warns about and ignores invalid entries. It also logs
|
||||
one warning if the list contains any valid HTTP origin whose hostname is not
|
||||
`localhost`. Those HTTP entries still work; they do not change the secure
|
||||
session cookie flags.
|
||||
- The frontend container writes the list to the existing `config.js` as data.
|
||||
At startup, the frontend uses the browser's origin if it matches the list;
|
||||
otherwise it keeps the canonical URL. On a match, only the scheme, host,
|
||||
and port change. Navigation, assets, and API calls keep the path and trailing
|
||||
slash from the configured base.
|
||||
- The frontend sends `X-Penpot-Origin` only on Penpot API calls that need to
|
||||
select the public base, including RPC reads that may lack `Origin` and OIDC
|
||||
login requests. It does not add the header to general HTTP requests for
|
||||
fonts, assets, or external URLs. The backend uses `X-Penpot-Origin` if it
|
||||
matches the list, then tries `Origin`. If neither matches, it uses
|
||||
`PENPOT_PUBLIC_URI`. Generated links keep the configured path.
|
||||
- This list does not grant cross-origin browser access. With `enable-cors`,
|
||||
`PENPOT_ALLOWED_ORIGINS` separately controls which origins may make CORS
|
||||
requests. Listing an origin in either setting does not add it to the other.
|
||||
|
||||
Register the exact OIDC callback URL for the canonical base and for each alias
|
||||
at the identity provider. For example, with `PENPOT_PUBLIC_URI` set to
|
||||
`https://mycompany.com/penpot/` and `https://alt.mycompany.com` in the list, register
|
||||
both `https://mycompany.com/penpot/api/auth/oidc/callback` and
|
||||
`https://alt.mycompany.com/penpot/api/auth/oidc/callback`. If you use SSO logout,
|
||||
register the post-logout redirect URL as well. The OIDC callback reuses the
|
||||
origin from the signed login state and combines it with the configured path.
|
||||
Removing an alias does not invalidate state already signed with it; that state
|
||||
expires within four hours. The backend can still redirect the user to the
|
||||
removed alias, but if the frontend no longer accepts it, the user may need
|
||||
to start a new login on the canonical domain. Changing the configured path
|
||||
during a login can also require a new login. MCP OAuth always uses the
|
||||
canonical base.
|
||||
|
||||
Server-sent events (SSE) keep the full base of the request that opened the stream.
|
||||
An export requested through a trusted alias saves the full base in the job's
|
||||
parameters for the download link. Without an alias, the export worker uses its
|
||||
canonical base. Templated emails save the request's base in the template data
|
||||
and the worker uses it when it renders the email. Workers that build new links
|
||||
without a saved request base use the canonical `PENPOT_PUBLIC_URI`, as do
|
||||
server-to-server calls with no matching origin.
|
||||
|
||||
#### Upgrade or roll back the `binfile` workers
|
||||
|
||||
Before enabling aliases, upgrade every worker that consumes the `binfile` queue.
|
||||
Older workers whose export job schema does not accept `public-uri` reject jobs
|
||||
that store an alternate public base.
|
||||
|
||||
To roll back to those workers, first disable aliases on the frontend and
|
||||
all backend instances that accept requests so no new jobs store an alternate
|
||||
base. Keep the upgraded workers
|
||||
running until all queued or running export jobs with a saved alternate base
|
||||
have finished. Removing an alias does not change jobs already submitted.
|
||||
|
||||
#### Retire an alternate domain
|
||||
|
||||
1. Remove the alias from `PENPOT_TRUSTED_ORIGINS` on the frontend and backend,
|
||||
and apply the new configuration on all instances. Direct users to the
|
||||
canonical URL for new logins and links.
|
||||
2. Review pending mail in Penpot and any downstream mail queues. Stop delivery
|
||||
of sensitive links to the retired domain where possible, and reissue links
|
||||
from the canonical URL if users still need them. Queued mail can still
|
||||
contain the old base after you change the setting.
|
||||
3. Keep control of the old domain until any sensitive links and in-flight OIDC
|
||||
logins that reference it are no longer valid. Removing the alias does not
|
||||
revoke links or signed state. Cancel invitations you need to invalidate
|
||||
rather than waiting for them to expire. For flows without a supported
|
||||
way to invalidate an individual link, such as password recovery or email
|
||||
verification, wait for the token to expire. Check the lifetime for each
|
||||
flow; there is no single safe waiting period for all links.
|
||||
|
||||
## Email configuration
|
||||
|
||||
By default, <code class="language-bash">smtp</code> flag is disabled, the email will be
|
||||
|
||||
@ -194,9 +194,44 @@
|
||||
;; all path join operations works as expected.
|
||||
(u/ensure-path-slash uri-str))
|
||||
|
||||
(defn- normalize-trusted-origin
|
||||
[value]
|
||||
(when-let [[value host]
|
||||
(re-matches #"https?://(\[[0-9a-f:.]+\]|[a-z0-9.-]+)(?::[0-9]+)?"
|
||||
(str/lower value))]
|
||||
(try
|
||||
(let [url (js/URL. value)]
|
||||
;; Do not let URL parsing turn a different host spelling into a
|
||||
;; trusted host, or accept DNS names the backend does not parse.
|
||||
(when (and (= host (.-hostname url))
|
||||
(or (str/starts-with? host "[")
|
||||
(re-matches #"[0-9]+(?:\.[0-9]+){3}" host)
|
||||
(re-matches #"[a-z0-9]+(?:[a-z0-9-]*[a-z0-9])?" host)
|
||||
(re-matches #"(?:[a-z0-9]+(?:[a-z0-9-]*[a-z0-9])?\.)*[a-z](?:[a-z0-9-]*[a-z0-9])?\.?" host)))
|
||||
(.-origin url)))
|
||||
(catch :default _ nil))))
|
||||
|
||||
(defn- decode-trusted-origins
|
||||
[encoded]
|
||||
(when (string? encoded)
|
||||
(try
|
||||
(into #{} (keep normalize-trusted-origin)
|
||||
(str/split (js/atob encoded) #"[ \t\n\r\f\u000b,]+"))
|
||||
(catch :default _ nil))))
|
||||
|
||||
(defn- resolve-public-uri
|
||||
[canonical browser-origin encoded-origins]
|
||||
(let [base (normalize-uri (or canonical browser-origin))
|
||||
origins (decode-trusted-origins encoded-origins)]
|
||||
(if (contains? origins browser-origin)
|
||||
(let [{:keys [scheme host port]} (u/uri browser-origin)]
|
||||
(assoc base :scheme scheme :host host :port port))
|
||||
base)))
|
||||
|
||||
(def public-uri
|
||||
(normalize-uri (or (obj/get global "penpotPublicURI")
|
||||
(obj/get location "origin"))))
|
||||
(resolve-public-uri (obj/get global "penpotPublicURI")
|
||||
(obj/get location "origin")
|
||||
(obj/get global "penpotTrustedOrigins")))
|
||||
|
||||
(def mcp-ws-uri
|
||||
(or (some-> (obj/get global "penpotMcpServerURI") u/uri)
|
||||
|
||||
@ -14,6 +14,7 @@
|
||||
[app.common.uri :as u]
|
||||
[app.config :as cf]
|
||||
[app.main.data.event :as-alias ev]
|
||||
[app.util.globals :as globals]
|
||||
[app.util.http :as http]
|
||||
[app.util.sse :as sse]
|
||||
[beicon.v2.core :as rx]
|
||||
@ -214,6 +215,16 @@
|
||||
|
||||
:retrieve-list-of-builtin-templates {:query-params :all}})
|
||||
|
||||
(defn- get-backend-headers
|
||||
[params]
|
||||
;; RPC and OIDC select a public base on the backend. The backend validates
|
||||
;; the page origin, which is needed even for GETs without an Origin header.
|
||||
(let [origin (.-origin ^js globals/location)]
|
||||
(cond-> {"x-external-session-id" (cf/external-session-id)
|
||||
"x-event-origin" (::ev/origin (meta params))}
|
||||
(some? origin)
|
||||
(assoc "x-penpot-origin" origin))))
|
||||
|
||||
(defn- send!
|
||||
[id params options]
|
||||
(let [{:keys [response-type
|
||||
@ -244,10 +255,9 @@
|
||||
{:method method
|
||||
:uri (u/join cf/public-uri "api/main/methods/" nid)
|
||||
:credentials "include"
|
||||
:headers {"accept" "application/transit+json,text/event-stream,*/*"
|
||||
"x-external-session-id" (cf/external-session-id)
|
||||
"x-session-id" (str cf/session-id)
|
||||
"x-event-origin" (::ev/origin (meta params))}
|
||||
:headers (assoc (get-backend-headers params)
|
||||
"accept" "application/transit+json,text/event-stream,*/*"
|
||||
"x-session-id" (str cf/session-id))
|
||||
:body (when (= method :post)
|
||||
(if form-data?
|
||||
(http/form-data params)
|
||||
@ -313,8 +323,7 @@
|
||||
(->> (http/send! {:method :post
|
||||
:uri uri
|
||||
:credentials "include"
|
||||
:headers {"x-external-session-id" (cf/external-session-id)
|
||||
"x-event-origin" (::ev/origin (meta params))}
|
||||
:headers (get-backend-headers params)
|
||||
:query params})
|
||||
(rx/map http/conditional-decode-transit)
|
||||
(rx/mapcat handle-response))))
|
||||
@ -363,8 +372,7 @@
|
||||
(->> (http/send! {:method :post
|
||||
:uri (u/join cf/public-uri "api/main/methods/" (name id))
|
||||
:credentials "include"
|
||||
:headers {"x-external-session-id" (cf/external-session-id)
|
||||
"x-event-origin" (::ev/origin (meta params))}
|
||||
:headers (get-backend-headers params)
|
||||
:body (http/form-data params)})
|
||||
(rx/map http/conditional-decode-transit)
|
||||
(rx/mapcat handle-response)))
|
||||
|
||||
@ -11,6 +11,47 @@
|
||||
[cljs.test :as t :include-macros true]))
|
||||
|
||||
(def ^:private apply-devenv-defaults @#'cf/apply-devenv-defaults)
|
||||
(def ^:private resolve-public-uri @#'cf/resolve-public-uri)
|
||||
|
||||
(t/deftest public-uri-uses-only-a-configured-alternate-origin
|
||||
(let [base "https://primary.example:8443/penpot"
|
||||
origins " https://other.example,\n HTTPS://Alias.Example:443 https://alias.example:9443 "
|
||||
resolve (fn [origin]
|
||||
(str (resolve-public-uri base origin (js/btoa origins))))]
|
||||
(t/is (= "https://alias.example/penpot/" (resolve "https://alias.example")))
|
||||
(t/is (= "https://alias.example:9443/penpot/" (resolve "https://alias.example:9443")))
|
||||
(t/is (= "https://primary.example:8443/penpot/" (resolve "https://alias.example:8443")))
|
||||
(t/is (= "https://primary.example:8443/penpot/" (resolve "https://primary.example:8443")))
|
||||
(t/is (= "https://primary.example:8443/penpot/" (resolve "https://unlisted.example")))))
|
||||
|
||||
(t/deftest public-uri-supports-http-and-ipv6-aliases
|
||||
(let [base "https://primary.example/penpot/"
|
||||
origins (js/btoa "http://localhost:80 https://[::1]:9443")]
|
||||
(t/is (= "http://localhost/penpot/"
|
||||
(str (resolve-public-uri base "http://localhost" origins))))
|
||||
(t/is (= "https://[::1]:9443/penpot/"
|
||||
(str (resolve-public-uri base "https://[::1]:9443" origins))))))
|
||||
|
||||
(t/deftest public-uri-ignores-malformed-alternate-origins
|
||||
(let [base "https://primary.example/penpot/"]
|
||||
(doseq [[origin value] [["https://alias.example" "https://alias.example/"]
|
||||
["https://alias.example" "https://alias.example?"]
|
||||
["https://alias.example" "https://alias.example#"]
|
||||
["https://alias.example" "https://user@alias.example"]
|
||||
["https://alias.example" "https://alias.example:"]
|
||||
["https://alias.example" "https://alias.example:65536"]
|
||||
["https://alias.example" "https://*.example"]
|
||||
["https://alias.example" "https://alias.example\\"]
|
||||
["https://alias.example" "https://%61lias.example"]
|
||||
["https://a.-example" "https://a.-example"]
|
||||
["https://a.1example" "https://a.1example"]
|
||||
["http://127.0.0.1" "http://127.1"]
|
||||
["http://127.0.0.1" "http://0x7f000001"]]]
|
||||
(t/is (= base (str (resolve-public-uri base origin (js/btoa value)))) value))
|
||||
(t/is (= base (str (resolve-public-uri base "https://alias.example" "%"))))
|
||||
(t/is (= base (str (resolve-public-uri base "https://alias.example" nil))))
|
||||
(t/is (= "http://localhost:9001/"
|
||||
(str (resolve-public-uri nil "http://localhost:9001" nil))))))
|
||||
|
||||
(t/deftest devenv-default-disables-admin-console
|
||||
(t/testing "in devenv, without user flags, the admin-console is disabled by default"
|
||||
|
||||
@ -6,10 +6,73 @@
|
||||
|
||||
(ns frontend-tests.data.repo-test
|
||||
(:require
|
||||
[app.common.uri :as u]
|
||||
[app.config :as cf]
|
||||
[app.main.data.event :as-alias ev]
|
||||
[app.main.repo :as repo]
|
||||
[app.util.globals :as globals]
|
||||
[beicon.v2.core :as rx]
|
||||
[cljs.test :as t :include-macros true]
|
||||
[cuerdas.core :as str]))
|
||||
[cuerdas.core :as str]
|
||||
[frontend-tests.helpers.async :as async]
|
||||
[frontend-tests.helpers.http :as http-mock]
|
||||
[frontend-tests.helpers.mock :as mock]))
|
||||
|
||||
(defn- ^:async capture-request
|
||||
[command params]
|
||||
(let [request (volatile! nil)
|
||||
original (http-mock/install-fetch-mock!
|
||||
(fn [url ^js options]
|
||||
(vreset! request [url options])
|
||||
(js/Promise.resolve (http-mock/make-transit-response {}))))]
|
||||
(try
|
||||
(await (async/->promise (repo/cmd! command params)))
|
||||
@request
|
||||
(finally
|
||||
(http-mock/restore-fetch! original)))))
|
||||
|
||||
(t/deftest ^:async penpot-api-requests-send-the-page-origin
|
||||
(await (mock/with-mocks*
|
||||
{(.-origin ^js globals/location) "https://alias.example"
|
||||
cf/public-uri (u/uri "https://canonical.example/penpot/")
|
||||
cf/external-session-id (fn [] "external-session")}
|
||||
;; Keep the page origin distinct from the request URI to prove
|
||||
;; which one supplies the header.
|
||||
(doseq [[command method path]
|
||||
[[:get-profile "GET" "/penpot/api/main/methods/get-profile"]
|
||||
[:login-with-oidc "POST" "/penpot/api/auth/oidc"]
|
||||
[:upload-chunk "POST" "/penpot/api/main/methods/upload-chunk"]
|
||||
[:create-file-thumbnail "POST" "/penpot/api/main/methods/create-file-thumbnail"]]]
|
||||
(t/testing (name command)
|
||||
(let [[url ^js options] (await (capture-request command (with-meta {} {::ev/origin "test"})))
|
||||
headers (js/Headers. (.-headers options))]
|
||||
(t/is (= (str "https://canonical.example" path) url))
|
||||
(t/is (= method (.-method options)))
|
||||
(t/is (= "include" (.-credentials options)))
|
||||
(t/is (= "cors" (.-mode options)))
|
||||
(t/is (= "https://alias.example" (.get headers "x-penpot-origin")))
|
||||
(t/is (= "external-session" (.get headers "x-external-session-id")))
|
||||
(t/is (= "test" (.get headers "x-event-origin")))
|
||||
(when (= :get-profile command)
|
||||
(t/is (= "application/transit+json,text/event-stream,*/*" (.get headers "accept")))
|
||||
(t/is (= (str cf/session-id) (.get headers "x-session-id"))))
|
||||
(when (#{:upload-chunk :create-file-thumbnail} command)
|
||||
(t/is (instance? js/FormData (.-body options)))
|
||||
(t/is (not (.has headers "content-type"))))))))))
|
||||
|
||||
(t/deftest ^:async exporter-requests-do-not-send-the-page-origin
|
||||
(await (mock/with-mocks*
|
||||
{(.-origin ^js globals/location) "https://alias.example"
|
||||
cf/public-uri (u/uri "https://alias.example/penpot/")}
|
||||
(doseq [[command params path]
|
||||
[[:export {} "/penpot/api/export"]
|
||||
[:create-export-job {} "/penpot/api/export/jobs"]
|
||||
[:cancel-export-job {:job-id "job-id"} "/penpot/api/export/jobs/job-id"]]]
|
||||
(t/testing (name command)
|
||||
(let [[url ^js options] (await (capture-request command params))
|
||||
headers (js/Headers. (.-headers options))]
|
||||
(t/is (= path (.-pathname (js/URL. url))))
|
||||
(t/is (not (.has headers "x-penpot-origin")))))))))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; retryable-error? tests (synchronous)
|
||||
|
||||
@ -8,7 +8,8 @@
|
||||
(:require
|
||||
[app.util.http :as http]
|
||||
[cljs.test :as t :include-macros true]
|
||||
[frontend-tests.helpers.async :as async]))
|
||||
[frontend-tests.helpers.async :as async]
|
||||
[frontend-tests.helpers.http :as http-mock]))
|
||||
|
||||
(def ^:private uri "https://example.com/assets/file.json")
|
||||
|
||||
@ -73,3 +74,24 @@
|
||||
(t/is (false? (http/network-failure? (make-error "Error" "Failed to fetch")))))
|
||||
(t/testing "Other TypeErrors are not network failures"
|
||||
(t/is (false? (http/network-failure? (make-error "TypeError" "x is not a function"))))))
|
||||
|
||||
(t/deftest ^:async fetch-respects-omit-default-headers
|
||||
(let [requests (atom [])
|
||||
original (http-mock/install-fetch-mock!
|
||||
(fn [_url options]
|
||||
(swap! requests conj options)
|
||||
(js/Promise.resolve (js/Response. "" #js {:status 200}))))]
|
||||
(try
|
||||
(await (async/->promise (http/fetch {:method :get :uri uri})))
|
||||
(await (async/->promise (http/fetch {:method :get
|
||||
:uri uri
|
||||
:omit-default-headers true})))
|
||||
(finally
|
||||
(http-mock/restore-fetch! original)))
|
||||
(let [default-headers (aget (first @requests) "headers")
|
||||
omitted-headers (aget (second @requests) "headers")]
|
||||
(t/is (not (js/Object.hasOwn default-headers "x-penpot-origin")))
|
||||
(t/is (not (js/Object.hasOwn omitted-headers "x-penpot-origin")))
|
||||
(doseq [header ["x-frontend-version" "x-client"]]
|
||||
(t/is (js/Object.hasOwn default-headers header) header)
|
||||
(t/is (not (js/Object.hasOwn omitted-headers header)) header)))))
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user