From 9b950f9c41a6331635e1792f048dbbd610cb9714 Mon Sep 17 00:00:00 2001 From: Tao Schiro Date: Thu, 3 Dec 2026 15:59:20 +0100 Subject: [PATCH] feat(launcher): optional login gate for local launches --- app/components/Launcher.vue | 49 +++++- app/stores/back.ts | 6 +- app/stores/infra.ts | 4 +- app/stores/viewer.ts | 16 +- app/stores/viewer_helpers/actions.ts | 4 + app/utils/auth_headers.ts | 11 ++ app/utils/backend_lifecycle.ts | 12 +- app/utils/extension.ts | 27 ++- tests/unit/components/Launcher.nuxt.test.ts | 165 ++++++++++++++++++ ...kend_lifecycle_create_backend.nuxt.test.ts | 71 +++++++- 10 files changed, 336 insertions(+), 29 deletions(-) create mode 100644 app/utils/auth_headers.ts create mode 100644 tests/unit/components/Launcher.nuxt.test.ts diff --git a/app/components/Launcher.vue b/app/components/Launcher.vue index 3145956a4..ceab65310 100644 --- a/app/components/Launcher.vue +++ b/app/components/Launcher.vue @@ -10,25 +10,56 @@ import { useInfraStore } from "@ogw_front/stores/infra"; interface Props { appName: AppName; - // Firebase ID token for the cloud launch; required in cloud mode. + // Firebase ID token for the cloud launch; required in cloud mode. Also sent with the local launches. authToken?: AuthToken; isUserAuthenticated?: boolean; + // True while the authentication state is being restored: the launcher waits instead of showing the auth slot. + isAuthPending?: boolean; + // Outside cloud mode, launches the local microservices only once the user is authenticated. + requireAuth?: boolean; logo?: ImageSource; } const { appName, authToken = undefined, isUserAuthenticated = false, + isAuthPending = false, + requireAuth = false, logo = "", } = defineProps(); const infraStore = useInfraStore(); -// In cloud mode, wait for the user to authenticate and load the app, unless a `?cloud_url=` link -// Points at an already running service: that one is connected straight away, without authentication. -if (infraStore.app_mode !== appMode.CLOUD || getCloudUrlParam() !== undefined) { +const isCloud = infraStore.app_mode === appMode.CLOUD; +// The local launch is automatic once the user is authenticated: no "Load the app" button. +const waitsForLogin = requireAuth && !isCloud; + +if (isCloud) { + // In cloud mode, wait for the user to authenticate and load the app, unless a `?cloud_url=` link + // Points at an already running service: that one is connected straight away, without authentication. + if (getCloudUrlParam() !== undefined) { + void createBackend(authToken); + } +} else if (waitsForLogin) { + let launch_requested = false; + watch( + () => isUserAuthenticated && authToken !== undefined, + (is_ready) => { + if (!is_ready || launch_requested || infraStore.status !== Status.NOT_CREATED) { + return; + } + launch_requested = true; + void createBackend(authToken); + }, + { immediate: true }, + ); +} else { void createBackend(authToken); } +const showLoadButton = computed( + () => !waitsForLogin && isUserAuthenticated && infraStore.status === Status.NOT_CREATED, +); + function cloudCreateBackend(): Promise { return createBackend(authToken); } @@ -37,11 +68,14 @@ function cloudCreateBackend(): Promise { diff --git a/app/stores/back.ts b/app/stores/back.ts index e780d7445..07b9296ac 100644 --- a/app/stores/back.ts +++ b/app/stores/back.ts @@ -6,9 +6,11 @@ import { usePing, useRequestCounter, } from "@ogw_internal/stores/microservice"; +import type { AuthToken } from "@ogw_front/types/server"; import type { RequestHandlers } from "@ogw_shared/utils/types.js"; import { Status } from "@ogw_front/utils/status"; import type { Url } from "@ogw_front/types/files"; +import { authorizationHeaders } from "@ogw_front/utils/auth_headers"; import back_schemas from "@geode/opengeodeweb-back/opengeodeweb_back_typed_schemas.js"; import opengeodeweb_front_schemas from "@geode/opengeodeweb-front/opengeodeweb_front_typed_schemas.js"; import { useAppStore } from "@ogw_front/stores/app"; @@ -67,14 +69,14 @@ export const useBackStore = defineStore( const { start_ping, stop_ping } = usePing(ping); - async function launch(args: LaunchArgs): Promise { + async function launch(args: LaunchArgs, authToken?: AuthToken): Promise { const appStore = useAppStore(); const { COMMAND_BACK, NUXT_ROOT_PATH } = useRuntimeConfig().public; const schema = opengeodeweb_front_schemas.api.local.app.run_back; const params = { COMMAND_BACK, NUXT_ROOT_PATH, args }; const result = await appStore.request( - { schema, params }, + { schema, params, headers: authorizationHeaders(authToken) }, { response_function: (response) => { default_local_port.value = String(response.port); diff --git a/app/stores/infra.ts b/app/stores/infra.ts index 8d104d193..e48f9a74c 100644 --- a/app/stores/infra.ts +++ b/app/stores/infra.ts @@ -1,5 +1,6 @@ import type { FilePath, Url } from "@ogw_front/types/files"; import { type MicroserviceStatus, Status } from "@ogw_front/utils/status"; +import type { AuthToken } from "@ogw_front/types/server"; import type { MicroserviceId } from "@ogw_front/types/identifiers"; const LOCALHOST = "localhost"; @@ -14,7 +15,8 @@ interface Microservice { $id: MicroserviceId; status?: MicroserviceStatus; is_busy?: boolean; - launch?: (params: LaunchArgs) => Promise; + // `authToken` is the user's Firebase ID token, sent to the app server that spawns the process + launch?: (params: LaunchArgs, authToken?: AuthToken) => Promise; connect: () => void | Promise; } diff --git a/app/stores/viewer.ts b/app/stores/viewer.ts index 8607ba486..ae7649870 100644 --- a/app/stores/viewer.ts +++ b/app/stores/viewer.ts @@ -137,10 +137,18 @@ export const useViewerStore = defineStore( } }); } - async function launch(args: Readonly): Promise { - const result = await launchViewerMicroservice(args, (new_port) => { - default_local_port.value = new_port; - }); + // The token type is taken from the helper: one more import would exceed this file's dependency limit + async function launch( + args: Readonly, + authToken?: Parameters[2], + ): Promise { + const result = await launchViewerMicroservice( + args, + (new_port) => { + default_local_port.value = new_port; + }, + authToken, + ); return result; } async function connect(): Promise { diff --git a/app/stores/viewer_helpers/actions.ts b/app/stores/viewer_helpers/actions.ts index 0af81cdc3..292a5483c 100644 --- a/app/stores/viewer_helpers/actions.ts +++ b/app/stores/viewer_helpers/actions.ts @@ -1,7 +1,9 @@ +import type { AuthToken } from "@ogw_front/types/server"; import type { Coordinate } from "@ogw_front/types/geometry"; import type { LaunchArgs } from "@ogw_front/stores/infra"; import type { Vector3 } from "@kitware/vtk.js/types"; import type { ViewerRequest } from "./request.js"; +import { authorizationHeaders } from "@ogw_front/utils/auth_headers"; import { consola } from "consola"; import opengeodeweb_front_schemas from "@geode/opengeodeweb-front/opengeodeweb_front_typed_schemas.js"; import opengeodeweb_viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; @@ -28,6 +30,7 @@ async function pickWorldPosition( async function launchViewerMicroservice( args: Readonly, onPort: (port: string) => void, + authToken?: AuthToken, ): Promise { const appStore = useAppStore(); const { COMMAND_VIEWER, NUXT_ROOT_PATH } = useRuntimeConfig().public; @@ -41,6 +44,7 @@ async function launchViewerMicroservice( { schema, params, + headers: authorizationHeaders(authToken), }, { response_function: (response) => { diff --git a/app/utils/auth_headers.ts b/app/utils/auth_headers.ts new file mode 100644 index 000000000..62a1c4fe3 --- /dev/null +++ b/app/utils/auth_headers.ts @@ -0,0 +1,11 @@ +import type { AuthToken } from "@ogw_front/types/server"; + +// The `Authorization` header carrying the user's Firebase ID token, or no header without a token. +function authorizationHeaders(authToken?: AuthToken): Record { + if (authToken === undefined) { + return {}; + } + return { Authorization: `Bearer ${authToken}` }; +} + +export { authorizationHeaders }; diff --git a/app/utils/backend_lifecycle.ts b/app/utils/backend_lifecycle.ts index 91cd82389..b652ff995 100644 --- a/app/utils/backend_lifecycle.ts +++ b/app/utils/backend_lifecycle.ts @@ -30,7 +30,8 @@ declare global { var electronAPI: ElectronApi["electronAPI"]; } -async function launchLocalServices(): Promise { +// `authToken` is the user's Firebase ID token, sent with every request that spawns a process +async function launchLocalServices(authToken?: AuthToken): Promise { const infraStore = useInfraStore(); const appStore = useAppStore(); await appStore.createProjectFolder(); @@ -43,10 +44,13 @@ async function launchLocalServices(): Promise { const launch_promises: Promise[] = infraStore.microservices .filter((store: Microservice) => store.launch) .map(async (store: Microservice) => { - const result = await store.launch?.({ projectFolderPath: appStore.projectFolderPath }); + const result = await store.launch?.( + { projectFolderPath: appStore.projectFolderPath }, + authToken, + ); return result; }); - launch_promises.push(registerRunningExtensions()); + launch_promises.push(registerRunningExtensions(authToken)); await Promise.all(launch_promises); } @@ -147,7 +151,7 @@ async function createBackend(authToken?: AuthToken): Promise { throw error; } } else { - await launchLocalServices(); + await launchLocalServices(authToken); } infraStore.set_status(Status.CREATED); await infraStore.create_connection(); diff --git a/app/utils/extension.ts b/app/utils/extension.ts index d04ac3a86..c4d0f229e 100644 --- a/app/utils/extension.ts +++ b/app/utils/extension.ts @@ -3,11 +3,12 @@ // Third party imports // Local imports -import type { ExtensionName, PackageVersion, Port } from "@ogw_front/types/server"; +import type { AuthToken, ExtensionName, PackageVersion, Port } from "@ogw_front/types/server"; import type { FileName, Url } from "@ogw_front/types/files"; import type { RegisterableStore, useAppStore } from "@ogw_front/stores/app"; import type { ExtensionId } from "@ogw_front/types/identifiers"; import type { Microservice } from "@ogw_front/stores/infra"; +import { authorizationHeaders } from "@ogw_front/utils/auth_headers"; import { consola } from "consola"; import { isCloudMode } from "@ogw_front/utils/stores"; import opengeodeweb_front_schemas from "@geode/opengeodeweb-front/opengeodeweb_front_typed_schemas.js"; @@ -40,7 +41,10 @@ async function uploadExtension(file: File): Promise { await appStore.upload(file); } -async function runExtensions(): Promise<{ extensionsArray: ExtensionDescriptor[] }> { +// `authToken` is the user's Firebase ID token: running the extensions spawns their processes +async function runExtensions( + authToken?: AuthToken, +): Promise<{ extensionsArray: ExtensionDescriptor[] }> { const { useAppStore } = await import("@ogw_front/stores/app"); const appStore = useAppStore(); const { projectFolderPath } = appStore; @@ -55,6 +59,7 @@ async function runExtensions(): Promise<{ extensionsArray: ExtensionDescriptor[] const result = await appStore.request({ schema, params, + headers: authorizationHeaders(authToken), }); return result; } @@ -83,12 +88,12 @@ function isMicroservice(store: RegisterableStore): store is RegisterableStore & return typeof store.connect === "function"; } -async function registerRunningExtensions(): Promise { +async function registerRunningExtensions(authToken?: AuthToken): Promise { const { useAppStore } = await import("@ogw_front/stores/app"); const { useInfraStore } = await import("@ogw_front/stores/infra"); const appStore = useAppStore(); const infraStore = useInfraStore(); - const { extensionsArray } = await runExtensions(); + const { extensionsArray } = await runExtensions(authToken); return Promise.all( extensionsArray.map(async (extension: ExtensionDescriptor) => { const { id, name, version, frontendContent, port, serverPort } = extension; @@ -123,14 +128,20 @@ async function registerRunningExtensions(): Promise { ); } -async function importExtensionFile(file: File): Promise { +async function importExtensionFile( + file: File, + authToken?: AuthToken, +): Promise { await uploadExtension(file); - return registerRunningExtensions(); + return registerRunningExtensions(authToken); } -async function importExtensionURL(url: DownloadExtensionParams): Promise { +async function importExtensionURL( + url: DownloadExtensionParams, + authToken?: AuthToken, +): Promise { await downloadExtension(url); - return registerRunningExtensions(); + return registerRunningExtensions(authToken); } async function unloadExtension(extensionId: ExtensionId): Promise { diff --git a/tests/unit/components/Launcher.nuxt.test.ts b/tests/unit/components/Launcher.nuxt.test.ts new file mode 100644 index 000000000..8bb806b5f --- /dev/null +++ b/tests/unit/components/Launcher.nuxt.test.ts @@ -0,0 +1,165 @@ +// Third party imports +import { type VueWrapper, mount } from "@vue/test-utils"; +import { beforeEach, describe, expect, test, vi } from "vitest"; + +// Local imports +import { setupActivePinia, vuetify } from "@ogw_tests/utils"; +import Launcher from "@ogw_front/components/Launcher.vue"; +import Loading from "@ogw_front/components/Loading.vue"; +import { appMode } from "@ogw_shared/app_mode"; +import { createBackend } from "@ogw_front/utils/backend_lifecycle"; +import { getCloudUrlParam } from "@ogw_front/utils/cloud"; +import { useInfraStore } from "@ogw_front/stores/infra"; + +// The launcher only decides when to create the backend: the creation itself is mocked +vi.mock(import("@ogw_front/utils/backend_lifecycle"), () => ({ + createBackend: vi.fn().mockResolvedValue(undefined), +})); + +vi.mock(import("@ogw_front/utils/cloud"), () => ({ + getCloudUrlParam: vi.fn().mockReturnValue(undefined), +})); + +const TOKEN = "token"; +const REFRESHED_TOKEN = "refreshed-token"; +const CLOUD_RUN_HOST = "vease-abc123.europe-west1.run.app"; + +type LauncherProps = InstanceType["$props"]; + +function mountLauncher( + props: Partial = {}, + pinia = setupActivePinia(), +): VueWrapper> { + return mount(Launcher, { + props: { appName: "App", ...props }, + slots: { auth: '
' }, + global: { plugins: [vuetify, pinia], stubs: { Loading: true } }, + }); +} + +function setMode(mode: string): ReturnType { + const pinia = setupActivePinia(); + useInfraStore().app_mode = mode; + return pinia; +} + +describe("launcher", () => { + beforeEach(() => { + vi.mocked(createBackend).mockClear(); + vi.mocked(getCloudUrlParam).mockReturnValue(undefined); + }); + + describe("without requireAuth", () => { + test("launches the local microservices on mount", () => { + const pinia = setMode(appMode.BROWSER); + mountLauncher({ authToken: TOKEN }, pinia); + + expect(vi.mocked(createBackend).mock.calls).toStrictEqual([[TOKEN]]); + }); + + test("launches without a user", () => { + const pinia = setMode(appMode.DESKTOP); + mountLauncher({}, pinia); + + expect(vi.mocked(createBackend).mock.calls).toStrictEqual([[undefined]]); + }); + }); + + describe("with requireAuth outside cloud mode", () => { + test("waits for a user before launching", () => { + const pinia = setMode(appMode.BROWSER); + mountLauncher({ requireAuth: true }, pinia); + + expect(createBackend).not.toHaveBeenCalled(); + }); + + test("waits for the token of an authenticated user", () => { + const pinia = setMode(appMode.BROWSER); + mountLauncher({ requireAuth: true, isUserAuthenticated: true }, pinia); + + expect(createBackend).not.toHaveBeenCalled(); + }); + + test("launches once a user and a token are there", async () => { + const pinia = setMode(appMode.DESKTOP); + const wrapper = mountLauncher({ requireAuth: true }, pinia); + + await wrapper.setProps({ isUserAuthenticated: true, authToken: TOKEN }); + + expect(vi.mocked(createBackend).mock.calls).toStrictEqual([[TOKEN]]); + }); + + test("launches right away when the user is already there", () => { + const pinia = setMode(appMode.BROWSER); + mountLauncher({ requireAuth: true, isUserAuthenticated: true, authToken: TOKEN }, pinia); + + expect(vi.mocked(createBackend).mock.calls).toStrictEqual([[TOKEN]]); + }); + + test("launches only once", async () => { + const pinia = setMode(appMode.BROWSER); + const wrapper = mountLauncher({ requireAuth: true }, pinia); + + await wrapper.setProps({ isUserAuthenticated: true, authToken: TOKEN }); + await wrapper.setProps({ authToken: REFRESHED_TOKEN }); + await wrapper.setProps({ isUserAuthenticated: false, authToken: undefined }); + await wrapper.setProps({ isUserAuthenticated: true, authToken: TOKEN }); + + expect(vi.mocked(createBackend).mock.calls).toStrictEqual([[TOKEN]]); + }); + + test("shows no load button", () => { + const pinia = setMode(appMode.BROWSER); + const wrapper = mountLauncher( + { requireAuth: true, isUserAuthenticated: true, authToken: TOKEN }, + pinia, + ); + + expect(wrapper.find('[data-testid="loadAppButton"]').exists()).toBe(false); + }); + }); + + describe("in cloud mode", () => { + test("waits for the load button, even with requireAuth", async () => { + const pinia = setMode(appMode.CLOUD); + const wrapper = mountLauncher( + { requireAuth: true, isUserAuthenticated: true, authToken: TOKEN }, + pinia, + ); + + expect(createBackend).not.toHaveBeenCalled(); + + await wrapper.find('[data-testid="loadAppButton"]').trigger("click"); + + expect(vi.mocked(createBackend).mock.calls).toStrictEqual([[TOKEN]]); + }); + + test("connects a `?cloud_url=` service on mount", () => { + vi.mocked(getCloudUrlParam).mockReturnValue(CLOUD_RUN_HOST); + const pinia = setMode(appMode.CLOUD); + mountLauncher({ requireAuth: true }, pinia); + + expect(vi.mocked(createBackend).mock.calls).toStrictEqual([[undefined]]); + }); + }); + + describe("pending authentication", () => { + test("shows the loading screen instead of the auth slot", () => { + const pinia = setMode(appMode.BROWSER); + const wrapper = mountLauncher({ requireAuth: true, isAuthPending: true }, pinia); + + expect(wrapper.find('[data-testid="authSlot"]').exists()).toBe(false); + expect(wrapper.findComponent(Loading).exists()).toBe(true); + }); + + test("shows the auth slot once settled", async () => { + const pinia = setMode(appMode.BROWSER); + const wrapper = mountLauncher({ requireAuth: true, isAuthPending: true }, pinia); + + await wrapper.setProps({ isAuthPending: false }); + + expect(wrapper.find('[data-testid="authSlot"]').exists()).toBe(true); + expect(wrapper.findComponent(Loading).exists()).toBe(false); + }); + }); +}); diff --git a/tests/unit/utils/backend_lifecycle_create_backend.nuxt.test.ts b/tests/unit/utils/backend_lifecycle_create_backend.nuxt.test.ts index 0e8b4c53c..528d47aa9 100644 --- a/tests/unit/utils/backend_lifecycle_create_backend.nuxt.test.ts +++ b/tests/unit/utils/backend_lifecycle_create_backend.nuxt.test.ts @@ -52,7 +52,7 @@ vi.stubGlobal( async function respondWithSuccess( options: FetchOptions | undefined, request: FetchRequest, - data: { url: string }, + data: object, ): Promise { const onResponse = options?.onResponse; if (typeof onResponse !== "function") { @@ -66,6 +66,50 @@ async function respondWithSuccess( await onResponse({ request, options: resolvedOptions, response }); } +const TOKEN = "token"; +const SPAWNING_ROUTES = [ + "api/local/app/run_back", + "api/local/app/run_viewer", + "api/local/extensions/run", +]; +// What the app server answers to each request of a local launch +const LOCAL_RESPONSES: Record = { + "api/local/app/project_folder_path": { projectFolderPath: "/project" }, + "api/microservice/app/set_app_base_url": {}, + "api/local/app/run_back": { port: 5001 }, + "api/local/app/run_viewer": { port: 1234 }, + "api/local/extensions/run": { extensionsArray: [] }, +}; + +function routeOf(request: FetchRequest): string { + return typeof request === "string" ? request : request.url; +} + +// Answers every request of a local launch, and registers the back and viewer launches with a +// No-op connect so the test stops at the requests the launch sends. +function setupLocalLaunch(): void { + const infraStore = useInfraStore(); + const backStore = useBackStore(); + const viewerStore = useViewerStore(); + infraStore.app_mode = appMode.BROWSER; + infraStore.register_microservice({ $id: "back", launch: backStore.launch, connect: vi.fn() }); + infraStore.register_microservice({ + $id: "viewer", + launch: viewerStore.launch, + connect: vi.fn(), + }); + vi.mocked($fetch).mockImplementation(async (request, options) => { + const data = LOCAL_RESPONSES[routeOf(request)] ?? {}; + await respondWithSuccess(options, request, data); + return data; + }); +} + +function headersSentTo(route: string): unknown { + const call = vi.mocked($fetch).mock.calls.find(([request]) => routeOf(request) === route); + return call?.[1]?.headers; +} + describe("backend lifecycle", () => { beforeEach(() => { setupActivePinia(); @@ -104,4 +148,29 @@ describe("backend lifecycle", () => { expect(infraStore.status).toBe(Status.NOT_CREATED); }); }); + + describe("launch the local microservices", () => { + beforeEach(() => { + vi.mocked($fetch).mockReset(); + setupLocalLaunch(); + }); + + test("sends the token to every request that spawns a process", async () => { + await createBackend(TOKEN); + + expect(useInfraStore().status).toBe(Status.CREATED); + expect(SPAWNING_ROUTES.map((route) => headersSentTo(route))).toStrictEqual( + SPAWNING_ROUTES.map(() => ({ Authorization: `Bearer ${TOKEN}` })), + ); + }); + + test("sends no token without an authenticated user", async () => { + await createBackend(); + + expect(useInfraStore().status).toBe(Status.CREATED); + expect(SPAWNING_ROUTES.map((route) => headersSentTo(route))).toStrictEqual( + SPAWNING_ROUTES.map(() => ({})), + ); + }); + }); });