penpot/frontend/src/app/main/router.cljs
Andrey Antukh d97972c81d
🐛 Build the SSO redirect target on the server (#12952)
* 🐛 Build the SSO redirect target on the server

The organization SSO flow took the destination URL from the client and
redirected to it after the identity provider round-trip, so any
authenticated profile could point that redirect at another domain: the
server never checked where the URL came from.

The RPC now takes the route token of the client (?screen=...&params)
and the server builds the destination out of it: the public URI plus
the query string, parsed and rendered back. The destination can no
longer leave the public URI, and the callback checks it again before
redirecting, which covers the state tokens minted before the change.

The state token also carries the profile that started the flow, so
only that session is granted the organization SSO entry: a state
prepared by someone else cannot mark the session of the one that
completes it. Whenever the RPC receives an organization id (it always
comes from the client), it also checks that the profile is a member of
the organization or its owner, instead of letting any profile start a
flow for an organization it does not belong to.

Tests cover the destination builder, a callback that ignores a
destination outside the public URI, a state that does not grant the SSO
entry to another session, and the organization access check.

AI-assisted-by: minimax-m3.1-flash

* 🐛 Check the SSO redirect target against the public URI

The callback compared the destination with a string prefix, so the two
bypasses the advisory documents (a userinfo prefix and a look-alike
host) were closed only by the trailing slash of the public URI. The
check now compares the parsed origin (scheme, host case-insensitive,
port with the default made explicit) and requires the path to be under
the base path of the public URI, so neither bypass passes.

The client sent `location.search`, the history token, whose leading `?`
is URL syntax and no part of a query string. It sends the query string
proper now (`screen=…&params`) through `rt/get-current-query-string`,
and `rt/token->query-string` is the single bridge between the two
shapes: every other consumer concatenates the token over the base path.
The server puts the separator back when it joins the destination, and
trims one that still arrives, so a browser holding the previous bundle
keeps its destination while the new one rolls out.

Building the destination can no longer break the flow: it catches its
own errors and lands on the public URI, which matters in the
deployments where the browser origin differs from the configured one.
A value that is not a route is ignored with a warning, decided by the
keys it parses into (a URL becomes a single key holding the whole URL),
and a route with no `screen`, like the root params of the application
(`template=…`), stays a usable destination.

The organization membership lookup is now shared by the check that
gates the SSO flow and the one that raises, so the two cannot drift
apart, and the docstring of the RPC lists `:no-organization-access`
next to `:no-team-access`.

`rt/nav-raw` returns its `:href`/`:uri` through `@event`, as its
sibling `rt/navigate` already did. Nothing in the app listens to
`::rt/nav-raw`, so the callers behave the same; the SSO test now reads
the destination from the event instead of intercepting the helper.

Tests cover the two bypasses and the base-path rule, the RPC with an
unusable destination, the value that is not a route, the request that
carries both ids, an organization that does not exist, the query string
the frontend sends, and the two router helpers.

AI-assisted-by: minimax-m3.1-flash

* ♻️ Deduplicate SSO destination URL building

The backend had an unreachable blank check and a one-line wrapper around
the URI helper in build-dest-url. On the client, the SSO retry and error
flows each assembled the destination from public-uri and the route params.

Flatten build-dest-url with a cond and call u/query-string->map directly.
Add rt/token->url as the single client helper for absolute route URLs, with
tests for both token shapes and for a blank token. Update the routing memory
with the new helper contract.

AI-assisted-by: hy4-flash-free
2026-11-16 17:34:49 +01:00

284 lines
8.7 KiB
Clojure

;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) KALEIDOS SUBSIDIARY SL
(ns app.main.router
(:refer-clojure :exclude [resolve])
(:require
[app.common.data.macros :as dm]
[app.common.uri :as u]
[app.config :as cf]
[app.main.data.event :as ev]
[app.util.browser-history :as bhistory]
[app.util.dom :as dom]
[app.util.globals :as globals]
[app.util.timers :as ts]
[beicon.v2.core :as rx]
[cuerdas.core :as str]
[potok.v2.core :as ptk]))
;; --- Router API
;; Query-string routing: `router` is the set of enabled route names
;; (see `app.main.ui.routes/routes`). The `screen` query param carries
;; the route name; every other param travels as a plain query param.
(def ^:private history-path-prefix
"The application base path. The history token is the query string
appended to it; the path never carries the token."
(:path cf/public-uri))
(defn create
[routes]
routes)
(defn resolve
"Build the history token (`?screen=<name>&params`) for a route.
Returns nil when the route id is not enabled."
([router id]
(resolve router id {}))
([router id params]
(when (contains? router id)
;; The target screen always wins: callers often forward the
;; current query params (which carry the previous screen).
(str "?" (u/map->query-string
(into {:screen (name id)} (dissoc params :screen)))))))
(defn resolve-uri
"Build the absolute URL string for a route under `cf/public-uri`."
[router id params]
(when-let [token (resolve router id params)]
(dm/str cf/public-uri "?" (subs token 1))))
(defn initialize-router
[routes]
(ptk/reify ::initialize-router
ptk/UpdateEvent
(update [_ state]
(assoc state :router (create routes)))))
(defn encode-url
[url]
(js/encodeURIComponent url))
;; --- Navigate (Event)
(defn get-query-param
"Safely extracts a scalar value for a query param key from a params
map. When the same key appears multiple times in a URL,
query-string->map returns a vector for that key; this function
always returns a single (last) element in that case, so downstream
consumers such as parse-long always receive a plain string or nil."
[params k]
(let [v (get params k)]
(if (sequential? v) (peek v) v)))
(defn match
"Given the enabled routes and the current history token (the query
string, `?screen=<name>&params`), return a match shaped like the old
reitit one (`:data/:name`, `:params/:query`, `:query-params`).
Return nil when there is no usable `screen`."
[router token]
(let [query (if (str/starts-with? (or token "") "?")
(subs token 1)
(or token ""))
query-params (u/query-string->map query)
screen (some-> (get-query-param query-params :screen) keyword)]
(when (contains? router screen)
{:data {:name screen}
:params {:path {} :query query-params}
:query-params query-params})))
(defn navigated
[match send-event-info?]
(ptk/reify ::navigated
IDeref
(-deref [_] match)
ptk/WatchEvent
(watch [_ _ _]
(when send-event-info?
(let [route (dm/get-in match [:data :name])
params (get match :query-params)]
(rx/of (ev/event
(assoc params
::ev/name "navigate"
:route (name route)))))))
ptk/UpdateEvent
(update [_ state]
(-> state
(assoc :route match)
(dissoc :exception)))))
(defn navigate
[id params & {:keys [::replace ::new-window] :as options}]
(ptk/reify ::navigate
IDeref
(-deref [_]
{:id id
:params params
:options options})
ptk/EffectEvent
(effect [_ state _]
(let [router (:router state)
path (resolve router id params)]
(if ^boolean new-window
(let [name (or (::window-name options) "_blank")
uri (assoc cf/public-uri :query (some-> path (subs 1)))]
(dom/open-new-window uri name nil))
(ts/asap
#(if ^boolean replace
(bhistory/replace-token! history-path-prefix path)
(bhistory/set-token! history-path-prefix path))))))))
(defn assign-exception
[error]
(ptk/reify ::assign-exception
ptk/UpdateEvent
(update [_ state]
(if (nil? error)
(dissoc state :exception)
(assoc state :exception error)))))
(defn nav
([id] (navigate id nil))
([id params] (navigate id params))
([id params & {:as options}]
(navigate id params options)))
(defn lookup-name
[state]
(dm/get-in state [:route :data :name]))
;; FIXME: rename to lookup-params
(defn get-params
[state]
(dm/get-in state [:route :params :query]))
(defn nav-back
[]
(ptk/reify ::nav-back
ptk/EffectEvent
(effect [_ _ _]
(ts/asap dom/browser-back))))
(defn nav-back-local
"Navigate back only if the previous page is in penpot app."
[]
(let [location (.-location js/document)
referrer (u/uri (.-referrer js/document))]
(when (or (nil? (:host referrer))
(= (.-hostname location) (:host referrer)))
(nav-back))))
(defn nav-root
"Navigate to the root page."
[]
(ptk/reify ::nav-root
ptk/EffectEvent
(effect [_ _ _]
(set! (.-href globals/location) "/"))))
(defn reload
[force?]
(ptk/reify ::reload
ptk/EffectEvent
(effect [_ _ _]
(ts/asap (partial dom/reload-current-window force?)))))
(defn nav-raw
"Navigate to a raw URL, out of the router.
The destination is exposed through `@event`, like `navigate` does, so
listeners and tests can tell where the user is being sent."
[& {:keys [href uri] :as props}]
(ptk/reify ::nav-raw
IDeref
(-deref [_] props)
ptk/EffectEvent
(effect [_ _ _]
(cond
(string? uri)
(.replace globals/location uri)
(string? href)
(set! (.-href globals/location) href)))))
(defn get-current-href
[]
(.-href globals/location))
(defn token->query-string
"The query string of `token`, without the `?` that separates it from the
path. The history token is `location.search`, so it carries that delimiter;
a query string does not, and this is what the organization SSO RPC takes: the
server joins it under its own public URI and puts the separator back."
[token]
(let [token (or token "")]
(if (str/starts-with? token "?")
(subs token 1)
token)))
(defn token->url
"Build the absolute URL for a route token under `cf/public-uri`. Accepts
the token in either shape: with its leading `?` or as a bare query string.
A blank token lands on the public URI, without a trailing separator."
[token]
(let [query-string (token->query-string token)]
(if (str/blank? query-string)
(str cf/public-uri)
(str cf/public-uri "?" query-string))))
(defn get-current-token
"Return the current history token: the query string that carries the route,
with the leading `?` that separates it from the path. The application
concatenates it over the base path, so it keeps the delimiter; use
`get-current-query-string` for the value the SSO flow sends to the backend.
The server builds the destination URL out of that one, so the client never
chooses the origin of it."
[]
(bhistory/get-token))
(defn get-current-query-string
"The query string of the current route (see `token->query-string`)."
[]
(token->query-string (get-current-token)))
;; --- History API
;; Check the urls to see if we need to send the navigated event.
;; If two query strings select the same screen we only send the event
;; when there is a change in the parameters `screen`, `file-id`,
;; `page-id` or `team-id`
(defn- send-event-info?
[old-url new-url]
(let [params [:screen :file-id :page-id :team-id]
new-params (-> (u/uri new-url) :query u/query-string->map (select-keys params))
old-params (-> (u/uri old-url) :query u/query-string->map (select-keys params))]
(not= new-params old-params)))
(defn initialize-history
[on-change]
(ptk/reify ::initialize-history
ptk/EffectEvent
(effect [_ state stream]
(let [stopper (rx/filter (ptk/type? ::initialize-history) stream)
router (:router state)]
(ts/schedule #(on-change router (bhistory/get-token) true))
(->> (rx/concat
(rx/of nil nil)
bhistory/token-changes)
(rx/buffer 2 1)
(rx/take-until stopper)
(rx/subs!
(fn [[old-url new-url]]
(when (some? new-url)
(let [send? (or (nil? old-url) (send-event-info? old-url new-url))]
(on-change router new-url send?))))))))))