diff --git a/.serena/memories/backend/auth-permissions-product-domains.md b/.serena/memories/backend/auth-permissions-product-domains.md index 5391802b1d..d49d2c4bff 100644 --- a/.serena/memories/backend/auth-permissions-product-domains.md +++ b/.serena/memories/backend/auth-permissions-product-domains.md @@ -11,6 +11,8 @@ - Account lockout (flag `:account-lockout`, `app.auth.login-lockout`) is Redis-backed and keyed per profile id. Password and LDAP flows check/increment on the profile derived from the typed email and clear on the profile that actually logs in. - Lockout and RPC rate limits share the `app.http.errors/handle-error :rate-limit` HTTP path: status 429, body `{:type :rate-limit :code ... :hint ... :ttl ...}`, and any supplied `::http/headers` preserved. Account lockout raises `:code :account-locked` and, when it carries a non-nil `:ttl` (seconds), the handler adds `retry-after`. The RPC limiter (`app.rpc.rlimit`) raises `:code :request-blocked` and sets `retry-after` itself in `::http/headers` (seconds until the longest rejecting limit resets), alongside `x-rate-limit-remaining`/`x-rate-limit-reset`. CORS (`app.http.middleware/with-cors-headers`) exposes `content-type`, `retry-after`, and both `x-rate-limit-*` headers. External flags: `enable-account-lockout`, `enable-rpc-rlimit`. - Logout may return an OIDC provider redirect URI when the session claims include provider/session data and the provider has a logout URI. +- Organization SSO (Nitrate): the RPC `check-nitrate-sso` takes the route's **query string proper** (`:query-string`, e.g. `screen=workspace&team-id=…`), never a URL and never with the `?` separator: the client strips it (`rt/token->query-string`) and the server puts it back. The server builds the destination with `app.auth.oidc/build-dest-url` (`public-uri` + `?` + the params, parsed and rendered back), so the redirect can never leave the public URI; a value whose parsed keys are not param names is not a route: a URL parses into a single key holding the whole URL, and a key carrying `:`, `/`, `?` or `#` is rejected with a `:warn` and the user lands on the public URI (the RPC never fails because of it). Do not reason from `u/map->query-string`: it keeps a valueless key as `key=`, so rendering is not what filters a URL out — the key shape is. A leading `?` is still trimmed server-side, so a client bundled before the trim keeps its destination. Never require `screen`: the root of the app carries its params instead of a screen (`?template=…`), and `check-nitrate-sso` is called from that branch too (`dtm/resolve-login-team-id`, which today reads only `:authorized` and never follows the redirect, so a wrong destination there is a silent `:warn` and not a visible break); the callback re-checks the destination before redirecting, which covers state tokens minted before that. The state token also carries `:profile-id`: only that session is granted the `props :sso` entry (`session-mismatch` otherwise, and the redirect still happens). +- Organization SSO needs `app.nitrate/organization-access?` whenever the RPC receives an `:organization-id` (that id always comes from the client): the profile must be a member of the organization or its owner; otherwise the RPC answers `{:authorized true :reason :no-organization-access}`, the same short-circuit shape as `:no-team-access`. - Invitation tokens are verified through token issuers and only accepted when the token member id/email matches the authenticated profile; otherwise login proceeds without consuming the invitation. - When public registration is disabled, invitation-based password registration also requires a matching, non-expired `team_invitation` row; registration revalidates it under a row lock before creating the profile. SSO registration (OIDC and compatible providers) follows the OIDC callback gate: it requires `:registration` or `:oidc-registration`, or a team invitation token issued for the registering email (an invitation substitutes the flags only when `member-email` matches the OIDC/`prepared-register` email via `clean-email`, as in the password flow, which raises `:email-does-not-match-invitation` otherwise). The OIDC callback verifies the invitation JWT and the email before redirecting to register, and `register-profile` revalidates the invitation under a row lock when no SSO flag is set; it never requires password login. Only OIDC-typed backends (`oidc-provider-types` in `app.auth.oidc`) take the SSO registration gate; any other `:backend` in a prepared-register token is rejected as `:invalid-token`. - Access tokens (`app.http.access-token`): personal tokens have JWT issuer `access-token` and DB type other than `mcp`; MCP tokens have issuer `urn:penpot:mcp-token` (`actoken/mcp-token-issuer`) and DB type `mcp`. Authentication requires issuer and type to agree, and the claim `uid` to match the row's profile; other issuers and undecryptable tokens are treated as anonymous. diff --git a/.serena/memories/frontend/routing-app-shell-subtleties.md b/.serena/memories/frontend/routing-app-shell-subtleties.md index 8c43a30161..936bcf911e 100644 --- a/.serena/memories/frontend/routing-app-shell-subtleties.md +++ b/.serena/memories/frontend/routing-app-shell-subtleties.md @@ -7,6 +7,8 @@ - `set-token!` and `replace-token!` are deliberately asymmetric. `set-token!` is a total no-op when the token already is the current one (no URL write, no report), so navigating to the screen you are on cannot grow the history stack. `replace-token!` always writes and always reports, because it is how the app corrects the URL in place (legacy `#/…` translation, cleaned share links) and that correction must reach the router even when the token did not change. This matches `Html5History`, which did the same; do not "fix" the asymmetry without deciding what navigates to the current screen. - `app.util.dom/replace-history-state!` is the deliberate bypass used by `app.main.ui.dashboard`/`app.main.ui.static` to rewrite the URL **without** routing. Keep using it there instead of `replace-token!`, which would re-enter the router. - Route params live entirely in the query map under the reserved `screen` key; duplicate query params can become vectors, so use `rt/get-query-param` when a scalar is required. +- The organization SSO flow sends the **query string** (`rt/get-current-query-string`), not the URL and not the token: the backend builds the destination URL from `public-uri` + `?` + those params, so the client never chooses the origin of the redirect. The history token (`rt/get-current-token`, `location.search`) keeps its leading `?` because every other consumer concatenates it over the base path (`str cf/public-uri token`, `dom/append-query-param`, `dom/remove-query-param`); `rt/token->query-string` is the only bridge between the two shapes, so do not trim at a call site by hand; `rt/token->url` is the single client builder of an absolute destination from either shape (used by the SSO retry and error flow), so do not assemble `public-uri + "?" + params` at call sites. The gate is not the only caller: `dtm/resolve-login-team-id` runs from the root branch of `on-navigate` too, and there the URL carries its params instead of a screen (`?template=…`) — that call only reads `:authorized`, so it never follows the destination, which is exactly why a wrong destination there goes unnoticed. Do not add a rule that requires `screen`. See `mem:backend/auth-permissions-product-domains`. +- The router events expose their payload through `@event` (`IDeref`): `rt/navigate` returns `{:id :params :options}` and `rt/nav-raw` returns its `:href`/`:uri`. `rt/nav-raw` is the way out of the router (raw URL, outside the token scheme) and nothing in the app listens to `::rt/nav-raw`; the destination travels in the effect, so `@event` is the only way to tell where the user is being sent (tests included). - Legacy `#/…` hash URLs translate client-side to the query format (one-version compat; see `legacy-routes` in `app.main.ui.routes`, TODO(next-version) to delete). - Unknown/empty routes trigger an extra `get-profile`/`get-teams` check before redirecting. This avoids invitation and root-route race conditions. - The root app has two error layers, and they reset differently. `:exception` in the store renders `static/exception-page*` directly and is cleared by `rt/navigated`; a React render error is caught by `app.main.ui.error-boundary` (`react-error-boundary`), whose error lives in internal React state that only `reset-error-boundary` clears. Because every exit from the error page (the logo, the no-permission dialogs, the SSO dialog, the feedback link) only *navigates*, the boundary is given `:resetKeys [(eb/reset-key route)]` — the screen name — so a navigation counts as a fresh attempt at rendering. Three traps in that `resetKeys` value, all learned the hard way: it must be a real JS array (`#js [...]`), never a ClojureScript vector, because `react-error-boundary` reads `.length` and `.some` and a `PersistentVector` has neither, so `componentDidUpdate` throws `some is not a function`; it must hold the screen name as a *string*, because the library compares entries with `Object.is` and ClojureScript does not intern keywords, so two equal keywords are two objects and a keyword key would read as new on every route rebuilt, resetting the boundary on a param change inside the same screen; and it must be the screen rather than the params, so a param change does not replay the screen that just crashed. Navigating to the *same* screen therefore does not reset, and a reload is the only way out of that case. diff --git a/backend/src/app/auth/oidc.clj b/backend/src/app/auth/oidc.clj index 477236c291..0de9163f84 100644 --- a/backend/src/app/auth/oidc.clj +++ b/backend/src/app/auth/oidc.clj @@ -690,15 +690,113 @@ (assoc :query (u/map->query-string params)))] (redirect-response uri)))) +(defn- public-uri + "The configured public URI, parsed, with the app base path normalized with + a trailing slash." + [] + (u/ensure-path-slash (u/uri (cf/get :public-uri)))) + +(defn- public-uri-base + "The public URI as a string, with the app base path normalized with a + trailing slash. Every URL the server builds starts here, so the app base + path is never lost." + [] + (str (public-uri))) + (defn- redirect-with-organization-sso-error [{:keys [dest-url organization-id organization-name]}] - (-> (str (or dest-url (cf/get :public-uri))) + (-> (str (or dest-url (public-uri-base))) (u/append-query-param :sso-error true) (u/append-query-param :organization-id organization-id) (cond-> organization-name (u/append-query-param :organization-name organization-name)) (redirect-response))) +(defn- routable-params? + "True when `params` are params of a route: at least one, and no key carries + a scheme, a path or a fragment. `screen=workspace&team-id=…` and the root + params of the application (`template=…`) qualify; `https://evil.example/` + does not." + [params] + (and (seq params) + (every? #(nil? (re-find #"[/:?#]" (name %))) (keys params)))) + +(defn build-dest-url + "Return the absolute URL for `query-string` under the current public URI. + + The query string is the route of the client (`screen=…¶ms`, and the root + of the application may carry only its params, like `template=…`): it does not + carry the `?` that separates it from the path, which is put back here, so the + destination is always built by the server and the client only picks the route. + A value that still comes with the separator is trimmed, so a client bundled + before that change keeps its destination. + + The params are parsed and rendered back, so a value that is not a route never + becomes a destination: it is ignored with a warning and the user lands on the + public URI, which is also where a blank one lands." + [query-string] + (try + (let [base (public-uri-base) + query (str query-string) + route (if (str/starts-with? query "?") + (subs query 1) + query) + params (u/query-string->map route)] + (cond + (str/blank? query) + base + + (not (routable-params? params)) + (do (l/warn :hint "ignoring a redirect target that is not a route" + :query-string (subs route 0 (min 200 (count route)))) + base) + + :else + (str base "?" (u/map->query-string params)))) + (catch Exception e + ;; The destination must never break the SSO flow: a query string the + ;; server cannot parse lands on the public URI instead. + (l/warn :hint "could not build the redirect target" :cause e) + (public-uri-base)))) + +(defn- same-origin? + "True when `uri` has the same origin as `base`: scheme, host (case + insensitive) and port, with the default port made explicit." + [uri base] + (let [default-port (fn [scheme] (if (= "https" (str/lower (str scheme))) 443 80)) + port (fn [u] (or (:port u) (default-port (:scheme u))))] + (and (= (str/lower (str (:scheme uri))) + (str/lower (str (:scheme base)))) + (= (str/lower (str (:host uri))) + (str/lower (str (:host base)))) + (= (port uri) (port base))))) + +(defn- under-base-path? + "True when the path of `uri` is under the base path of `base`." + [uri base] + (str/starts-with? (str (:path uri)) (:path base))) + +(defn- trusted-dest-url + "Return `dest-url` when it points inside the current public URI, nil + otherwise. + + The destination is built by the server (see `build-dest-url`), but state + tokens minted before that was the case may carry any URL, so the callback + checks the destination before redirecting to it. The check compares the + parsed origin, so neither a userinfo prefix + (`https://penpot.example.com@evil.example/`) nor a look-alike host + (`https://penpot.example.com.evil.example/`) can pass, and it requires + the path to be under the base path of the public URI, so the destination + stays inside the application." + [dest-url] + (when (some? dest-url) + (let [dest (try (u/uri (str dest-url)) (catch Exception _ nil)) + base (public-uri)] + (when (and (some? dest) + (same-origin? dest base) + (under-base-path? dest base)) + (str dest-url))))) + (defn- redirect-to-register [cfg info provider] (let [info (assoc info @@ -915,11 +1013,18 @@ (defn build-organization-sso-auth-redirect-uri "Build the OIDC authorization redirect URI for an organization SSO config. - Raises if the config is incomplete or OIDC discovery fails." - [cfg sso & {:keys [dest-url organization-id provider]}] + Raises if the config is incomplete or OIDC discovery fails. + + `query-string` is the route of the client (`screen=…¶ms`, the query + string proper, without its separator): the destination is built here, so it + 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]}] (let [organization-id (or organization-id (:organization-id sso)) issuer (organization-sso-discovery-uri sso) - dest-url (or dest-url (str (cf/get :public-uri)))] + dest-url (build-dest-url query-string)] (when-not issuer (raise-invalid-sso-config :hint "missing issuer" @@ -929,6 +1034,7 @@ state-token (tokens/generate cfg {:iss "oidc" :dest-url dest-url :organization-id organization-id + :profile-id profile-id :issuer issuer :exp (ct/in-future "4h")})] (build-auth-redirect-uri oidc-provider state-token)) @@ -1024,25 +1130,39 @@ (defn- organization-sso-callback-handler "Handle the organization-SSO branch of the OIDC callback: state carries :dest-url — exchange the authorization code with the OIDC provider to - verify authentication actually occurred, then redirect back to dest-url." + verify authentication actually occurred, then redirect back to dest-url. + + The state also carries the :profile-id that started the flow: only that + session is granted the organization SSO entry, so a state prepared by + someone else cannot mark the session of the one who completes it." [cfg request state code] - (let [dest-url (:dest-url state)] + (let [dest-url (trusted-dest-url (:dest-url state))] (try (let [organization-id (:organization-id state) sso (nitrate/call cfg :get-organization-sso {:organization-id organization-id}) provider (prepare-organization-sso-provider cfg sso) _info (get-info cfg provider state code) session (session/get-session request) - exp (ct/in-future {:hours 4})] - (when (and session organization-id) - (let [props (-> (or (:props session) {}) - (update :sso assoc organization-id exp))] - (session/update-session (::session/manager cfg) (assoc session :props props)) + exp (ct/in-future {:hours 4}) + ;; A state minted before the profile claim existed never + ;; matches, and neither does the session of another profile. + same-profile? (and (some? session) + (some? (:profile-id state)) + (= (:profile-id state) (:profile-id session)))] + (if (and (some? session) (not same-profile?)) + (submit-organization-sso-auth-event + cfg request (:profile-id session) organization-id "organization-sso-auth-failed" + :failure-reason "session-mismatch") + (do + (when (and session organization-id) + (let [props (-> (or (:props session) {}) + (update :sso assoc organization-id exp))] + (session/update-session (::session/manager cfg) (assoc session :props props)) + (submit-organization-sso-auth-event + cfg request (:profile-id session) organization-id "organization-sso-token-issued"))) (submit-organization-sso-auth-event - cfg request (:profile-id session) organization-id "organization-sso-token-issued"))) - (submit-organization-sso-auth-event - cfg request (:profile-id session) organization-id "organization-sso-auth-succeeded") - (redirect-response dest-url)) + cfg request (:profile-id session) organization-id "organization-sso-auth-succeeded"))) + (redirect-response (or dest-url (public-uri-base)))) (catch Throwable cause (let [{:keys [code]} (ex-data cause)] (binding [l/*context* (errors/request->context request)] @@ -1060,7 +1180,7 @@ (let [organization-id (:organization-id state) organization-name (:name (nitrate/call cfg :get-organization-summary {:organization-id organization-id}))] (redirect-with-organization-sso-error - {:dest-url dest-url + {:dest-url (or dest-url (public-uri-base)) :organization-id organization-id :organization-name organization-name})))))) diff --git a/backend/src/app/nitrate.clj b/backend/src/app/nitrate.clj index af1e915903..6fb33b6ebf 100644 --- a/backend/src/app/nitrate.clj +++ b/backend/src/app/nitrate.clj @@ -772,12 +772,19 @@ :organization-id (:organization-id params)})) team)) +(defn- organization-membership + "The membership of `profile-id` in `organization-id`, as Nitrate reports it. + The profile travels in the path of the Nitrate endpoint, so no acting + profile is sent." + [cfg profile-id organization-id] + (call cfg :get-organization-membership {:profile-id profile-id + :organization-id organization-id})) + (defn assert-membership "Verifies that the user is a member of the organization. Raises an exception if the organization doesn't exist or the user is not a member." [cfg profile-id organization-id] - (let [membership (call cfg :get-organization-membership {:profile-id profile-id - :organization-id organization-id})] + (let [membership (organization-membership cfg profile-id organization-id)] (when-not (:organization-id membership) (ex/raise :type :validation :code :organization-does-not-exist)) @@ -785,3 +792,18 @@ (when-not (:is-member membership) (ex/raise :type :validation :code :user-doesnt-belong-organization)))) + +(defn organization-access? + "True when `profile-id` may act for `organization-id`: it is a member of + the organization or its owner. + + The organization id reaches the backend from the client, so the flows that + take one have to check it: without this check any authenticated profile + could start a flow for an organization it does not belong to." + [cfg profile-id organization-id] + (let [membership (organization-membership cfg profile-id organization-id)] + (if (:is-member membership) + true + (= (:owner-id (call cfg :get-organization-summary {:organization-id organization-id + ::rpc/profile-id profile-id})) + profile-id)))) diff --git a/backend/src/app/rpc/commands/nitrate.clj b/backend/src/app/rpc/commands/nitrate.clj index af52bede6f..61243719c8 100644 --- a/backend/src/app/rpc/commands/nitrate.clj +++ b/backend/src/app/rpc/commands/nitrate.clj @@ -704,7 +704,7 @@ [:map {:title "CheckNitrateSsoParams"} [:team-id {:optional true} ::sm/uuid] [:organization-id {:optional true} ::sm/uuid] - [:url ::sm/uri]] + [:query-string [:string {:max 2048}]]] [::sm/contains-any #{:team-id :organization-id}]]) (sv/defmethod ::check-nitrate-sso @@ -714,40 +714,57 @@ session already holds a valid entry for the organization, and {:authorized true :reason :no-team-access} when the gate was skipped because the user cannot access the team; the reason lets the client tell a usable session - apart from a plain permission failure. + apart from a plain permission failure. When an organization id comes with the + request, the gate is also skipped with + {:authorized true :reason :no-organization-access} when the profile neither + belongs to that organization nor owns it. Returns {:authorized false :redirect-uri } when SSO is active; the client must redirect there. The OIDC provider itself handles re-authentication transparently if the user already has an active SSO session. - A nil :redirect-uri means SSO is required but the provider is not usable." + A nil :redirect-uri means SSO is required but the provider is not usable. + + The :query-string is the route of the client as a query string + (`screen=…¶ms`, without the `?` that separates it from the path; the root + of the application may carry only its params, like `template=…`): the server + builds the destination URL from it, so it can never point outside the public + URI. A value without params of its own is not a route, is ignored with a + warning, and the user lands on the home page." {::rpc/auth true ::doc/added "2.18" ::sm/params schema:check-nitrate-sso ::nitrate/sso false} - [cfg {:keys [::rpc/profile-id team-id organization-id url] :as params}] + [cfg {:keys [::rpc/profile-id team-id organization-id query-string] :as params}] (if (contains? cf/flags :admin-console) (if (and team-id (not (teams/has-read-permissions? cfg profile-id team-id))) ;; Let the destination RPC enforce its own permissions. Starting SSO before ;; access is established sends unrelated users through the organization's IdP. {:authorized true :reason :no-team-access} - (let [request (rph/get-request params) - {:keys [authorized sso]} (nitrate/sso-session-authorized? cfg organization-id team-id request)] - (if authorized - {:authorized true :reason :sso-satisfied} - (if (oidc/organization-sso-discovery-uri sso) - (try - (let [redirect-uri (oidc/build-organization-sso-auth-redirect-uri - cfg sso - :dest-url url - :organization-id organization-id) - organization-id (or organization-id (:organization-id sso))] - (oidc/submit-organization-sso-auth-started-event - cfg request profile-id organization-id) - {:authorized false :redirect-uri redirect-uri}) - (catch Throwable cause - (oidc/submit-organization-sso-auth-failed-event - cfg request profile-id (or organization-id (:organization-id sso)) cause) - (throw cause))) - {:authorized false - :redirect-uri nil})))) + (if (and organization-id + (not (nitrate/organization-access? cfg profile-id organization-id))) + ;; The organization id comes from the client: without this check any + ;; authenticated profile could start a flow for an organization it does + ;; not belong to. + {:authorized true :reason :no-organization-access} + (let [request (rph/get-request params) + {:keys [authorized sso]} (nitrate/sso-session-authorized? cfg organization-id team-id request)] + (if authorized + {:authorized true :reason :sso-satisfied} + (if (oidc/organization-sso-discovery-uri sso) + (try + (let [redirect-uri (oidc/build-organization-sso-auth-redirect-uri + cfg sso + :query-string query-string + :organization-id organization-id + :profile-id profile-id) + organization-id (or organization-id (:organization-id sso))] + (oidc/submit-organization-sso-auth-started-event + cfg request profile-id organization-id) + {:authorized false :redirect-uri redirect-uri}) + (catch Throwable cause + (oidc/submit-organization-sso-auth-failed-event + cfg request profile-id (or organization-id (:organization-id sso)) cause) + (throw cause))) + {:authorized false + :redirect-uri nil}))))) {:authorized true :reason :sso-satisfied})) diff --git a/backend/test/backend_tests/auth_oidc_test.clj b/backend/test/backend_tests/auth_oidc_test.clj index 42a7e4f9d4..8b624a6fbb 100644 --- a/backend/test/backend_tests/auth_oidc_test.clj +++ b/backend/test/backend_tests/auth_oidc_test.clj @@ -10,6 +10,7 @@ [app.common.data :as d] [app.common.exceptions :as ex] [app.common.time :as ct] + [app.common.uri :as u] [app.common.uuid :as uuid] [app.config :as cf] [app.http.session :as session] @@ -648,69 +649,73 @@ (t/deftest organization-sso-callback-success-emits-succeeded ;; No session on the request → auth-succeeded only (no token-issued). (let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist) - state (make-state-token cfg {:dest-url "https://penpot.example.com/#/workspace" + state (make-state-token cfg {:dest-url "https://penpot.example.com/?screen=workspace" :organization-id test-organization-id}) request (default-request cfg :state state) events (atom [])] - (with-redefs [app.nitrate/call (constantly {:active true}) - app.auth.oidc/prepare-organization-sso-provider (constantly {:type "oidc"}) - app.auth.oidc/get-info (constantly {}) - app.loggers.audit/submit (fn [_cfg event] (swap! events conj event))] - (let [result (#'oidc/callback-handler cfg request)] - (t/is (= "https://penpot.example.com/#/workspace" (redirect-location result))) - (t/is (= ["organization-sso-auth-succeeded"] (mapv :name @events))) - (t/is (= test-organization-id (get-in (first @events) [:props :organization-id]))))))) + (binding [cf/config {:public-uri "https://penpot.example.com"}] + (with-redefs [app.nitrate/call (constantly {:active true}) + app.auth.oidc/prepare-organization-sso-provider (constantly {:type "oidc"}) + app.auth.oidc/get-info (constantly {}) + app.loggers.audit/submit (fn [_cfg event] (swap! events conj event))] + (let [result (#'oidc/callback-handler cfg request)] + (t/is (= "https://penpot.example.com/?screen=workspace" (redirect-location result))) + (t/is (= ["organization-sso-auth-succeeded"] (mapv :name @events))) + (t/is (= test-organization-id (get-in (first @events) [:props :organization-id])))))))) (t/deftest organization-sso-callback-success-with-session-emits-token-issued (let [manager (session/inmemory-manager) cfg (assoc (dissoc base-cfg :app.email/blacklist :app.email/whitelist) ::session/manager manager) - state (make-state-token cfg {:dest-url "https://penpot.example.com/#/workspace" - :organization-id test-organization-id}) + state (make-state-token cfg {:dest-url "https://penpot.example.com/?screen=workspace" + :organization-id test-organization-id + :profile-id test-profile-id}) request (default-request cfg :state state) events (atom []) sess {:id (uuid/next) :profile-id test-profile-id :props {}}] - (with-redefs [app.nitrate/call (constantly {:active true}) - app.auth.oidc/prepare-organization-sso-provider (constantly {:type "oidc"}) - app.auth.oidc/get-info (constantly {}) - app.http.session/get-session (constantly sess) - app.loggers.audit/submit (fn [_cfg event] (swap! events conj event))] - (let [result (#'oidc/callback-handler cfg request) - names (mapv :name @events) - stored (session/read-session manager (:id sess))] - (t/is (= "https://penpot.example.com/#/workspace" (redirect-location result))) - (t/is (= ["organization-sso-token-issued" - "organization-sso-auth-succeeded"] - names)) - (t/is (= test-organization-id - (get-in (first @events) [:props :organization-id]))) - (t/is (= test-profile-id (:profile-id (first @events)))) - (t/is (= #{:organization-id} - (set (keys (:props (first @events)))))) - (t/is (contains? (get-in stored [:props :sso]) test-organization-id)))))) + (binding [cf/config {:public-uri "https://penpot.example.com"}] + (with-redefs [app.nitrate/call (constantly {:active true}) + app.auth.oidc/prepare-organization-sso-provider (constantly {:type "oidc"}) + app.auth.oidc/get-info (constantly {}) + app.http.session/get-session (constantly sess) + app.loggers.audit/submit (fn [_cfg event] (swap! events conj event))] + (let [result (#'oidc/callback-handler cfg request) + names (mapv :name @events) + stored (session/read-session manager (:id sess))] + (t/is (= "https://penpot.example.com/?screen=workspace" (redirect-location result))) + (t/is (= ["organization-sso-token-issued" + "organization-sso-auth-succeeded"] + names)) + (t/is (= test-organization-id + (get-in (first @events) [:props :organization-id]))) + (t/is (= test-profile-id (:profile-id (first @events)))) + (t/is (= #{:organization-id} + (set (keys (:props (first @events)))))) + (t/is (contains? (get-in stored [:props :sso]) test-organization-id))))))) (t/deftest organization-sso-callback-error-emits-failed (let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist) - state (make-state-token cfg {:dest-url "https://penpot.example.com/#/workspace" + state (make-state-token cfg {:dest-url "https://penpot.example.com/?screen=workspace" :organization-id test-organization-id}) request (default-request cfg :state state) events (atom [])] - (with-redefs [app.nitrate/call (fn [_cfg method _params] - (case method - :get-organization-sso {:active true} - :get-organization-summary {:name "Organization"})) - app.auth.oidc/prepare-organization-sso-provider (constantly {:type "oidc"}) - app.auth.oidc/get-info (fn [& _] - (ex/raise :type :internal - :code :unable-to-retrieve-user-info)) - app.loggers.audit/submit (fn [_cfg event] (swap! events conj event))] - (#'oidc/callback-handler cfg request) - (t/is (= ["organization-sso-auth-failed"] (mapv :name @events))) - (t/is (= {:organization-id test-organization-id - :failure-reason "user-info-failed"} - (:props (first @events))))))) + (binding [cf/config {:public-uri "https://penpot.example.com"}] + (with-redefs [app.nitrate/call (fn [_cfg method _params] + (case method + :get-organization-sso {:active true} + :get-organization-summary {:name "Organization"})) + app.auth.oidc/prepare-organization-sso-provider (constantly {:type "oidc"}) + app.auth.oidc/get-info (fn [& _] + (ex/raise :type :internal + :code :unable-to-retrieve-user-info)) + app.loggers.audit/submit (fn [_cfg event] (swap! events conj event))] + (#'oidc/callback-handler cfg request) + (t/is (= ["organization-sso-auth-failed"] (mapv :name @events))) + (t/is (= {:organization-id test-organization-id + :failure-reason "user-info-failed"} + (:props (first @events)))))))) (t/deftest organization-sso-oauth-error-emits-failed-without-changing-redirect (let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist) @@ -729,6 +734,155 @@ :failure-reason "access-denied"} (:props (first @events))))))))) +(t/deftest build-dest-url-builds-the-destination-on-the-public-uri + (binding [cf/config {:public-uri "https://penpot.example.com"}] + (t/testing "the route is appended to the public uri, separator included" + (t/is (= "https://penpot.example.com/?screen=workspace&team-id=0e5f" + (oidc/build-dest-url "screen=workspace&team-id=0e5f")))) + + (t/testing "the app base path of the public uri is kept" + (binding [cf/config {:public-uri "https://host/penpot"}] + (t/is (= "https://host/penpot/?screen=workspace" + (oidc/build-dest-url "screen=workspace"))))) + + (t/testing "a blank query string lands on the public uri" + (t/is (= "https://penpot.example.com/" (oidc/build-dest-url ""))) + (t/is (= "https://penpot.example.com/" (oidc/build-dest-url nil)))) + + (t/testing "a value without params of its own is not a route" + (doseq [query-string ["https://evil.example/" + "//evil.example/x"]] + (t/is (= "https://penpot.example.com/" + (oidc/build-dest-url query-string)) query-string))) + + (t/testing "the root of the app keeps its params (invitation, template)" + (t/is (= "https://penpot.example.com/?template=xyz" + (oidc/build-dest-url "template=xyz")))) + + (t/testing "a value that still carries the separator is trimmed" + (t/is (= "https://penpot.example.com/?screen=workspace" + (oidc/build-dest-url "?screen=workspace")))) + + (t/testing "control characters never reach the destination" + (let [dest (oidc/build-dest-url "screen=x\r\nSet-Cookie: a=b")] + (t/is (not (.contains dest "\r"))) + (t/is (not (.contains dest "\n"))))) + + (t/testing "repeated params are kept" + (t/is (= "https://penpot.example.com/?a=1&a=2" + (oidc/build-dest-url "a=1&a=2")))))) + +(def ^:private foreign-dest-urls + "Destinations that a naive prefix check would let through: the first one + parses the prefix as userinfo, the second one is a look-alike host." + ["https://evil.example/" + "https://penpot.example.com@evil.example/" + "https://penpot.example.com.evil.example/"]) + +(t/deftest build-organization-sso-auth-redirect-uri-seals-a-server-built-destination + (let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist) + provider {:id "oidc" + :type "oidc" + :client-id "client" + :auth-uri "https://idp.example.com/authorize" + :scopes ["openid"]} + sso {:active true + :issuer "https://idp.example.com" + :organization-id test-organization-id}] + (binding [cf/config {:public-uri "https://penpot.example.com"}] + (doseq [[query-string expected] + [["screen=workspace" "https://penpot.example.com/?screen=workspace"] + ["template=xyz" "https://penpot.example.com/?template=xyz"] + ["https://evil.example/" "https://penpot.example.com/"] + ["" "https://penpot.example.com/"]]] + (t/testing (str "the destination sealed for " (pr-str query-string)) + (let [uri (oidc/build-organization-sso-auth-redirect-uri + cfg sso + :query-string query-string + :organization-id test-organization-id + :profile-id test-profile-id + :provider provider) + claims (tokens/decode cfg (-> (u/uri uri) + :query + (u/query-string->map) + :state))] + ;; The destination is always composed by the server: the route + ;; of the client, never a URL of its own. + (t/is (= expected (:dest-url claims))) + (t/is (= test-profile-id (:profile-id claims))))))))) + +(t/deftest organization-sso-callback-ignores-a-destination-outside-the-public-uri + (doseq [dest-url foreign-dest-urls] + (t/testing (str "the success path ignores " dest-url) + (let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist) + state (make-state-token cfg {:dest-url dest-url + :organization-id test-organization-id}) + request (default-request cfg :state state)] + (binding [cf/config {:public-uri "https://penpot.example.com"}] + (with-redefs [app.nitrate/call (constantly {:active true}) + app.auth.oidc/prepare-organization-sso-provider (constantly {:type "oidc"}) + app.auth.oidc/get-info (constantly {})] + (let [result (#'oidc/callback-handler cfg request)] + (t/is (= "https://penpot.example.com/" (redirect-location result)))))))) + + (t/testing (str "the error path ignores " dest-url " as well") + (let [cfg (dissoc base-cfg :app.email/blacklist :app.email/whitelist) + state (make-state-token cfg {:dest-url dest-url + :organization-id test-organization-id}) + request (default-request cfg :state state)] + (binding [cf/config {:public-uri "https://penpot.example.com"}] + (with-redefs [app.nitrate/call (fn [_cfg method _params] + (case method + :get-organization-sso {:active true} + :get-organization-summary {:name "Organization"})) + app.auth.oidc/prepare-organization-sso-provider (constantly {:type "oidc"}) + app.auth.oidc/get-info (fn [& _] + (ex/raise :type :internal + :code :unable-to-retrieve-user-info))] + (let [result (#'oidc/callback-handler cfg request) + loc (redirect-location result)] + (t/is (not (.contains loc "evil.example"))) + (t/is (.contains loc "https://penpot.example.com/"))))))))) + +(t/deftest trusted-dest-url-requires-the-base-path + (binding [cf/config {:public-uri "https://host/penpot"}] + (t/testing "a destination under the app base path is trusted" + (t/is (= "https://host/penpot/?screen=workspace" + (#'oidc/trusted-dest-url "https://host/penpot/?screen=workspace")))) + + (t/testing "a destination in another path of the same host is not" + (t/is (nil? (#'oidc/trusted-dest-url "https://host/otra/?screen=workspace")))) + + (t/testing "a destination in another host is not" + (t/is (nil? (#'oidc/trusted-dest-url "https://otro.example/penpot/?screen=workspace")))))) + +(t/deftest organization-sso-callback-does-not-grant-the-sso-entry-to-another-session + (let [manager (session/inmemory-manager) + cfg (assoc (dissoc base-cfg :app.email/blacklist :app.email/whitelist) + ::session/manager manager) + ;; The state was prepared by another profile: the session that + ;; completes the flow must not be granted the organization entry. + state (make-state-token cfg {:dest-url "https://penpot.example.com/?screen=workspace" + :organization-id test-organization-id + :profile-id (uuid/random)}) + request (default-request cfg :state state) + events (atom []) + sess {:id (uuid/next) + :profile-id test-profile-id + :props {}}] + (binding [cf/config {:public-uri "https://penpot.example.com"}] + (with-redefs [app.nitrate/call (constantly {:active true}) + app.auth.oidc/prepare-organization-sso-provider (constantly {:type "oidc"}) + app.auth.oidc/get-info (constantly {}) + app.http.session/get-session (constantly sess) + app.loggers.audit/submit (fn [_cfg event] (swap! events conj event))] + (let [result (#'oidc/callback-handler cfg request) + stored (session/read-session manager (:id sess))] + (t/is (= "https://penpot.example.com/?screen=workspace" (redirect-location result))) + (t/is (= ["organization-sso-auth-failed"] (mapv :name @events))) + (t/is (= "session-mismatch" (get-in (first @events) [:props :failure-reason]))) + (t/is (nil? (get-in stored [:props :sso])))))))) + (t/deftest prepare-organization-sso-provider-does-not-skip-ssrf-check (t/testing "organization SSO provider must use SSRF protection" (let [captured-params (atom nil)] @@ -870,7 +1024,7 @@ {:client-id "test-client" :client-secret "test-secret" :issuer "https://wrong-idp.example.com"} - :dest-url "https://localhost:3449/#/dashboard" + :query-string "screen=dashboard" :organization-id #uuid "00000000-0000-0000-0000-000000000001") (catch Throwable t t))] (t/is (ex/error? e)) diff --git a/backend/test/backend_tests/rpc_nitrate_test.clj b/backend/test/backend_tests/rpc_nitrate_test.clj index abbfc679fc..26f0de65ec 100644 --- a/backend/test/backend_tests/rpc_nitrate_test.clj +++ b/backend/test/backend_tests/rpc_nitrate_test.clj @@ -87,6 +87,15 @@ :issuer "https://idp.example.com" :organization-id organization-id} + :get-organization-membership + {:is-member true + :organization-id organization-id} + + :get-organization-summary + {:id organization-id + :owner-id organization-owner-id + :teams []} + nil))) (defn- unauthorized-sso-mock @@ -127,7 +136,7 @@ {::th/type :check-nitrate-sso ::rpc/profile-id (:id external-profile) :team-id (:id team) - :url "https://penpot.example.com/#/workspace"} + :query-string "screen=workspace&team-id=0e5f-1a2b"} {::http/request {}})] (binding [cf/flags (conj cf/flags :admin-console)] (with-redefs [nitrate/call @@ -154,7 +163,7 @@ {::th/type :check-nitrate-sso ::rpc/profile-id (:id team-owner) :team-id (:id team) - :url "https://penpot.example.com/#/workspace"} + :query-string "screen=workspace&team-id=0e5f-1a2b"} {::http/request {}})] (binding [cf/flags (conj cf/flags :admin-console)] (with-redefs [nitrate/call @@ -175,8 +184,9 @@ (t/is (= {:authorized false :redirect-uri redirect-uri} (:result out))) - (t/is (= #{:dest-url :organization-id} (set (keys @redirect-options)))) - (t/is (= "https://penpot.example.com/#/workspace" (str (:dest-url @redirect-options)))) + (t/is (= #{:query-string :organization-id :profile-id} (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 (= {:profile-id (:id team-owner) :organization-id organization-id} @@ -191,10 +201,16 @@ {::th/type :check-nitrate-sso ::rpc/profile-id (:id profile) :organization-id organization-id - :url "https://penpot.example.com/#/workspace"} + :query-string "screen=workspace&team-id=0e5f-1a2b"} {::http/request {}})] (binding [cf/flags (conj cf/flags :admin-console)] (with-redefs [nitrate/sso-session-authorized? (unauthorized-sso-mock organization-id) + nitrate/call + (fn [_cfg method _params] + (case method + :get-organization-membership {:is-member true + :organization-id organization-id} + nil)) oidc/build-organization-sso-auth-redirect-uri (fn [& _] (throw cause)) oidc/submit-organization-sso-auth-failed-event (fn [_cfg _request profile-id received-organization-id received-cause] @@ -218,7 +234,7 @@ {::th/type :check-nitrate-sso ::rpc/profile-id (:id organization-owner) :team-id (:id team) - :url "https://penpot.example.com/#/workspace"} + :query-string "screen=workspace&team-id=0e5f-1a2b"} {::http/request {}})] (binding [cf/flags (conj cf/flags :admin-console)] (with-redefs [nitrate/organization-owner-of-team? @@ -246,7 +262,7 @@ {::th/type :check-nitrate-sso ::rpc/profile-id (:id team-owner) :team-id (:id team) - :url "https://penpot.example.com/#/workspace"} + :query-string "screen=workspace&team-id=0e5f-1a2b"} {::http/request {}})] (binding [cf/flags (conj cf/flags :admin-console)] (with-redefs [nitrate/sso-session-authorized? @@ -259,6 +275,153 @@ (t/is (th/success? out)) (t/is (= {:authorized true :reason :sso-satisfied} (:result out)))))))) +(t/deftest check-nitrate-sso-denies-an-organization-the-profile-does-not-belong-to + (let [profile (th/create-profile* 1 {:is-active true}) + organization-id (uuid/random) + params (with-meta + {::th/type :check-nitrate-sso + ::rpc/profile-id (:id profile) + :organization-id organization-id + :query-string "screen=workspace"} + {::http/request {}})] + (binding [cf/flags (conj cf/flags :admin-console)] + (with-redefs [nitrate/call + (fn [_cfg method _params] + (case method + :get-organization-membership {:is-member false + :organization-id organization-id} + :get-organization-summary {:id organization-id + :owner-id (uuid/random) + :teams []} + :get-organization-sso {:active true + :issuer "https://idp.example.com" + :organization-id organization-id} + nil)) + oidc/build-organization-sso-auth-redirect-uri + (constantly "https://idp.example.com/authorize")] + (let [out (th/command! params)] + (t/is (th/success? out)) + ;; The organization id comes from the client: a profile that does + ;; not belong to the organization must not start a flow for it. + (t/is (= {:authorized true :reason :no-organization-access} (:result out)))))))) + +(t/deftest check-nitrate-sso-denies-an-organization-the-profile-does-not-belong-to-even-with-a-team + (let [profile (th/create-profile* 1 {:is-active true}) + team (th/create-team* 1 {:profile-id (:id profile)}) + organization-id (uuid/random) + params (with-meta + {::th/type :check-nitrate-sso + ::rpc/profile-id (:id profile) + :team-id (:id team) + :organization-id organization-id + :query-string "screen=workspace"} + {::http/request {}})] + (binding [cf/flags (conj cf/flags :admin-console)] + (with-redefs [nitrate/call + (fn [_cfg method _params] + (case method + :get-organization-membership {:is-member false + :organization-id organization-id} + :get-organization-summary {:id organization-id + :owner-id (uuid/random) + :teams []} + :get-organization-sso {:active true + :issuer "https://idp.example.com" + :organization-id organization-id} + nil)) + oidc/build-organization-sso-auth-redirect-uri + (constantly "https://idp.example.com/authorize")] + (let [out (th/command! params)] + (t/is (th/success? out)) + ;; The organization id comes from the client too when the team is + ;; also sent, so the check applies to both shapes. + (t/is (= {:authorized true :reason :no-organization-access} (:result out)))))))) + +(t/deftest check-nitrate-sso-survives-an-organization-that-does-not-exist + (let [profile (th/create-profile* 1 {:is-active true}) + organization-id (uuid/random) + params (with-meta + {::th/type :check-nitrate-sso + ::rpc/profile-id (:id profile) + :organization-id organization-id + :query-string "screen=workspace"} + {::http/request {}})] + (binding [cf/flags (conj cf/flags :admin-console)] + (with-redefs [nitrate/call + (fn [_cfg _method _params] nil) + oidc/build-organization-sso-auth-redirect-uri + (constantly "https://idp.example.com/authorize")] + (let [out (th/command! params)] + (t/is (th/success? out)) + ;; Nitrate knows nothing about the organization: that is a denial, + ;; not a crash. + (t/is (= {:authorized true :reason :no-organization-access} (:result out)))))))) + +(t/deftest check-nitrate-sso-ignores-a-value-that-is-not-a-route + (let [profile (th/create-profile* 1 {:is-active true}) + organization-id (uuid/random) + redirect-uri "https://idp.example.com/authorize"] + (doseq [query-string ["https://evil.example/" ""]] + (let [params (with-meta + {::th/type :check-nitrate-sso + ::rpc/profile-id (:id profile) + :organization-id organization-id + :query-string query-string} + {::http/request {}})] + (binding [cf/flags (conj cf/flags :admin-console)] + (with-redefs [nitrate/call + (fn [_cfg method _params] + (case method + :get-organization-membership {:is-member true + :organization-id organization-id} + :get-organization-summary {:id organization-id + :owner-id (:id profile) + :teams []} + :get-organization-sso {:active true + :issuer "https://idp.example.com" + :organization-id organization-id} + nil)) + oidc/prepare-organization-sso-provider (constantly {:type "oidc"}) + oidc/build-auth-redirect-uri (constantly redirect-uri)] + (let [out (th/command! params)] + (t/is (th/success? out)) + ;; A destination the server cannot render must not break the + ;; flow: the user lands on the public uri instead. + (t/is (= {:authorized false + :redirect-uri redirect-uri} + (:result out)))))))))) + +(t/deftest check-nitrate-sso-allows-the-owner-of-the-organization + (let [profile (th/create-profile* 1 {:is-active true}) + organization-id (uuid/random) + redirect-uri "https://idp.example.com/authorize" + params (with-meta + {::th/type :check-nitrate-sso + ::rpc/profile-id (:id profile) + :organization-id organization-id + :query-string "screen=workspace"} + {::http/request {}})] + (binding [cf/flags (conj cf/flags :admin-console)] + (with-redefs [nitrate/call + (fn [_cfg method _params] + (case method + :get-organization-membership {:is-member false + :organization-id organization-id} + :get-organization-summary {:id organization-id + :owner-id (:id profile) + :teams []} + :get-organization-sso {:active true + :issuer "https://idp.example.com" + :organization-id organization-id} + nil)) + oidc/build-organization-sso-auth-redirect-uri + (constantly redirect-uri)] + (let [out (th/command! params)] + (t/is (th/success? out)) + (t/is (= {:authorized false + :redirect-uri redirect-uri} + (:result out)))))))) + (t/deftest nitrate-sso-required-error-resolves-the-team-from-the-file (t/testing "the workspace path, where the file id arrives as :id, still reports the team" (let [profile (th/create-profile* 1 {:is-active true}) diff --git a/frontend/src/app/main/data/common.cljs b/frontend/src/app/main/data/common.cljs index c2a7de99af..a9fcd5a296 100644 --- a/frontend/src/app/main/data/common.cljs +++ b/frontend/src/app/main/data/common.cljs @@ -237,8 +237,8 @@ (defn- check-team-sso [team-id] - (let [url (rt/get-current-href)] - (->> (rp/cmd! :check-nitrate-sso {:team-id team-id :url url}) + (let [query-string (rt/get-current-query-string)] + (->> (rp/cmd! :check-nitrate-sso {:team-id team-id :query-string query-string}) (rx/mapcat (fn [{:keys [authorized redirect-uri]}] (if authorized (rx/empty) diff --git a/frontend/src/app/main/data/nitrate.cljs b/frontend/src/app/main/data/nitrate.cljs index 1fbbce503c..7d1889e779 100644 --- a/frontend/src/app/main/data/nitrate.cljs +++ b/frontend/src/app/main/data/nitrate.cljs @@ -412,8 +412,11 @@ :add-method "move-existing-team-to-organization" :subscription-status subscription-status}) pending-id (str (uuid/next)) - callback-url (dom/append-query-param (rt/get-current-href) - :pending-action-id pending-id) + ;; The callback travels as a query string; the token is kept in + ;; its own shape because `append-query-param` works on URLs. + callback-query-string (-> (rt/get-current-token) + (dom/append-query-param :pending-action-id pending-id) + rt/token->query-string) ;; The permissions may have changed in Nitrate since the modal ;; was opened: refresh them and explain why the action failed. on-error @@ -428,7 +431,8 @@ (rx/concat (when-not skip-audit? (rx/of audit-event)) - (->> (rp/cmd! :check-nitrate-sso {:organization-id organization-id :url callback-url}) + (->> (rp/cmd! :check-nitrate-sso {:organization-id organization-id + :query-string callback-query-string}) (rx/mapcat (fn [{:keys [authorized redirect-uri]}] (if authorized @@ -446,32 +450,35 @@ (defn check-organization-sso "Asks the backend whether the organization SSO gate can be satisfied for - `dest-url`, returning an observable of the raw `:check-nitrate-sso` - result: `:authorized` with a `:reason` of `:sso-satisfied` or - `:no-team-access`, or `:authorized false` with a `:redirect-uri` (nil - when SSO is required but the provider is unusable). Failures are not - caught, so a network blip stays a network error for the caller to - handle instead of masquerading as an answer." - [{:keys [team-id organization-id dest-url]}] + `query-string` (the route params of the client, `screen=…¶ms`, without + the separator), returning an observable of the raw `:check-nitrate-sso` + result: `:authorized` with a `:reason` of `:sso-satisfied`, + `:no-team-access` or `:no-organization-access`, or `:authorized false` with + a `:redirect-uri` (nil when SSO is required but the provider is unusable). + Failures are not caught, so a network blip stays a network error for the + caller to handle instead of masquerading as an answer." + [{:keys [team-id organization-id query-string]}] (rp/cmd! :check-nitrate-sso (d/without-nils {:team-id team-id :organization-id organization-id - :url dest-url}))) + :query-string query-string}))) (defn retry-organization-sso "Retries the organization SSO login flow after a failed attempt, reusing the same check-nitrate-sso RPC used elsewhere to move the user through the organization's identity provider. Passing `team-id` enables the backend's non-member short-circuit. Falls back to navigating straight - to `dest-url` when no fresh SSO redirect is needed or available." - [{:keys [dest-url] :as params}] - (ptk/reify ::retry-organization-sso - ptk/WatchEvent - (watch [_ _ _] - (->> (check-organization-sso params) - (rx/map (fn [{:keys [redirect-uri]}] - (rt/nav-raw :uri (or redirect-uri dest-url)))) - (rx/catch (fn [_] - (rx/of (rt/nav-raw :uri dest-url)))))))) + to the route of `query-string` when no fresh SSO redirect is needed or + available." + [{:keys [query-string] :as params}] + (let [dest-url (rt/token->url query-string)] + (ptk/reify ::retry-organization-sso + ptk/WatchEvent + (watch [_ _ _] + (->> (check-organization-sso params) + (rx/map (fn [{:keys [redirect-uri]}] + (rt/nav-raw :uri (or redirect-uri dest-url)))) + (rx/catch (fn [_] + (rx/of (rt/nav-raw :uri dest-url))))))))) (defn- fetch-organizations-allowed "Returns an rx observable of an `organizations-allowed` map (organization-id -> boolean). diff --git a/frontend/src/app/main/data/team.cljs b/frontend/src/app/main/data/team.cljs index 80ab5e0fad..6659fa8aae 100644 --- a/frontend/src/app/main/data/team.cljs +++ b/frontend/src/app/main/data/team.cljs @@ -48,7 +48,7 @@ (if (or (not (contains? cf/flags :admin-console)) (= team-id default-team-id)) (rx/of team-id) - (->> (rp/cmd! :check-nitrate-sso {:team-id team-id :url (rt/get-current-href)}) + (->> (rp/cmd! :check-nitrate-sso {:team-id team-id :query-string (rt/get-current-query-string)}) (rx/map (fn [{:keys [authorized]}] (if authorized team-id default-team-id)))))) diff --git a/frontend/src/app/main/errors.cljs b/frontend/src/app/main/errors.cljs index fceac0d344..b4c248823c 100644 --- a/frontend/src/app/main/errors.cljs +++ b/frontend/src/app/main/errors.cljs @@ -806,11 +806,11 @@ [{:keys [organization-id team-id] :as error}] (when-not @sso-renewal-pending? (vreset! sso-renewal-pending? true) - (let [dest-url (rt/get-current-href)] + (let [query-string (rt/get-current-query-string)] (->> (dnt/check-organization-sso {:organization-id organization-id :team-id team-id - :dest-url dest-url}) + :query-string query-string}) ;; Release the guard however the check ends, including an ;; unsubscription or a completion without a result: a stuck guard ;; would silently drop every later rejection. diff --git a/frontend/src/app/main/router.cljs b/frontend/src/app/main/router.cljs index a466f9908b..070c2a764c 100644 --- a/frontend/src/app/main/router.cljs +++ b/frontend/src/app/main/router.cljs @@ -192,8 +192,15 @@ (ts/asap (partial dom/reload-current-window force?))))) (defn nav-raw - [& {:keys [href uri]}] + "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 @@ -207,6 +214,41 @@ [] (.-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 diff --git a/frontend/src/app/main/ui/routes.cljs b/frontend/src/app/main/ui/routes.cljs index fa9926911b..618e4ed99f 100644 --- a/frontend/src/app/main/ui/routes.cljs +++ b/frontend/src/app/main/ui/routes.cljs @@ -164,7 +164,7 @@ active. If so, calls :check-nitrate-sso and either proceeds with navigation or redirects to the SSO provider URL. Successful checks are cached for five minutes per profile and team; redirect results are never cached." - [match send-event-info? url] + [match send-event-info? query-string] (let [route-name (name (get-in match [:data :name])) relevant? (and (contains? cf/flags :admin-console) (or (str/starts-with? route-name "dashboard") @@ -188,7 +188,7 @@ (navigate) :else - (->> (rp/cmd! :check-nitrate-sso {:team-id team-id :url url}) + (->> (rp/cmd! :check-nitrate-sso {:team-id team-id :query-string query-string}) (rx/subs! (fn [{:keys [authorized redirect-uri]}] (if authorized @@ -206,7 +206,7 @@ and deliberately do NOT proceed with normal navigation: emitting `rt/navigated` would clear the exception that was just assigned. Otherwise, delegate to `check-sso-and-navigate`." - [match send-event-info? url] + [match send-event-info? query-string] (let [route-name (name (get-in match [:data :name])) sso-error? (some? (get-in match [:query-params :sso-error])) organization-id (some-> (get-in match [:query-params :organization-id]) uuid/parse*) @@ -223,7 +223,7 @@ :team-id team-id :is-workspace is-workspace? :is-dashboard is-dashboard?})) - (check-sso-and-navigate match send-event-info? url)))) + (check-sso-and-navigate match send-event-info? query-string)))) (declare on-query-navigate) @@ -260,9 +260,7 @@ (defn- on-query-navigate [router token send-event-info?] - (let [token-query (if (str/starts-with? (or token "") "?") - (subs token 1) - (or token "")) + (let [token-query (rt/token->query-string token) query-params (u/query-string->map token-query) ;; Without a `screen` the token targets the app root; its params ;; (e.g. `template`) are forwarded to the dashboard or kept for @@ -270,7 +268,7 @@ root? (nil? (rt/get-query-param query-params :screen)) match (rt/match router token)] (if (some? match) - (handle-sso-error-and-navigate match send-event-info? (rt/get-current-href)) + (handle-sso-error-and-navigate match send-event-info? (rt/get-current-query-string)) ;; We just recheck with an additional profile request; this ;; avoids some race conditions that causes unexpected redirects diff --git a/frontend/src/app/main/ui/static.cljs b/frontend/src/app/main/ui/static.cljs index 588dd0f970..2b58bb8db2 100644 --- a/frontend/src/app/main/ui/static.cljs +++ b/frontend/src/app/main/ui/static.cljs @@ -524,12 +524,14 @@ SSO exchange with the identity provider fails." {::mf/private true} [{:keys [organization-id team-id profile is-workspace is-dashboard organization-name]}] - (let [clean-url + (let [clean-token (mf/with-memo [] - (-> (rt/get-current-href) + (-> (rt/get-current-token) (dom/remove-query-param :sso-error) (dom/remove-query-param :organization-id))) + clean-url (rt/token->url clean-token) + _ (mf/with-effect [] ;; Consume the marker once: scrub it from the URL bar so a ;; browser refresh doesn't keep re-showing this dialog. @@ -545,14 +547,14 @@ on-retry (mf/use-fn - (mf/deps organization-id team-id clean-url) + (mf/deps organization-id team-id clean-token) (fn [] (st/emit! (rt/assign-exception nil)) (if (or team-id organization-id) ;; Retry with team-id and/or organization-id to trigger SSO check (st/emit! (dnt/retry-organization-sso {:team-id team-id :organization-id organization-id - :dest-url clean-url})) + :query-string (rt/token->query-string clean-token)})) ;; Fallback: just navigate to clean URL (st/emit! (rt/nav-raw :uri clean-url)))))] diff --git a/frontend/test/frontend_tests/data/dashboard_test.cljs b/frontend/test/frontend_tests/data/dashboard_test.cljs index 8bd965eca5..8a01c8e5dd 100644 --- a/frontend/test/frontend_tests/data/dashboard_test.cljs +++ b/frontend/test/frontend_tests/data/dashboard_test.cljs @@ -26,7 +26,7 @@ "Runs handle-change-team-organization and returns recorded i18n/tr calls." [notification organization] (let [team-id (uuid/next) - current-url (str "https://penpot.example.com/#/dashboard/recent?team-id=" team-id) + current-query-string (str "screen=dashboard-recent&team-id=" team-id) state {:current-team-id team-id :teams {team-id {:id team-id :name "Team-Apple"}}} event (dcm/handle-change-team-organization @@ -42,11 +42,11 @@ rp/cmd! (mock/stub (fn [cmd params] (if (= [:check-nitrate-sso - {:team-id team-id :url current-url}] + {:team-id team-id :query-string current-query-string}] [cmd params]) (rx/of {:authorized true}) (rx/throw (ex-info "unexpected RPC" {:cmd cmd :params params}))))) - rt/get-current-href (mock/stub (constantly current-url))} + rt/get-current-query-string (mock/stub (constantly current-query-string))} (await (async/observe (ptk/watch event state nil) :on-next (fn [ev] (t/is (contains? #{::ntf/show ::dtm/fetch-teams} @@ -119,7 +119,7 @@ (t/async done (let [team-id (uuid/next) organization {:id (uuid/next) :name "OrgA"} - current-url (str "https://penpot.example.com/#/dashboard/recent?team-id=" team-id) + current-query-string (str "screen=dashboard-recent&team-id=" team-id) redirect-url "https://idp.example.com/authorize" state {:current-team-id team-id} event (dcm/handle-change-team-organization @@ -130,11 +130,11 @@ rp/cmd! (mock/stub (fn [cmd params] (if (= [:check-nitrate-sso - {:team-id team-id :url current-url}] + {:team-id team-id :query-string current-query-string}] [cmd params]) (rx/of {:authorized false :redirect-uri redirect-url}) (rx/throw (ex-info "unexpected RPC" {:cmd cmd :params params}))))) - rt/get-current-href (mock/stub (constantly current-url))} + rt/get-current-query-string (mock/stub (constantly current-query-string))} (fn [done'] (->> (ptk/watch event state nil) (rx/reduce conj []) @@ -151,7 +151,7 @@ (t/async done (let [team-id (uuid/next) organization-id (uuid/next) - current-url (str "https://penpot.example.com/#/workspace?team-id=" team-id) + current-query-string (str "screen=workspace&team-id=" team-id) redirect-url "https://idp.example.com/authorize" state {:current-team-id team-id :teams {team-id {:id team-id @@ -163,11 +163,11 @@ rp/cmd! (mock/stub (fn [cmd params] (if (= [:check-nitrate-sso - {:team-id team-id :url current-url}] + {:team-id team-id :query-string current-query-string}] [cmd params]) (rx/of {:authorized false :redirect-uri redirect-url}) (rx/throw (ex-info "unexpected RPC" {:cmd cmd :params params}))))) - rt/get-current-href (mock/stub (constantly current-url))} + rt/get-current-query-string (mock/stub (constantly current-query-string))} (fn [done'] (->> (ptk/watch event state nil) (rx/reduce conj []) diff --git a/frontend/test/frontend_tests/data/nitrate_test.cljs b/frontend/test/frontend_tests/data/nitrate_test.cljs index 2ea4442157..bb539cccfb 100644 --- a/frontend/test/frontend_tests/data/nitrate_test.cljs +++ b/frontend/test/frontend_tests/data/nitrate_test.cljs @@ -8,6 +8,7 @@ (:require [app.common.time :as ct] [app.common.uri :as u] + [app.config :as cf] [app.main.data.event :as ev] [app.main.data.modal :as modal] [app.main.data.nitrate :as dnt] @@ -367,7 +368,7 @@ state {:teams {(:id team) team}}] (await (mock/with-mocks* - {rt/get-current-href (mock/stub (constantly "http://localhost/#/dashboard")) + {rt/get-current-token (mock/stub (constantly "?screen=dashboard&team-id=1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d")) rp/cmd! (mock/stub (fn [cmd _params] (case cmd @@ -394,3 +395,32 @@ (t/is (= ::dt/fetch-teams (ptk/type (first emitted)))) (t/is (= {:modal-show [:no-permission-modal {:type :no-organizations-create}]} (second emitted))))) + +(def ^:private sso-query-string + "screen=workspace&team-id=1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d") + +(defn- ^:async observe-retry-organization-sso + "Runs `retry-organization-sso` with the given answer from the backend and + resolves to the uri the user is sent to." + [rpc-answer] + (let [emitted (atom []) + event (dnt/retry-organization-sso {:team-id "team-1" + :organization-id "org-1" + :query-string sso-query-string})] + (await + (mock/with-mocks* + {rp/cmd! (mock/stub (fn [_cmd _params] (rx/of rpc-answer)))} + (await (async/observe (ptk/watch event {} nil) + :on-next #(swap! emitted conj %))))) + ;; `nav-raw` exposes its destination through `@event`. + (-> @emitted first deref :uri))) + +(t/deftest ^:async retry-organization-sso-lands-on-the-route-of-the-token + (t/testing "without a redirect uri the user goes back to the route of the token" + (let [target (await (observe-retry-organization-sso {:authorized true}))] + (t/is (= (str cf/public-uri "?" sso-query-string) target)))) + + (t/testing "the redirect uri of the backend wins over the route of the token" + (let [target (await (observe-retry-organization-sso {:authorized false + :redirect-uri "https://idp.example.com/authorize"}))] + (t/is (= "https://idp.example.com/authorize" target))))) diff --git a/frontend/test/frontend_tests/main_errors_test.cljs b/frontend/test/frontend_tests/main_errors_test.cljs index 4f59e70b95..d0181096e4 100644 --- a/frontend/test/frontend_tests/main_errors_test.cljs +++ b/frontend/test/frontend_tests/main_errors_test.cljs @@ -588,6 +588,9 @@ ;; being told they have no access to the file. ;; --------------------------------------------------------------------------- +(def ^:private workspace-query-string + "screen=workspace&team-id=b8f8bb52-8b70-8144-8004-4a5085f0bdc9") + (def ^:private workspace-href "https://penpot.example.com/#/workspace?team-id=b8f8bb52-8b70-8144-8004-4a5085f0bdc9") @@ -609,7 +612,8 @@ (fn [_command _params] (rx/of {:authorized false :redirect-uri "https://idp.example.com/authorize"}))) - rt/get-current-href (constantly workspace-href) + rt/get-current-href (constantly workspace-href) + rt/get-current-query-string (constantly workspace-query-string) st/emit! (mock/stub (fn [& emitted] (swap! events into emitted)))} (errors/on-error (sso-required-error)) (await (async/settle)) @@ -625,14 +629,15 @@ (swap! rpc-calls conj {:command command :params params}) (rx/of {:authorized false :redirect-uri "https://idp.example.com/authorize"}))) - rt/get-current-href (constantly workspace-href) + rt/get-current-href (constantly workspace-href) + rt/get-current-query-string (constantly workspace-query-string) st/emit! mock/noop} (errors/on-error (sso-required-error)) (await (async/settle)) (t/is (= [{:command :check-nitrate-sso :params {:team-id "b8f8bb52-8b70-8144-8004-4a5085f0bdc9" :organization-id organization-id - :url workspace-href}}] + :query-string workspace-query-string}}] @rpc-calls))))))) (t/deftest ^:async already-satisfied-organization-sso-retries-the-location @@ -643,7 +648,8 @@ {rp/cmd! (mock/stub (fn [_command _params] (rx/of {:authorized true :reason :sso-satisfied}))) - rt/get-current-href (constantly workspace-href) + rt/get-current-href (constantly workspace-href) + rt/get-current-query-string (constantly workspace-query-string) st/emit! (mock/stub (fn [& emitted] (swap! events into emitted)))} (errors/on-error (sso-required-error)) (await (async/settle)) @@ -657,7 +663,8 @@ {rp/cmd! (mock/stub (fn [_command _params] (rx/of {:authorized false :redirect-uri nil}))) - rt/get-current-href (constantly workspace-href) + rt/get-current-href (constantly workspace-href) + rt/get-current-query-string (constantly workspace-query-string) rt/assign-exception (fn [error] (reset! assigned* error) (ptk/data-event ::assigned error))} @@ -675,7 +682,8 @@ {rp/cmd! (mock/stub (fn [_command _params] (rx/of {:authorized true :reason :no-team-access}))) - rt/get-current-href (constantly workspace-href) + rt/get-current-href (constantly workspace-href) + rt/get-current-query-string (constantly workspace-query-string) rt/assign-exception (fn [error] (reset! assigned* error) (ptk/data-event ::assigned error))} @@ -690,7 +698,8 @@ (await (mock/with-mocks* {rp/cmd! (mock/stub (fn [_command _params] (rx/of {:authorized true}))) - rt/get-current-href (constantly workspace-href) + rt/get-current-href (constantly workspace-href) + rt/get-current-query-string (constantly workspace-query-string) rt/assign-exception (fn [error] (ptk/data-event ::assigned error)) st/async-emit! (fn [& emitted] (swap! events into emitted))} (errors/on-error (sso-required-error)) @@ -706,7 +715,8 @@ {rp/cmd! (mock/stub (fn [_command _params] (swap! rpc-calls inc) (rx/empty))) - rt/get-current-href (constantly workspace-href) + rt/get-current-href (constantly workspace-href) + rt/get-current-query-string (constantly workspace-query-string) rt/assign-exception (fn [error] (reset! assigned* error) (ptk/data-event ::assigned error))} @@ -724,7 +734,8 @@ {rp/cmd! (mock/stub (fn [_command _params] (swap! rpc-calls inc) (rx/empty))) - rt/get-current-href (constantly workspace-href) + rt/get-current-href (constantly workspace-href) + rt/get-current-query-string (constantly workspace-query-string) st/emit! mock/noop} (errors/on-error (sso-required-error)) (errors/on-error (sso-required-error)) @@ -758,6 +769,8 @@ rt/get-current-href (constantly workspace-href) + rt/get-current-query-string + (constantly workspace-query-string) rt/assign-exception (fn [error] @@ -1015,7 +1028,8 @@ (fn [_command _params] (rx/of {:authorized false :redirect-uri "https://idp.example.com/authorize"}))) - rt/get-current-href (constantly workspace-href) + rt/get-current-href (constantly workspace-href) + rt/get-current-query-string (constantly workspace-query-string) st/emit! (mock/stub (fn [& emitted] (swap! events into emitted)))} (errors/flash-persistence (ex-info "SSO required" (sso-required-error))) (await (async/settle)) diff --git a/frontend/test/frontend_tests/router_test.cljs b/frontend/test/frontend_tests/router_test.cljs index c6f39433dd..10d5713541 100644 --- a/frontend/test/frontend_tests/router_test.cljs +++ b/frontend/test/frontend_tests/router_test.cljs @@ -6,6 +6,7 @@ (ns frontend-tests.router-test (:require + [app.config :as cf] [app.main.router :as rt] [cljs.test :as t :include-macros true])) @@ -43,3 +44,28 @@ (t/is (nil? (rt/match test-routes ""))) (t/is (nil? (rt/match test-routes "?team-id=team-1"))) (t/is (nil? (rt/match test-routes "?screen=nope&team-id=team-1")))) + +(t/deftest token->query-string-drops-the-separator + ;; The history token is `location.search`, so it carries the `?` that + ;; separates it from the path; a query string does not carry it. + (t/is (= "screen=workspace&team-id=t1" + (rt/token->query-string "?screen=workspace&team-id=t1"))) + (t/is (= "" (rt/token->query-string "?"))) + ;; A value already without separator is not touched: no double strip. + (t/is (= "screen=workspace" (rt/token->query-string "screen=workspace"))) + (t/is (= "" (rt/token->query-string ""))) + (t/is (= "" (rt/token->query-string nil)))) + +(t/deftest token->url-joins-the-token-to-the-public-uri + (let [base (str cf/public-uri)] + (t/is (= (str base "?screen=workspace") + (rt/token->url "?screen=workspace"))) + (t/is (= (str base "?screen=workspace") + (rt/token->url "screen=workspace"))) + (t/is (= base (rt/token->url ""))) + (t/is (= base (rt/token->url nil))))) + +(t/deftest get-current-query-string-comes-from-the-current-token + (with-redefs [rt/get-current-token (constantly "?screen=workspace&team-id=t1")] + (t/is (= "screen=workspace&team-id=t1" + (rt/get-current-query-string))))) diff --git a/frontend/test/frontend_tests/ui/routes_test.cljs b/frontend/test/frontend_tests/ui/routes_test.cljs index 68ef15c5d1..08c2203187 100644 --- a/frontend/test/frontend_tests/ui/routes_test.cljs +++ b/frontend/test/frontend_tests/ui/routes_test.cljs @@ -38,15 +38,17 @@ (fn [command params] (t/is (= :check-nitrate-sso command)) (t/is (= team-id (:team-id params))) + (t/is (= "screen=workspace&team-id=1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d" + (:query-string params))) (swap! rpc-calls inc) (rx/of {:authorized true}))) st/emit! (mock/stub (fn [& emitted] (swap! events into emitted)))} (fn [done'] - (#'routes/check-sso-and-navigate match true "https://penpot.example.com/#/workspace") + (#'routes/check-sso-and-navigate match true "screen=workspace&team-id=1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d") (reset! now (ct/plus @now #js {:minutes 4 :seconds 59})) - (#'routes/check-sso-and-navigate match true "https://penpot.example.com/#/workspace") + (#'routes/check-sso-and-navigate match true "screen=workspace&team-id=1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d") (t/is (= 1 @rpc-calls)) (t/is (= 2 (count @events))) (done')) @@ -67,9 +69,9 @@ (rx/of {:authorized true}))) st/emit! mock/noop} (fn [done'] - (#'routes/check-sso-and-navigate match true "https://penpot.example.com/#/workspace") + (#'routes/check-sso-and-navigate match true "screen=workspace&team-id=1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d") (reset! now (ct/plus @now #js {:minutes 5})) - (#'routes/check-sso-and-navigate match true "https://penpot.example.com/#/workspace") + (#'routes/check-sso-and-navigate match true "screen=workspace&team-id=1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d") (t/is (= 2 @rpc-calls)) (done')) done)))) @@ -91,8 +93,8 @@ (fn [& emitted] (swap! events into emitted)))} (fn [done'] - (#'routes/check-sso-and-navigate match true "https://penpot.example.com/#/workspace") - (#'routes/check-sso-and-navigate match true "https://penpot.example.com/#/workspace") + (#'routes/check-sso-and-navigate match true "screen=workspace&team-id=1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d") + (#'routes/check-sso-and-navigate match true "screen=workspace&team-id=1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d") (t/is (= 2 @rpc-calls)) (t/is (= 2 (count @events))) (done'))