Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Fix account-link dismissal for team members (#7960)

ConnorYohc7334fa9edbf
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.java
index 95f2ba5de7..e3819fd16f 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.java
@@ -73,7 +73,9 @@ public class ConnectController {
String callbackOrigin,
boolean insecureTransport,
String mode,
- String status) {}
+ String status,
+ boolean canApprove,
+ boolean canDeny) {}
/** Where the approver's browser goes next, and the correlator the instance is waiting on. */
public record ApproveResponse(String callbackUrl, String nonce) {}
@@ -183,18 +185,26 @@ public class ConnectController {
/** Detail for the approval page. */
@GetMapping("/{requestId}")
@PreAuthorize("isAuthenticated()")
- public ResponseEntity<ViewResponse> view(@PathVariable String requestId) {
+ public ResponseEntity<ViewResponse> view(@PathVariable String requestId, Authentication auth) {
return service.lookup(requestId)
.map(
- v ->
- ResponseEntity.ok(
- new ViewResponse(
- v.requestId(),
- v.name(),
- v.callbackOrigin(),
- v.insecureTransport(),
- v.mode().name(),
- v.status().name())))
+ v -> {
+ boolean canDeny = !leaderTeams.resolve(auth).isError();
+ boolean canApprove =
+ v.mode() == ConnectRequest.Mode.REAUTH
+ ? !leaderTeams.resolveMember(auth).isError()
+ : canDeny;
+ return ResponseEntity.ok(
+ new ViewResponse(
+ v.requestId(),
+ v.name(),
+ v.callbackOrigin(),
+ v.insecureTransport(),
+ v.mode().name(),
+ v.status().name(),
+ canApprove,
+ canDeny));
+ })
.orElseGet(() -> ResponseEntity.notFound().build());
}
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.java
index d58c4c4098..2691d2353b 100644
--- a/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.java
@@ -6,6 +6,8 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.when;
+import java.util.Optional;
+
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -13,16 +15,15 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
+import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.security.core.Authentication;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.saas.accountlink.ConnectController.CreateBody;
import stirling.software.saas.accountlink.ConnectController.CreateResponse;
+import stirling.software.saas.accountlink.LeaderTeamResolver.LeaderTeam;
-/**
- * The authorize URL the instance is told to send its admin to. Everything else on this controller
- * delegates; this is the only decision it makes on its own.
- */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class ConnectControllerTest {
@@ -33,6 +34,7 @@ class ConnectControllerTest {
@Mock private ConnectRequestService service;
@Mock private LeaderTeamResolver leaderTeams;
@Mock private AccountLinkService accountLinkService;
+ @Mock private Authentication auth;
private ApplicationProperties applicationProperties;
private ConnectController controller;
@@ -126,4 +128,59 @@ class ConnectControllerTest {
org.mockito.Mockito.verify(service, org.mockito.Mockito.never())
.createReauth(anyString(), anyString(), anyString(), anyString(), any(), isNull());
}
+
+ @Test
+ void linkLookupAllowsTheTeamLeaderToApproveAndDeny() {
+ pendingRequest(ConnectRequest.Mode.LINK);
+ when(leaderTeams.resolve(auth)).thenReturn(new LeaderTeam(1L, 2L, null));
+
+ var body = controller.view("req-1", auth).getBody();
+
+ assertThat(body).isNotNull();
+ assertThat(body.canApprove()).isTrue();
+ assertThat(body.canDeny()).isTrue();
+ }
+
+ @Test
+ void linkLookupKeepsTheRequestVisibleWithoutOfferingMemberDecisions() {
+ pendingRequest(ConnectRequest.Mode.LINK);
+ when(leaderTeams.resolve(auth))
+ .thenReturn(new LeaderTeam(null, null, HttpStatus.FORBIDDEN));
+
+ var response = controller.view("req-1", auth);
+
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
+ var body = response.getBody();
+ assertThat(body).isNotNull();
+ assertThat(body.callbackOrigin()).isEqualTo("https://pdf.example.com");
+ assertThat(body.canApprove()).isFalse();
+ assertThat(body.canDeny()).isFalse();
+ }
+
+ @Test
+ void reauthLookupAllowsMembersToApproveButNotDeny() {
+ pendingRequest(ConnectRequest.Mode.REAUTH);
+ when(leaderTeams.resolve(auth))
+ .thenReturn(new LeaderTeam(null, null, HttpStatus.FORBIDDEN));
+ when(leaderTeams.resolveMember(auth)).thenReturn(new LeaderTeam(1L, 2L, null));
+
+ var body = controller.view("req-1", auth).getBody();
+
+ assertThat(body).isNotNull();
+ assertThat(body.canApprove()).isTrue();
+ assertThat(body.canDeny()).isFalse();
+ }
+
+ private void pendingRequest(ConnectRequest.Mode mode) {
+ when(service.lookup("req-1"))
+ .thenReturn(
+ Optional.of(
+ new ConnectRequestService.ConnectView(
+ "req-1",
+ "prod-1",
+ "https://pdf.example.com",
+ false,
+ mode,
+ ConnectRequest.Status.PENDING)));
+ }
}
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index e540137a7c..d637932c97 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -3771,7 +3771,9 @@ step = "Step {{current}} of {{total}}"
[connect.confirm]
acknowledge = "I recognise this address and want to connect it to my team"
approve = "Connect server"
+cannotDecide = "Only a team owner can approve or decline this connection. Use a different account or dismiss this prompt to continue using Stirling."
deny = "Decline"
+dismiss = "Dismiss"
lead = "A Stirling server is asking to connect to your team. Check the address below is yours before you approve."
originLabel = "Address"
signedInAs = "Signed in as"
diff --git a/frontend/editor/src/saas/routes/ConnectApprove.test.tsx b/frontend/editor/src/saas/routes/ConnectApprove.test.tsx
new file mode 100644
index 0000000000..ff08815a0a
--- /dev/null
+++ b/frontend/editor/src/saas/routes/ConnectApprove.test.tsx
@@ -0,0 +1,182 @@
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { MemoryRouter, Route, Routes } from "react-router-dom";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { ReactNode } from "react";
+import ConnectApprove from "@app/routes/ConnectApprove";
+import { ResumePendingConnect } from "@app/routes/ResumePendingConnect";
+import { readPendingConnect } from "@app/routes/pendingConnect";
+import type { PendingConnect } from "@app/routes/ConnectApproveView";
+import apiClient from "@app/services/apiClient";
+
+const { signOut, session } = vi.hoisted(() => ({
+ signOut: vi.fn(),
+ session: { user: { id: "member-1" } },
+}));
+
+vi.mock("@app/auth/UseSession", () => ({
+ useAuth: () => ({
+ session,
+ user: { email: "[email protected]" },
+ loading: false,
+ signOut,
+ }),
+}));
+
+vi.mock("@app/services/apiClient", () => ({
+ default: { get: vi.fn(), post: vi.fn() },
+}));
+
+vi.mock("@app/hooks/useDocumentMeta", () => ({ useDocumentMeta: vi.fn() }));
+
+vi.mock("@app/routes/authShared/AuthLayout", () => ({
+ default: ({ children }: { children: ReactNode }) => children,
+}));
+
+vi.mock("@app/ui", async () => ({
+ ...(await import("@app/ui/Banner")),
+ ...(await import("@app/ui/Button")),
+ ...(await import("@app/ui/Checkbox")),
+ ...(await import("@app/ui/Spinner")),
+}));
+
+const pending: PendingConnect & { status: "PENDING" } = {
+ requestId: "req-1",
+ callbackOrigin: "https://pdf.example.com",
+ insecureTransport: false,
+ mode: "LINK",
+ status: "PENDING",
+ canApprove: false,
+ canDeny: false,
+};
+
+function arrive() {
+ return render(
+ <MantineProvider>
+ <MemoryRouter initialEntries={["/link?request=req-1"]}>
+ <ResumePendingConnect />
+ <Routes>
+ <Route path="/link" element={<ConnectApprove />} />
+ <Route path="/" element={<p>App home</p>} />
+ </Routes>
+ </MemoryRouter>
+ </MantineProvider>,
+ );
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ localStorage.clear();
+ vi.mocked(apiClient.get).mockResolvedValue({ data: pending });
+});
+
+describe("connect approval permissions", () => {
+ it("lets members dismiss the remembered prompt without declining the request", async () => {
+ arrive();
+ const dismiss = await screen.findByRole("button", {
+ name: "connect.confirm.dismiss",
+ });
+ expect(
+ screen.queryByRole("button", { name: "connect.confirm.deny" }),
+ ).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: "connect.confirm.approve" }),
+ ).toBeNull();
+ expect(screen.queryByRole("checkbox")).toBeNull();
+ expect(readPendingConnect()).toBe("req-1");
+
+ fireEvent.click(dismiss);
+
+ expect(await screen.findByText("App home")).toBeInTheDocument();
+ expect(readPendingConnect()).toBeNull();
+ expect(apiClient.post).not.toHaveBeenCalled();
+ expect(signOut).not.toHaveBeenCalled();
+ });
+
+ it("preserves the request when a member switches accounts", async () => {
+ arrive();
+ fireEvent.click(
+ await screen.findByRole("button", {
+ name: "connect.confirm.switchAccount",
+ }),
+ );
+
+ expect(signOut).toHaveBeenCalledOnce();
+ expect(readPendingConnect()).toBe("req-1");
+ expect(apiClient.post).not.toHaveBeenCalled();
+ });
+
+ it("keeps decisions hidden until the lookup supplies permissions", async () => {
+ let resolveLookup!: (value: { data: typeof pending }) => void;
+ vi.mocked(apiClient.get).mockReturnValue(
+ new Promise((resolve) => {
+ resolveLookup = resolve;
+ }),
+ );
+ arrive();
+ expect(
+ screen.queryByRole("button", { name: "connect.confirm.approve" }),
+ ).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: "connect.confirm.deny" }),
+ ).toBeNull();
+
+ await act(async () => resolveLookup({ data: pending }));
+
+ expect(
+ await screen.findByRole("button", { name: "connect.confirm.dismiss" }),
+ ).toBeInTheDocument();
+ });
+
+ it("keeps leader decisions and acknowledgement without offering dismissal", async () => {
+ vi.mocked(apiClient.get).mockResolvedValue({
+ data: { ...pending, canApprove: true, canDeny: true },
+ });
+ vi.mocked(apiClient.post).mockResolvedValue({});
+ arrive();
+ const approve = await screen.findByRole("button", {
+ name: "connect.confirm.approve",
+ });
+ expect(approve).toBeDisabled();
+ expect(
+ screen.queryByRole("button", { name: "connect.confirm.dismiss" }),
+ ).toBeNull();
+ fireEvent.click(screen.getByRole("checkbox"));
+ expect(approve).toBeEnabled();
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "connect.confirm.deny" }),
+ );
+
+ await waitFor(() => expect(readPendingConnect()).toBeNull());
+ expect(apiClient.post).toHaveBeenCalledWith(
+ "/api/v1/account-link/connect/req-1/deny",
+ );
+ });
+
+ it("allows a member to reauthenticate without offering decline", async () => {
+ vi.mocked(apiClient.get).mockResolvedValue({
+ data: { ...pending, mode: "REAUTH", canApprove: true },
+ });
+ arrive();
+ expect(
+ await screen.findByRole("button", { name: "connect.confirm.approve" }),
+ ).toBeDisabled();
+ expect(
+ screen.getByRole("button", { name: "connect.confirm.dismiss" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "connect.confirm.deny" }),
+ ).toBeNull();
+ fireEvent.click(screen.getByRole("checkbox"));
+ expect(
+ screen.getByRole("button", { name: "connect.confirm.approve" }),
+ ).toBeEnabled();
+ });
+});
diff --git a/frontend/editor/src/saas/routes/ConnectApprove.tsx b/frontend/editor/src/saas/routes/ConnectApprove.tsx
index 6374738713..2becfa9260 100644
--- a/frontend/editor/src/saas/routes/ConnectApprove.tsx
+++ b/frontend/editor/src/saas/routes/ConnectApprove.tsx
@@ -89,7 +89,8 @@ export default function ConnectApprove() {
const onDecide = useCallback(
async (approve: boolean) => {
- if (!requestId) return;
+ if (!requestId || !(approve ? pending?.canApprove : pending?.canDeny))
+ return;
setBusy(true);
setError(null);
const path = `/api/v1/account-link/connect/${encodeURIComponent(requestId)}`;
@@ -115,7 +116,7 @@ export default function ConnectApprove() {
setBusy(false);
}
},
- [requestId, session, t],
+ [requestId, pending, session, t],
);
/**
@@ -125,6 +126,12 @@ export default function ConnectApprove() {
void signOut();
}, [signOut]);
+ const onDismiss = useCallback(() => {
+ if (!pending || pending.canDeny) return;
+ clearPendingConnect();
+ navigate("/", { replace: true });
+ }, [pending, navigate]);
+
if (loading || !session) return null;
return (
@@ -153,6 +160,7 @@ export default function ConnectApprove() {
error={error}
onDecide={(approve) => void onDecide(approve)}
onSwitchAccount={onSwitchAccount}
+ onDismiss={onDismiss}
/>
</AuthLayout>
);
diff --git a/frontend/editor/src/saas/routes/ConnectApproveView.tsx b/frontend/editor/src/saas/routes/ConnectApproveView.tsx
index c89a27ef49..1a9282b9e5 100644
--- a/frontend/editor/src/saas/routes/ConnectApproveView.tsx
+++ b/frontend/editor/src/saas/routes/ConnectApproveView.tsx
@@ -27,7 +27,6 @@ function ApproveShell({
const { t } = useTranslation();
return (
<div className="saas-connect">
- {/* No onClose: this is a page, so there is nowhere to close back to. */}
<StepModalHeader
brand
title={title}
@@ -61,6 +60,8 @@ export interface PendingConnect {
insecureTransport: boolean;
/** REAUTH cannot rebind: the team is pinned from the device credential at request time. */
mode?: "LINK" | "REAUTH";
+ canApprove: boolean;
+ canDeny: boolean;
}
export interface ConnectApproveViewProps {
@@ -73,6 +74,8 @@ export interface ConnectApproveViewProps {
onDecide: (approve: boolean) => void;
/** Sign out and come back here, keeping the request so it survives the detour. */
onSwitchAccount: () => void;
+ /** Forget the local intent and return to the app without settling the server request. */
+ onDismiss: () => void;
}
/** Presentation for the connect approval page. */
@@ -84,6 +87,7 @@ export function ConnectApproveView({
error,
onDecide,
onSwitchAccount,
+ onDismiss,
}: ConnectApproveViewProps) {
const { t } = useTranslation();
// Gates the primary action: anyone can create a request, so the approver reading
@@ -152,10 +156,15 @@ export function ConnectApproveView({
title={t("connect.confirm.title", "Connect this server?")}
>
<p className="saas-connect__lead">
- {t(
- "connect.confirm.lead",
- "A Stirling server is asking to connect to your team. Check the address below is yours before you approve.",
- )}
+ {pending?.canApprove
+ ? t(
+ "connect.confirm.lead",
+ "A Stirling server is asking to connect to your team. Check the address below is yours before you approve.",
+ )
+ : t(
+ "connect.confirm.cannotDecide",
+ "Only a team owner can approve or decline this connection. Use a different account or dismiss this prompt to continue using Stirling.",
+ )}
</p>
{/* One panel, because the account and the address are two halves of the same
@@ -207,31 +216,41 @@ export function ConnectApproveView({
{error ? <Banner tone="danger">{error}</Banner> : null}
- <Checkbox
- checked={acknowledged}
- disabled={busy}
- onChange={(e) => setAcknowledged(e.currentTarget.checked)}
- label={t(
- "connect.confirm.acknowledge",
- "I recognise this address and want to connect it to my team",
- )}
- />
+ {pending?.canApprove ? (
+ <Checkbox
+ checked={acknowledged}
+ disabled={busy}
+ onChange={(e) => setAcknowledged(e.currentTarget.checked)}
+ label={t(
+ "connect.confirm.acknowledge",
+ "I recognise this address and want to connect it to my team",
+ )}
+ />
+ ) : null}
<div className="saas-connect__actions">
- <Button
- variant="secondary"
- disabled={busy}
- onClick={() => onDecide(false)}
- >
- {t("connect.confirm.deny", "Decline")}
- </Button>
- <Button
- variant="primary"
- disabled={busy || !acknowledged}
- onClick={() => onDecide(true)}
- >
- {t("connect.confirm.approve", "Connect server")}
- </Button>
+ {pending?.canDeny ? (
+ <Button
+ variant="secondary"
+ disabled={busy}
+ onClick={() => onDecide(false)}
+ >
+ {t("connect.confirm.deny", "Decline")}
+ </Button>
+ ) : (
+ <Button variant="secondary" disabled={busy} onClick={onDismiss}>
+ {t("connect.confirm.dismiss", "Dismiss")}
+ </Button>
+ )}
+ {pending?.canApprove ? (
+ <Button
+ variant="primary"
+ disabled={busy || !acknowledged}
+ onClick={() => onDecide(true)}
+ >
+ {t("connect.confirm.approve", "Connect server")}
+ </Button>
+ ) : null}
</div>
</ApproveShell>
);
diff --git a/frontend/editor/src/saas/routes/pendingConnect.ts b/frontend/editor/src/saas/routes/pendingConnect.ts
index c44af277be..ba5bd20346 100644
--- a/frontend/editor/src/saas/routes/pendingConnect.ts
+++ b/frontend/editor/src/saas/routes/pendingConnect.ts
@@ -10,7 +10,7 @@
*
* Reading does not consume it: the request may be open in another tab, or the page
* closed and reopened, or the reader mounted twice. Only a recorded decision, or a
- * request that is settled or gone, retires it.
+ * request that is settled or gone, or an explicit dismissal, retires it.
*/
const KEY = "stirling-pending-connect";