penpot/frontend/test/frontend_tests/data/nitrate_test.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

427 lines
21 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 frontend-tests.data.nitrate-test
(: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]
[app.main.data.nitrate-audit :as nitrate-audit]
[app.main.data.notifications :as ntf]
[app.main.data.team :as dt]
[app.main.repo :as rp]
[app.main.router :as rt]
[app.main.store :as st]
[app.main.ui.auth.verify-token :as verify-token]
[beicon.v2.core :as rx]
[cljs.test :as t :include-macros true]
[frontend-tests.helpers.async :as async]
[frontend-tests.helpers.mock :as mock]
[potok.v2.core :as ptk]))
(t/deftest account-age-days-test
(with-redefs [ct/now (constantly (ct/inst "2026-07-27T12:00:00Z"))]
(t/testing "returns the number of complete days since account creation"
(t/is (= 10
(dnt/account-age-days
{:created-at (ct/inst "2026-07-17T00:00:00Z")}))))
(t/testing "does not return negative ages"
(t/is (= 0
(dnt/account-age-days
{:created-at (ct/inst "2026-07-28T00:00:00Z")}))))
(t/testing "returns nil when the creation date is not an instant"
(t/is (nil? (dnt/account-age-days {})))
(t/is (nil? (dnt/account-age-days {:created-at "invalid"}))))))
(t/deftest add-team-to-organization-audit-event-test
(with-redefs [ct/now (constantly (ct/inst "2026-07-27T12:00:00Z"))]
(t/testing "reports creating the first team in an organization"
(let [event @(nitrate-audit/add-team-to-organization-event
{:organization-id "organization-1"
:organization-team-count-before 0
:team-previous-organization-status "no-organization"
:add-method "create-team-in-organization"
:subscription-status "trialing"})]
(t/is (= "add-team-to-organization" (::ev/name event)))
(t/is (= "dashboard:create-team-in-organization" (::ev/origin event)))
(t/is (= {:is-your-penpot false
:add-method "create-team-in-organization"
:organization-id "organization-1"
:organization-team-count-before 0
:team-previous-organization-status "no-organization"
:is-first-team-in-organization true
:subscription-status "trialing"}
(dissoc event ::ev/name ::ev/origin)))))
(t/testing "reports moving an older team from another organization"
(let [event @(nitrate-audit/add-team-to-organization-event
{:team {:id "team-2"
:created-at (ct/inst "2026-07-17T12:00:00Z")}
:organization-id "organization-2"
:organization-team-count-before 3
:team-previous-organization-status "other-organization"
:add-method "move-existing-team-to-organization"
:subscription-status "active"})]
(t/is (= "dashboard:move-team-to-organization" (::ev/origin event)))
(t/is (= 10 (:team-age-days event)))
(t/is (false? (:is-first-team-in-organization event)))))))
(t/deftest organization-team-count-test
(let [organization-id "organization-1"
teams [{:id "default"
:is-default true
:organization-id organization-id}
{:id "team-1"
:is-default false
:organization-id organization-id}
{:id "team-2"
:is-default false
:organization {:id organization-id}}
{:id "other-team"
:is-default false
:organization-id "organization-2"}]]
(t/is (= 2
(nitrate-audit/organization-team-count
teams
organization-id)))))
(t/deftest delete-organization-member-audit-event-test
(with-redefs [ct/now (constantly (ct/inst "2026-07-27T12:00:00Z"))]
(let [event @(nitrate-audit/delete-organization-member-event
{:organization-id "organization-1"
:user-id "profile-1"
:user-who-delete-member "profile-1"
:deleted-by-role "organization-member"
:member-added-at (ct/inst "2026-07-17T12:00:00Z")
:organization-member-count-before 4
:subscription-status "trial"})]
(t/is (= "delete-organization-member" (::ev/name event)))
(t/is (nil? (::ev/origin event)))
(t/is (= {:organization-id "organization-1"
:user-id "profile-1"
:user-who-delete-member "profile-1"
:deleted-by-role "organization-member"
:days-since-member-added 10
:organization-member-count-before 4
:subscription-status "trial"}
(dissoc event ::ev/name))))
(t/testing "keeps a null age when the membership date is unavailable"
(let [event @(nitrate-audit/delete-organization-member-event
{:organization-id "organization-1"
:user-id "profile-1"
:user-who-delete-member "profile-1"
:deleted-by-role "organization-member"
:organization-member-count-before 4
:subscription-status "active"})]
(t/is (contains? event :days-since-member-added))
(t/is (nil? (:days-since-member-added event)))))))
(t/deftest pending-team-invitation-redirects-to-register
(let [emitted (atom [])
invitation-token "invitation-123"]
(with-redefs [st/emit! (fn
([event]
(swap! emitted conj event))
([event & events]
(swap! emitted into (cons event events))))]
(verify-token/handle-token
{:iss :team-invitation
:state :pending
:redirect-to :auth-register
:invitation-token invitation-token})
(let [event @(first @emitted)]
(t/is (= :auth-register (:id event)))
(t/is (= invitation-token (get-in event [:params :invitation-token])))))))
(t/deftest build-admin-console-url-preserves-public-uri-subpath
(t/testing "builds admin console routes below the configured Penpot subpath"
(let [public-uri (u/uri "https://example.com/penpot/")]
(t/is (= "https://example.com/penpot/admin-console/"
(dnt/build-admin-console-url public-uri "" nil)))
(t/is (= "https://example.com/penpot/admin-console/organization/my-organization/organization-id/people/"
(dnt/build-admin-console-url
public-uri
"organization/my-organization/organization-id/people/"
nil)))
(t/is (= {:action "create-organization"
:origin "dashboard:organization-switcher"}
(-> (dnt/build-admin-console-url
public-uri
""
{:action "create-organization"
:origin "dashboard:organization-switcher"})
u/uri
:query
u/query-string->map))))))
(t/deftest build-nitrate-callback-urls-preserves-hash-query
(t/testing "appends subscription to an existing query inside the hash route"
(let [base-url "https://localhost:3449/#/dashboard/recent?team-id=e6666530-0216-81c8-8007-f17d6087b74f"
callbacks (dnt/build-nitrate-callback-urls base-url base-url)]
(t/is (= "https://localhost:3449/#/dashboard/recent?team-id=e6666530-0216-81c8-8007-f17d6087b74f&subscription=subscribed-to-penpot-nitrate"
(:success-callback callbacks)))
(t/is (= "https://localhost:3449/#/dashboard/recent?team-id=e6666530-0216-81c8-8007-f17d6087b74f&subscription=nitrate-checkout-error"
(:error-callback callbacks)))
(t/is (= "https://localhost:3449/#/dashboard/recent?team-id=e6666530-0216-81c8-8007-f17d6087b74f&subscription=nitrate-checkout-finish-error"
(:finish-error-callback callbacks)))
(t/is (= "https://localhost:3449/#/dashboard/recent?team-id=e6666530-0216-81c8-8007-f17d6087b74f&subscription=nitrate-checkout-cancelled"
(:cancel-callback callbacks))))))
(t/deftest build-nitrate-callback-urls-adds-hash-query-when-missing
(t/testing "adds a hash query when the route has no query string yet"
(let [base-url "https://localhost:3449/#/settings/subscriptions"
callbacks (dnt/build-nitrate-callback-urls base-url base-url)]
(t/is (= "https://localhost:3449/#/settings/subscriptions?subscription=subscribed-to-penpot-nitrate"
(:success-callback callbacks))))))
(t/deftest build-nitrate-callback-urls-adds-regular-query-without-hash
(t/testing "falls back to the regular URL query when there is no hash route"
(let [base-url "https://localhost:3449/admin-console/licenses/billing?foo=bar"
callbacks (dnt/build-nitrate-callback-urls base-url base-url)]
(t/is (= "https://localhost:3449/admin-console/licenses/billing?foo=bar&subscription=subscribed-to-penpot-nitrate"
(:success-callback callbacks))))))
(t/deftest build-nitrate-callback-urls-accepts-uri-object
(t/testing "accepts a URI object as base url (used by the nitrate-form modal)"
(let [base-url (u/uri "https://localhost:3449/#/settings/subscriptions")
callbacks (dnt/build-nitrate-callback-urls base-url base-url)]
(t/is (= "https://localhost:3449/#/settings/subscriptions?subscription=nitrate-checkout-error"
(:error-callback callbacks))))))
(t/deftest build-nitrate-callback-urls-uses-separate-error-base
(t/testing "error callbacks use base-error-url while success/cancel use base-url"
(let [callbacks (dnt/build-nitrate-callback-urls
"https://localhost:3449/#/dashboard/recent"
"https://localhost:3449/#/settings/subscriptions")]
(t/is (= "https://localhost:3449/#/dashboard/recent?subscription=subscribed-to-penpot-nitrate"
(:success-callback callbacks)))
(t/is (= "https://localhost:3449/#/settings/subscriptions?subscription=nitrate-checkout-error"
(:error-callback callbacks)))
(t/is (= "https://localhost:3449/#/settings/subscriptions?subscription=nitrate-checkout-finish-error"
(:finish-error-callback callbacks)))
(t/is (= "https://localhost:3449/#/dashboard/recent?subscription=nitrate-checkout-cancelled"
(:cancel-callback callbacks))))))
(t/deftest go-to-subscription-url-is-a-string
(t/testing "must be a string so licenses/billing?callback=... survives query encoding"
(t/is (string? dnt/go-to-subscription-url))
(t/is (not (u/uri? dnt/go-to-subscription-url)))))
(t/deftest organization-teams-filters-by-organization-id
(let [teams {"t1" {:id "t1" :organization {:id "org-a"}}
"t2" {:id "t2" :organization {:id "org-b"}}
"t3" {:id "t3" :is-default true}
"t4" {:id "t4" :organization {:id "org-a"}}}]
(t/is (= ["t1" "t4"] (map :id (dnt/organization-teams teams "org-a"))))
(t/is (= [] (dnt/organization-teams teams "org-c")))))
(t/deftest organization-leave-info-keeps-default-and-not-owned-teams
(let [org-teams [{:id "default" :is-default true}
{:id "owned-1" :permissions {:is-owner true}}
{:id "member-1" :permissions {:is-owner false}}]
info (dnt/organization-leave-info org-teams)]
(t/is (= "default" (:default-team-id info)))
(t/is (= ["member-1"] (map :id (:not-owned-teams info))))))
(t/deftest leave-organization-fn-builds-delete-and-leave-lists
(let [captured (atom nil)
emitted (atom [])
not-owned-teams [{:id "member-1" :name "extra"}]
leave-fn (dnt/leave-organization-fn {:organization {:id "org-1" :name "Acme"}
:default-team-id "default"
:not-owned-teams not-owned-teams
:on-error :on-error-fn})]
(with-redefs [dnt/leave-organization (fn [params] (reset! captured params) ::leave-event)
st/emit! (fn
([event] (swap! emitted conj event))
([event & events] (swap! emitted into (cons event events))))]
(t/testing "with no teams offered for transfer"
(leave-fn {:teams-to-transfer nil
:teams-to-delete ["solo"]
:member-added-at "2026-07-17T00:00:00Z"
:organization-member-count-before 3})
(t/is (= [::leave-event] @emitted))
(t/is (= {:id "org-1"
:name "Acme"
:default-team-id "default"
:teams-to-delete ["solo"]
:teams-to-leave [{:id "member-1"}]
:member-added-at "2026-07-17T00:00:00Z"
:organization-member-count-before 3
:on-error :on-error-fn}
@captured)))
(t/testing "folds transferred teams into teams-to-leave, ahead of the rest"
(leave-fn {:teams-to-transfer [{:id "pair" :reassign-to "new-owner"}]
:member-added-at "2026-07-17T00:00:00Z"
:organization-member-count-before 3})
(t/is (= [{:id "pair" :reassign-to "new-owner"}
{:id "member-1"}]
(:teams-to-leave @captured)))))))
(t/deftest show-leave-organization-modal-takes-owned-teams-from-the-summary
(let [requests (atom [])
accepted (atom nil)
transferable [{:id "pair" :name "Pair" :members [{:id "m2" :name "Other"}]}]
summary {:teams-to-delete 1
:teams-to-transfer 1
:teams-to-exit 0
:teams-to-detach 0
:team-ids-to-delete ["solo"]
:transferable-teams transferable
:member-added-at "2026-07-17T00:00:00Z"
:organization-member-count-before 3}
event (dnt/show-leave-organization-modal
{:organization {:id "org-1" :name "Acme"}
:profile {:id "me"}
:default-team-id "default"
:leave-fn #(reset! accepted %)
:on-error identity})]
(with-redefs [rp/cmd! (mock/stub
(fn [cmd params]
(swap! requests conj cmd)
(t/is (= {:id "org-1" :default-team-id "default"} params))
(rx/of summary)))
modal/show (mock/stub (fn [params] params))]
(let [modal-params (atom nil)]
(rx/sub! (ptk/watch event nil nil) #(reset! modal-params %))
;; The summary is the only request: no SSO gated member fetch
(t/is (= [::dnt/get-leave-organization-summary] @requests))
(t/is (= :leave-and-reassign-organization (:type @modal-params)))
(t/is (= transferable (:teams-to-transfer @modal-params)))
((:accept @modal-params) {:teams-to-transfer [{:id "pair" :reassign-to "m2"}]})
(t/is (= {:teams-to-transfer [{:id "pair" :reassign-to "m2"}]
:teams-to-delete ["solo"]
:member-added-at "2026-07-17T00:00:00Z"
:organization-member-count-before 3}
@accepted))))))
(t/deftest team-leave-on-error-matrix
(t/testing "known error code shows a translated notification"
(let [emitted (atom [])]
(->> (dnt/team-leave-on-error (ex-info "boom" {:code :owner-cant-leave-team}))
(rx/subs! #(swap! emitted conj %)))
(t/is (= 1 (count @emitted)))
(t/is (= :visible (:status (:notification (ptk/update (first @emitted) {})))))))
(t/testing "unknown error code rethrows the original error"
(let [error (ex-info "boom" {:code :something-unmapped})
rejected (atom [])]
(->> (dnt/team-leave-on-error error)
(rx/subs! (fn [_]) #(swap! rejected conj %)))
(t/is (= [error] @rejected)))))
(t/deftest org-leave-on-error-matrix
(t/testing "known error code refetches teams, hides the modal, and notifies"
(let [emitted (atom [])]
(->> (dnt/org-leave-on-error (ex-info "boom" {:code :not-valid-teams}))
(rx/subs! #(swap! emitted conj %)))
(t/is (= 3 (count @emitted)))
(t/is (some (ptk/type? ::dt/fetch-teams) @emitted))
(t/is (some (ptk/type? ::modal/hide-modal) @emitted))
(let [notification-event (first (filter (ptk/type? ::ntf/show) @emitted))]
(t/is (some? notification-event))
(t/is (= :visible (:status (:notification (ptk/update notification-event {}))))))))
(t/testing "unknown error code rethrows the original error"
(let [error (ex-info "boom" {:code :something-unmapped})
rejected (atom [])]
(->> (dnt/org-leave-on-error error)
(rx/subs! (fn [_]) #(swap! rejected conj %)))
(t/is (= [error] @rejected)))))
(t/deftest build-admin-console-billing-url-encodes-string-callback
(t/testing "billing callback query param round-trips as a real URL string"
(let [public-uri (u/uri "https://localhost:3449/")
callback "https://localhost:3449/#/settings/subscriptions"
href (dnt/build-admin-console-url
public-uri
"licenses/billing"
{:callback callback})
parsed (-> href u/uri :query u/query-string->map :callback)]
(t/is (= callback parsed)))))
(defn- ^:async observe-add-team-rejected-by-permissions
"Runs `add-team-to-organization` for `team` while the backend rejects it
with `:not-allowed`, as when another session changed the permissions
after the modal opened. Resolves to the emitted events."
[team]
(let [emitted (atom [])
event (dnt/add-team-to-organization {:team-id (:id team)
:organization-id "org-2"
:skip-audit? true})
state {:teams {(:id team) team}}]
(await
(mock/with-mocks*
{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
:check-nitrate-sso (rx/of {:authorized true})
::dnt/add-team-to-organization
(rx/throw (ex-info "not allowed" {:type :validation :code :not-allowed})))))
modal/show (mock/stub (fn [& args] {:modal-show args}))}
(await (async/observe (ptk/watch event state nil)
:on-next #(swap! emitted conj %)))))
@emitted))
(t/deftest ^:async add-team-to-organization-shows-no-permission-on-stale-move
(let [emitted (await (observe-add-team-rejected-by-permissions
{:id "team-1" :organization {:id "org-1"}}))]
(t/is (= 2 (count emitted)))
(t/is (= ::dt/fetch-teams (ptk/type (first emitted))))
(t/is (= {:modal-show [:no-permission-modal {:type :no-organizations-change}]}
(second emitted)))))
(t/deftest ^:async add-team-to-organization-shows-no-permission-on-stale-add
(let [emitted (await (observe-add-team-rejected-by-permissions
{:id "team-1"}))]
(t/is (= 2 (count emitted)))
(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)))))