From 1fdaefe14cc4134b64b3ba1639961f23a95dd03e Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Mon, 23 Nov 2026 09:30:02 +0100 Subject: [PATCH 01/20] fix: close p1-p7 security gaps across org membership, auth linking, and collaboration rooms Adds server-side membership/rank checks to the admin-on-member user routes, mails password resets only to an account's own resolved address, fixes an org-membership exclusivity check that ENTERPRISE mode's membership collapsing could hide, sanitizes npm registry credentials out of shared organization settings, enforces current-org folder ownership on folder permission mutations, blocks resetting a super-admin's password except by another super-admin or self, and rewrites the Hocuspocus collaboration server to authorize each room against the connecting user's real READ access rather than trusting the client-supplied application id. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- client/packages/lowcoder/hocuspocus-server.js | 128 ++++++++-- .../lowcoder/hocuspocus-server.test.mjs | 181 +++++++++++++ .../src/comps/comps/moduleComp/moduleComp.tsx | 12 +- .../src/comps/hooks/chatControllerComp.tsx | 14 +- .../packages/lowcoder/src/i18n/locales/en.ts | 2 +- .../setting/advanced/AdvancedSetting.tsx | 16 +- ...alEditorContext.hostApplicationId.test.tsx | 159 ++++++++++++ .../src/util/context/ExternalEditorContext.ts | 11 + .../organization/model/Organization.java | 10 +- .../service/OrgMemberService.java | 9 + .../service/OrgMemberServiceImpl.java | 5 + .../domain/user/service/UserServiceImpl.java | 48 +++- ...ganizationCommonSettingsSanitizedTest.java | 55 ++++ .../service/UserServiceImplPasswordTest.java | 129 ++++++++++ .../service/AuthenticationApiServiceImpl.java | 58 ++++- .../api/home/FolderApiServiceImpl.java | 41 ++- .../usermanagement/UserApiServiceImpl.java | 32 +++ .../api/usermanagement/UserController.java | 75 +++++- ...enticationApiServiceImplEmailLinkTest.java | 239 ++++++++++++++++++ ...enticationApiServiceImplMutationsTest.java | 10 +- .../endpoint/UserEndpointsContractTest.java | 183 +++++++++++++- .../api/home/FolderApiServiceImplTest.java | 93 +++++++ .../InvitationAndUserApiServiceTest.java | 10 +- .../UserApiServiceImplResetPasswordTest.java | 209 +++++++++++++++ ...ceImplEnterpriseEnrolmentPinMongoTest.java | 26 ++ ...nagement.view.UserProfileView.Reduced.json | 1 + 26 files changed, 1699 insertions(+), 57 deletions(-) create mode 100644 client/packages/lowcoder/hocuspocus-server.test.mjs create mode 100644 client/packages/lowcoder/src/util/context/ExternalEditorContext.hostApplicationId.test.tsx create mode 100644 server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/organization/model/OrganizationCommonSettingsSanitizedTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImplEmailLinkTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetPasswordTest.java create mode 100644 server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.Reduced.json diff --git a/client/packages/lowcoder/hocuspocus-server.js b/client/packages/lowcoder/hocuspocus-server.js index 78f745d4a4..0acd2a503b 100644 --- a/client/packages/lowcoder/hocuspocus-server.js +++ b/client/packages/lowcoder/hocuspocus-server.js @@ -8,24 +8,122 @@ * Hocuspocus awareness on the client side. * * Env vars: - * PORT - HTTP/WebSocket port (default 3006) - * HOST - Bind address (default 0.0.0.0) - * HOCUSPOCUS_SECRET - Optional shared secret for token auth + * PORT - HTTP/WebSocket port (default 3006) + * HOST - Bind address (default 0.0.0.0) + * HOCUSPOCUS_SECRET - Optional shared secret for token auth, checked before room authorization + * API_SERVICE_URL - Base URL of the api-service, used to authorize signal_* rooms (default http://localhost:8080) + * LOWCODER_API_SERVICE_URL - Same as API_SERVICE_URL, read if API_SERVICE_URL is unset + * + * A room named signal_[:] is authorized by re-checking the connecting + * browser's own cookie against GET /api/applications//view -- the same READ rule the app + * editor/viewer itself uses (a public app is open to anonymous visitors, a private app only to a reader). Rooms + * named typeform_*, googleform_*, website_* (the proxy-service bridges) keep today's behaviour: only the shared + * secret, if one is configured, gates them (left open deliberately for now). Any other room name is refused. * * Usage: node hocuspocus-server.js */ import { Server } from "@hocuspocus/server"; +import { pathToFileURL } from "node:url"; const PORT = parseInt(process.env.PORT || "3006", 10); const HOST = process.env.HOST || "0.0.0.0"; const SECRET = process.env.HOCUSPOCUS_SECRET || ""; +const API_SERVICE_URL = process.env.API_SERVICE_URL || process.env.LOWCODER_API_SERVICE_URL || "http://localhost:8080"; +const FETCH_TIMEOUT_MS = 5000; + +/** A signal_ room's own id, matching SlugUtils.validate exactly -- no numeric length cap. */ +const APP_ID_PATTERN = /^[A-Za-z0-9_-]*$/; +const BRIDGE_PREFIXES = ["typeform_", "googleform_", "website_"]; +const SIGNAL_PREFIX = "signal_"; function writeJson(response, statusCode, payload) { response.writeHead(statusCode, { "Content-Type": "application/json" }); response.end(JSON.stringify(payload)); } +/** + * The `Cookie` header of the upgrade request, whatever shape `requestHeaders` has. Different `@hocuspocus/server` + * versions expose it differently: a plain Node `IncomingHttpHeaders` object (property access), confirmed against + * the locally installed 3.4.4; or, NOT VERIFIED locally, a Fetch-API-style `Headers` instance (a `.get` method) in + * the deployed 4.3.0. Support both rather than assume one. + */ +export function cookieOf(requestHeaders) { + if (!requestHeaders) { + return undefined; + } + if (typeof requestHeaders.get === "function") { + return requestHeaders.get("cookie") ?? requestHeaders.get("Cookie") ?? undefined; + } + return requestHeaders.cookie ?? requestHeaders["Cookie"] ?? undefined; +} + +/** + * Authorizes a Hocuspocus room by name. `fetchImpl` and `apiServiceUrl` are injectable for tests; + * production calls pass the real `fetch` and `API_SERVICE_URL`. + */ +export async function authorizeDocument({ documentName, cookie, fetchImpl = fetch, apiServiceUrl = API_SERVICE_URL }) { + if (typeof documentName !== "string") { + throw new Error("Unauthorized"); + } + + if (BRIDGE_PREFIXES.some((prefix) => documentName.startsWith(prefix))) { + return; + } + + if (!documentName.startsWith(SIGNAL_PREFIX)) { + throw new Error("Unauthorized"); + } + + const afterPrefix = documentName.slice(SIGNAL_PREFIX.length); + const colonIndex = afterPrefix.indexOf(":"); + const appId = colonIndex === -1 ? afterPrefix : afterPrefix.slice(0, colonIndex); + + if (!APP_ID_PATTERN.test(appId)) { + throw new Error("Unauthorized"); + } + + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); + try { + const response = await fetchImpl(`${apiServiceUrl}/api/applications/${appId}/view`, { + method: "GET", + headers: cookie ? { Cookie: cookie } : {}, + signal: controller.signal, + }); + if (!response.ok) { + throw new Error("Unauthorized"); + } + const body = await response.json(); + if (body?.success !== true) { + throw new Error("Unauthorized"); + } + } catch { + throw new Error("Unauthorized"); + } finally { + clearTimeout(timeout); + } +} + +/** + * The secret check (when `SECRET` is set) runs first, before any room authorization -- a wrong token must refuse + * without ever calling `authorizeDocument` (and so without any fetch). Exported, not only the inline Server hook, + * so the gate order itself is directly testable. + */ +export async function onAuthenticate({ token, documentName, requestHeaders }, secret = SECRET, authorize = authorizeDocument) { + if (secret && token !== secret) { + console.warn(`[hocuspocus] rejected connection for ${documentName}: invalid token`); + throw new Error("Unauthorized"); + } + + try { + await authorize({ documentName, cookie: cookieOf(requestHeaders) }); + } catch (error) { + console.warn(`[hocuspocus] rejected connection for ${documentName}: ${error?.message || "Unauthorized"}`); + throw error; + } +} + const server = new Server({ name: "lowcoder-hocuspocus", quiet: true, @@ -46,6 +144,7 @@ const server = new Server({ host: HOST, port: PORT, auth: SECRET ? "enabled" : "disabled", + rooms: "app-read-check", }); throw null; } @@ -60,16 +159,7 @@ const server = new Server({ } }, - async onAuthenticate({ token, documentName }) { - if (!SECRET) { - return; - } - - if (token !== SECRET) { - console.warn(`[hocuspocus] rejected connection for ${documentName}: invalid token`); - throw new Error("Unauthorized"); - } - }, + onAuthenticate, async onConnect({ documentName, socketId }) { console.log(`[hocuspocus] connect socket=${socketId} document=${documentName}`); @@ -80,9 +170,11 @@ const server = new Server({ }, }); -try { - await server.listen(); -} catch (error) { - console.error("[hocuspocus] failed to start", error); - process.exit(1); +if (import.meta.url === pathToFileURL(process.argv[1]).href) { + try { + await server.listen(); + } catch (error) { + console.error("[hocuspocus] failed to start", error); + process.exit(1); + } } diff --git a/client/packages/lowcoder/hocuspocus-server.test.mjs b/client/packages/lowcoder/hocuspocus-server.test.mjs new file mode 100644 index 0000000000..0ede7e16e0 --- /dev/null +++ b/client/packages/lowcoder/hocuspocus-server.test.mjs @@ -0,0 +1,181 @@ +// Unit tests of hocuspocus-server.js's room authorization. Run with `node --test`. +// Not copied into any image -- this file is test-only. + +import test from "node:test"; +import assert from "node:assert/strict"; +import { authorizeDocument, onAuthenticate, cookieOf } from "./hocuspocus-server.js"; + +const COOKIE = "lowcoder.sid=abc123"; + +function fetchReturning(status, body) { + const calls = []; + const impl = async (url, options) => { + calls.push({ url, options }); + return { + ok: status >= 200 && status < 300, + status, + json: async () => body, + }; + }; + impl.calls = calls; + return impl; +} + +function fetchThrowing(error) { + return async () => { + throw error; + }; +} + +function fetchNeverCalled() { + return async () => { + throw new Error("fetchImpl must not be called"); + }; +} + +// ----------------------------------------------------------------- authorizeDocument: signal_* rooms + +test("signal_: a 200 with success:true is accepted", async () => { + const fetchImpl = fetchReturning(200, { success: true }); + await authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl, apiServiceUrl: "http://api" }); + assert.equal(fetchImpl.calls.length, 1); + assert.equal(fetchImpl.calls[0].url, "http://api/api/applications/app-1/view"); +}); + +test("signal_: a 200 with success:false is refused", async () => { + const fetchImpl = fetchReturning(200, { success: false }); + await assert.rejects( + authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl }), + /Unauthorized/ + ); +}); + +test("signal_: a 401 is refused", async () => { + const fetchImpl = fetchReturning(401, {}); + await assert.rejects(authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl }), /Unauthorized/); +}); + +test("signal_: a 403 is refused", async () => { + const fetchImpl = fetchReturning(403, {}); + await assert.rejects(authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl }), /Unauthorized/); +}); + +test("signal_: a fetch failure (timeout/network error) is refused", async () => { + const fetchImpl = fetchThrowing(new Error("network error")); + await assert.rejects(authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl }), /Unauthorized/); +}); + +test("signal_: a bad app id is refused before any fetch", async () => { + const fetchImpl = fetchNeverCalled(); + await assert.rejects(authorizeDocument({ documentName: "signal_app one!", cookie: COOKIE, fetchImpl }), /Unauthorized/); +}); + +test("signal_:sub checks , not the sub-room suffix", async () => { + const fetchImpl = fetchReturning(200, { success: true }); + await authorizeDocument({ documentName: "signal_app-1:app-2", cookie: COOKIE, fetchImpl, apiServiceUrl: "http://api" }); + assert.equal(fetchImpl.calls[0].url, "http://api/api/applications/app-1/view"); +}); + +test("the cookie is forwarded and nothing else is sent as a header", async () => { + const fetchImpl = fetchReturning(200, { success: true }); + await authorizeDocument({ documentName: "signal_app-1", cookie: COOKIE, fetchImpl }); + assert.deepEqual(fetchImpl.calls[0].options.headers, { Cookie: COOKIE }); +}); + +test("an id containing an underscore is accepted (the SDK-slug case)", async () => { + const fetchImpl = fetchReturning(200, { success: true }); + await authorizeDocument({ documentName: "signal_my_app_slug", cookie: COOKIE, fetchImpl, apiServiceUrl: "http://api" }); + assert.equal(fetchImpl.calls[0].url, "http://api/api/applications/my_app_slug/view"); +}); + +test("a deliberately long id (500+ chars) of only valid characters is accepted -- no numeric length cap", async () => { + const longId = "a".repeat(500) + "-" + "b".repeat(50); + const fetchImpl = fetchReturning(200, { success: true }); + await authorizeDocument({ documentName: `signal_${longId}`, cookie: COOKIE, fetchImpl, apiServiceUrl: "http://api" }); + assert.equal(fetchImpl.calls[0].url, `http://api/api/applications/${longId}/view`); +}); + +test("an id containing a character outside [A-Za-z0-9_-] is refused before any fetch, regardless of length", async () => { + const fetchImpl = fetchNeverCalled(); + const longInvalidId = "a".repeat(500) + "/evil"; + await assert.rejects(authorizeDocument({ documentName: `signal_${longInvalidId}`, cookie: COOKIE, fetchImpl }), /Unauthorized/); +}); + +test("an empty app id (signal_ alone) is accepted by the regex (matches SlugUtils.validate's *)", async () => { + const fetchImpl = fetchReturning(200, { success: true }); + await authorizeDocument({ documentName: "signal_", cookie: COOKIE, fetchImpl, apiServiceUrl: "http://api" }); + assert.equal(fetchImpl.calls[0].url, "http://api/api/applications//view"); +}); + +// ----------------------------------------------------------------- authorizeDocument: other rooms + +test("bridge-prefixed rooms (typeform_/googleform_/website_) pass without any fetch", async () => { + const fetchImpl = fetchNeverCalled(); + await authorizeDocument({ documentName: "typeform_abc", cookie: COOKIE, fetchImpl }); + await authorizeDocument({ documentName: "googleform_abc", cookie: COOKIE, fetchImpl }); + await authorizeDocument({ documentName: "website_abc", cookie: COOKIE, fetchImpl }); +}); + +test("an unknown room prefix is refused", async () => { + const fetchImpl = fetchNeverCalled(); + await assert.rejects(authorizeDocument({ documentName: "unknown_room", cookie: COOKIE, fetchImpl }), /Unauthorized/); +}); + +// ----------------------------------------------------------------- onAuthenticate (secret gate + wiring) +// onAuthenticate itself is exported (not only authorizeDocument), with injectable secret/authorize parameters +// for tests; production calls it with one argument, so those parameters default to the module's real SECRET and +// authorizeDocument -- these tests inject different ones to prove the gate order without touching real state. + +test("onAuthenticate: a wrong secret token short-circuits before authorizeDocument runs (never calls fetchImpl)", async () => { + const fetchImpl = fetchNeverCalled(); + const authorize = (args) => authorizeDocument({ ...args, fetchImpl }); + + await assert.rejects( + onAuthenticate({ token: "wrong", documentName: "signal_app-1", requestHeaders: { cookie: COOKIE } }, "the-secret", authorize), + /Unauthorized/ + ); + await assert.rejects( + onAuthenticate({ token: "wrong", documentName: "typeform_abc", requestHeaders: { cookie: COOKIE } }, "the-secret", authorize), + /Unauthorized/ + ); +}); + +test("onAuthenticate: a correct token proceeds to authorizeDocument", async () => { + const fetchImpl = fetchReturning(200, { success: true }); + const authorize = (args) => authorizeDocument({ ...args, fetchImpl }); + + await onAuthenticate({ token: "the-secret", documentName: "signal_app-1", requestHeaders: { cookie: COOKIE } }, "the-secret", authorize); + + assert.equal(fetchImpl.calls.length, 1); +}); + +test("onAuthenticate: no secret configured proceeds straight to authorizeDocument", async () => { + const fetchImpl = fetchReturning(200, { success: true }); + const authorize = (args) => authorizeDocument({ ...args, fetchImpl }); + + await onAuthenticate({ token: "anything-or-nothing", documentName: "signal_app-1", requestHeaders: { cookie: COOKIE } }, "", authorize); + + assert.equal(fetchImpl.calls.length, 1); +}); + +test("onAuthenticate: a refused authorizeDocument (e.g. a bad app id) still refuses the connection", async () => { + const fetchImpl = fetchNeverCalled(); + const authorize = (args) => authorizeDocument({ ...args, fetchImpl }); + + await assert.rejects( + onAuthenticate({ token: "", documentName: "signal_app one!", requestHeaders: { cookie: COOKIE } }, "", authorize), + /Unauthorized/ + ); +}); + +// ----------------------------------------------------------------- requestHeaders shape (plain object vs Headers) + +test("cookie extraction: a plain-object requestHeaders (Node IncomingHttpHeaders) works", async () => { + assert.equal(cookieOf({ cookie: COOKIE }), COOKIE); +}); + +test("cookie extraction: a Fetch-API-style Headers instance (.get method) works", async () => { + const headers = new Headers(); + headers.set("cookie", COOKIE); + assert.equal(cookieOf(headers), COOKIE); +}); diff --git a/client/packages/lowcoder/src/comps/comps/moduleComp/moduleComp.tsx b/client/packages/lowcoder/src/comps/comps/moduleComp/moduleComp.tsx index 30805ca766..285fae3a50 100644 --- a/client/packages/lowcoder/src/comps/comps/moduleComp/moduleComp.tsx +++ b/client/packages/lowcoder/src/comps/comps/moduleComp/moduleComp.tsx @@ -23,7 +23,7 @@ import { API_STATUS_CODES } from "constants/apiConstants"; import { AppTypeEnum } from "constants/applicationConstants"; import { GreyTextColor } from "constants/style"; import { ScrollBar, Section, sectionNames } from "lowcoder-design"; -import { ReactNode, useEffect, useMemo } from "react"; +import { ReactNode, useContext, useEffect, useMemo } from "react"; import styled from "styled-components"; import { ExternalEditorContext, @@ -513,14 +513,22 @@ const ModuleCompWithView = withViewFn(ModuleTmpComp, (comp) => { const error = comp.children.error.getView(); const scrollbars = comp.children.scrollbars.getView(); + // Read the ENCLOSING context before this component's own Provider (below) replaces + // it, so a nested chat controller can reach the outermost, actually READ-checked host app id rather than this + // module's own (moduleComp.tsx's Provider overrides `applicationId` with `appId`, which may not itself be + // directly READ-checked for a viewer who only has READ on the host -- see ExternalEditorContext.ts). + const enclosingContext = useContext(ExternalEditorContext); + const hostApplicationId = enclosingContext.hostApplicationId ?? enclosingContext.applicationId; + const moduleExternalState: ExternalEditorContextState = useMemo( () => ({ readOnly: true, hideHeader: true, applicationId: appId, + hostApplicationId, appType: AppTypeEnum.Module, }), - [appId] + [appId, hostApplicationId] ); useEffect(() => { diff --git a/client/packages/lowcoder/src/comps/hooks/chatControllerComp.tsx b/client/packages/lowcoder/src/comps/hooks/chatControllerComp.tsx index 1b220cf40f..f4fe831d2f 100644 --- a/client/packages/lowcoder/src/comps/hooks/chatControllerComp.tsx +++ b/client/packages/lowcoder/src/comps/hooks/chatControllerComp.tsx @@ -1,4 +1,5 @@ -import React, { useCallback, useEffect, useMemo, useRef } from "react"; +import React, { useCallback, useContext, useEffect, useMemo, useRef } from "react"; +import { ExternalEditorContext } from "util/context/ExternalEditorContext"; import { Section, sectionNames } from "lowcoder-design"; import { PropertyViewDocLink } from "comps/utils/propertyViewDocLink"; import { @@ -452,7 +453,16 @@ const ChatControllerBase = withViewFn( const userName = comp.children.userName.getView().value; const applicationId = comp.children.applicationId.getView().value; - const roomName = `signal_${applicationId || "lowcoder_app"}`; + // The room must be bound to the HOST application the viewer actually has READ on, + // not the immediate ExternalEditorContext.applicationId, which a module's own Provider overrides with the + // module's own id (moduleComp.tsx) -- a weaker authorization boundary than the host's (see + // ExternalEditorContext.ts / moduleComp.tsx for why). The `applicationId` property here now names a SUB-ROOM + // of the host, not another app. + const externalContext = useContext(ExternalEditorContext); + const hostAppId = externalContext.hostApplicationId ?? externalContext.applicationId; + const roomName = (!applicationId || applicationId === "lowcoder_app" || applicationId === hostAppId) + ? `signal_${hostAppId || "lowcoder_app"}` + : `signal_${hostAppId || "lowcoder_app"}:${applicationId}`; return ( (null); useEffect(() => { - // Only fetch common settings if not already loaded - if (Object.keys(commonSettings).length === 0) { + if (fetchedSettingsOrgIdRef.current !== currentUser.currentOrgId) { + fetchedSettingsOrgIdRef.current = currentUser.currentOrgId; dispatch(fetchCommonSettings({ orgId: currentUser.currentOrgId })); } - }, [currentUser.currentOrgId, dispatch, commonSettings]); + }, [currentUser.currentOrgId, dispatch]); // Lazy load applications only when dropdown is opened const handleDropdownOpen = () => { diff --git a/client/packages/lowcoder/src/util/context/ExternalEditorContext.hostApplicationId.test.tsx b/client/packages/lowcoder/src/util/context/ExternalEditorContext.hostApplicationId.test.tsx new file mode 100644 index 0000000000..cbb138344f --- /dev/null +++ b/client/packages/lowcoder/src/util/context/ExternalEditorContext.hostApplicationId.test.tsx @@ -0,0 +1,159 @@ +import { render, screen } from "@testing-library/react"; +import { useContext, useMemo } from "react"; +import { + ExternalEditorContext, + ExternalEditorContextState, +} from "./ExternalEditorContext"; +import { AppTypeEnum } from "constants/applicationConstants"; + +/** + * Tests the `hostApplicationId` threading between a module's own `ExternalEditorContext` + * Provider and a nested chat controller. The real `moduleComp.tsx`/`chatControllerComp.tsx` compute these values + * inside `withViewFn` render callbacks tied to the full comp/DSL framework (see `moduleComp.test.tsx`'s + * dispatch-driven style), which is impractical to mount for this narrow concern; this test mirrors their exact + * `useContext`/`useMemo` expressions in minimal stand-in components, to prove the context-propagation algorithm + * itself in isolation. + */ + +/** Mirrors moduleComp.tsx's moduleExternalState useMemo exactly. */ +function StandInModule({ appId, children }: { appId: string; children: React.ReactNode }) { + const enclosingContext = useContext(ExternalEditorContext); + const hostApplicationId = enclosingContext.hostApplicationId ?? enclosingContext.applicationId; + + const moduleExternalState: ExternalEditorContextState = useMemo( + () => ({ + readOnly: true, + hideHeader: true, + applicationId: appId, + hostApplicationId, + appType: AppTypeEnum.Module, + }), + [appId, hostApplicationId] + ); + + return ( + + {children} + + ); +} + +/** Mirrors chatControllerComp.tsx's roomName computation exactly. */ +function StandInChatController({ applicationIdProperty }: { applicationIdProperty: string }) { + const externalContext = useContext(ExternalEditorContext); + const hostAppId = externalContext.hostApplicationId ?? externalContext.applicationId; + const roomName = (!applicationIdProperty || applicationIdProperty === "lowcoder_app" || applicationIdProperty === hostAppId) + ? `signal_${hostAppId || "lowcoder_app"}` + : `signal_${hostAppId || "lowcoder_app"}:${applicationIdProperty}`; + return
{roomName}
; +} + +/** Probes the current context's resolved host id directly. */ +function HostIdProbe() { + const ctx = useContext(ExternalEditorContext); + return
{ctx.hostApplicationId ?? ctx.applicationId}
; +} + +const TOP_LEVEL_HOST = "host-app"; +const OUTER_MODULE_APP = "outer-module-app"; +const INNER_MODULE_APP = "inner-module-app"; + +function topLevelContext(applicationId: string): ExternalEditorContextState { + return { applicationId, appType: AppTypeEnum.Application }; +} + +describe("ExternalEditorContext hostApplicationId threading", () => { + it("a top-level host page (no hostApplicationId of its own) resolves to its own applicationId", () => { + render( + + + + ); + expect(screen.getByTestId("host-id").textContent).toBe(TOP_LEVEL_HOST); + }); + + it("a module embedded in a top-level host propagates the HOST id as hostApplicationId, not its own appId", () => { + render( + + + + + + ); + expect(screen.getByTestId("host-id").textContent).toBe(TOP_LEVEL_HOST); + }); + + it("a module viewed stand-alone (no enclosing host) falls back to its own appId", () => { + render( + + + + ); + expect(screen.getByTestId("host-id").textContent).toBe(OUTER_MODULE_APP); + }); + + it("a module nested inside another module still resolves to the OUTERMOST host, not the outer module's id", () => { + render( + + + + + + + + ); + expect(screen.getByTestId("host-id").textContent).toBe(TOP_LEVEL_HOST); + }); + + it("a chat controller inside a module picks hostApplicationId over applicationId when both are present", () => { + render( + + + + + + ); + expect(screen.getByTestId("room-name").textContent).toBe(`signal_${TOP_LEVEL_HOST}`); + }); + + it("a chat controller falls back to applicationId when hostApplicationId is unset (stand-alone / top-level)", () => { + render( + + + + ); + expect(screen.getByTestId("room-name").textContent).toBe(`signal_${TOP_LEVEL_HOST}`); + }); + + it("a non-empty sub-room property names signal_:, binding to the HOST, not another app", () => { + render( + + + + + + ); + expect(screen.getByTestId("room-name").textContent).toBe(`signal_${TOP_LEVEL_HOST}:sub-room`); + }); + + it("re-rendering with ONLY the enclosing context's hostApplicationId changed (module's own appId unchanged) recomputes the inner probe", () => { + const { rerender } = render( + + + + + + ); + expect(screen.getByTestId("host-id").textContent).toBe(TOP_LEVEL_HOST); + + const NEW_HOST = "a-different-host-app"; + rerender( + + + + + + ); + expect(screen.getByTestId("host-id").textContent).toBe(NEW_HOST); + }); +}); diff --git a/client/packages/lowcoder/src/util/context/ExternalEditorContext.ts b/client/packages/lowcoder/src/util/context/ExternalEditorContext.ts index 94ade722f7..d076565003 100644 --- a/client/packages/lowcoder/src/util/context/ExternalEditorContext.ts +++ b/client/packages/lowcoder/src/util/context/ExternalEditorContext.ts @@ -9,6 +9,17 @@ export interface ExternalEditorContextState { applicationId: string; + /** + * The outermost, actually READ-checked application id. Additive -- `applicationId` + * keeps its existing meaning and uses unchanged. A module's own `Provider` overrides `applicationId` with its + * own id (moduleComp.tsx), so a nested component (e.g. the chat controller) that needs the HOST app a viewer + * was actually granted READ on -- not an embedded module's own id, which may not itself be directly + * READ-checked -- reads this field instead. Unset at the top level (the host page itself, module or not); a + * module propagates it from its own enclosing context so nested modules keep pointing at the same, outermost + * host (see moduleComp.tsx). + */ + hostApplicationId?: string; + /** * uneditable, hide the left/bottom/right panel */ diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/Organization.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/Organization.java index 560978b740..1a2f98b5c4 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/Organization.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/Organization.java @@ -96,6 +96,8 @@ public OrganizationCommonSettings getCommonSettings() { public static class OrganizationCommonSettings extends HashMap { public static final String PASSWORD_RESET_EMAIL_TEMPLATE = "PASSWORD_RESET_EMAIL_TEMPLATE"; + /** A registry URL and its {@code auth.credentials} (a bearer token or base64 user:password). */ + public static final String NPM_REGISTRIES = "npmRegistries"; /** The suffix of the key that holds when a setting was last written ({@code _updateTime}). */ public static final String UPDATE_TIME_SUFFIX = "_updateTime"; @@ -103,7 +105,8 @@ public static class OrganizationCommonSettings extends HashMap { * Settings excluded from sanitized export */ private final Set excludedKeys = Set.of( - PASSWORD_RESET_EMAIL_TEMPLATE + PASSWORD_RESET_EMAIL_TEMPLATE, + NPM_REGISTRIES ); /** The key that holds when the setting {@code key} was last written. */ @@ -113,8 +116,9 @@ public static String updateTimeKey(String key) { /** * A copy without the excluded settings and their update times (GH-02, GitHub #924: the update time of the - * password-reset template was kept), for views that are not the settings' own: the user profile and the - * application views, which reach anonymous visitors of a public application. + * password-reset template was kept; the npm registry credential is excluded the same way), for views that + * are not the settings' own: the user profile and the application views, which reach anonymous visitors of + * a public application. */ public OrganizationCommonSettings sanitized() { OrganizationCommonSettings sanitized = new OrganizationCommonSettings(); diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/service/OrgMemberService.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/service/OrgMemberService.java index 3e9a965804..1738bfe3cf 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/service/OrgMemberService.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/service/OrgMemberService.java @@ -28,6 +28,15 @@ public interface OrgMemberService { Mono countAllActiveOrgs(String userId); + /** + * Every RAW membership row this user has, untouched by {@link #getAllActiveOrgs}/{@link #countAllActiveOrgs}'s + * ENTERPRISE-mode collapsing (which, with a configured enterprise org, answers a single row regardless of how + * many real memberships exist, and otherwise truncates to the first). A caller + * that needs to know whether an account's membership is genuinely EXCLUSIVE -- not merely "counts as 1 after + * enterprise collapsing" -- must read this instead. + */ + Mono> getRawOrgMemberships(String userId); + Mono getOrgMember(String orgId, String userId); Mono addMember(String orgId, String userId, MemberRole memberRole); diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/service/OrgMemberServiceImpl.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/service/OrgMemberServiceImpl.java index 581475f175..aaa4e2ffe1 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/service/OrgMemberServiceImpl.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/service/OrgMemberServiceImpl.java @@ -268,6 +268,11 @@ private Flux membershipsOf(String userId) { .map(OrgMember::from); } + @Override + public Mono> getRawOrgMemberships(String userId) { + return membershipsOf(userId).collectList(); + } + /** * The org ids {@link #getAllActiveOrgs} answers memberships of, and whether finding them enrolled the user in the * enterprise org, a membership written after the memberships were read (BF-131). diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserServiceImpl.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserServiceImpl.java index 4c1e41bc80..4066e3441e 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserServiceImpl.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserServiceImpl.java @@ -171,6 +171,31 @@ private static boolean canRecoverPassword(User user) { return user.getState() != UserState.DELETED; } + /** + * The account's own address to mail a password-reset token to, never the text the requester typed (the + * account may have been resolved by display name, not by address). {@code user.getEmail()} when it is non-blank + * AND address-shaped ({@link EmailUtils#looksLikeEmail}: a legacy install can carry a display name there, from + * changeset 023's one-time {@code email = name} backfill, and {@link #addNewConnectionAndReturnUser} can set it + * from a connection's claimed email of any source); else, when exactly one EMAIL-source connection's + * {@code rawId} is address-shaped, that one. Zero or more than one qualifying connection -- with no timestamp on + * {@link Connection} to say which is current -- completes empty rather than guessing: mailing a wrong one of + * several would be worse than mailing none. + */ + private static Optional recoveryAddressOf(User user) { + if (EmailUtils.looksLikeEmail(user.getEmail())) { + return Optional.of(user.getEmail()); + } + List emailConnectionAddresses = user.getConnections().stream() + .filter(connection -> AuthSourceConstants.EMAIL.equals(connection.getSource())) + .map(Connection::getRawId) + .filter(EmailUtils::looksLikeEmail) + .toList(); + if (emailConnectionAddresses.size() == 1) { + return Optional.of(emailConnectionAddresses.get(0)); + } + return Optional.empty(); + } + /** * One probe of the email keyspace, resolved deterministically. * @@ -422,14 +447,17 @@ public Mono resetPassword(String userId) { /** * Looks up the account named by {@code userEmail} (an email, else a name) and, when it can recover its password, mails a - * password reset link to {@code userEmail} as given and then stores the token's hash and a 12 hour expiry; completes - * empty when it ends normally, a mail that is not sent included, and fails when a lookup or the save fails or the mail - * call throws. + * password reset link to the ACCOUNT'S OWN address ({@link #recoveryAddressOf}) -- never to {@code userEmail} as + * typed, so an account resolved by display name does not leak its reset token to whatever text (an address the + * requester owns, not the account's) was typed -- and then stores the token's hash and a 12 hour expiry; completes + * empty when it ends normally, a mail that is not sent (no qualifying address, or the mail call itself declining) + * included, and fails when a lookup or the save fails or the mail call throws. *

- * Limits: for an account found by its name the recipient is that name, which the mail call uses as an address, so such a - * mail is sent only if the name is accepted as one; the mail is sent before the token is saved (NEW-93: kept, owner - * decision D6), so a save that fails after a sent mail leaves a link that no stored token matches; a mail that is not - * sent stores nothing ({@code lostPassword_mailSendFails_storesNothing}). + * Limits: the mail is sent before the token is saved (NEW-93: kept, owner decision D6), so a save that fails after a + * sent mail leaves a link that no stored token matches; a mail that is not sent stores nothing + * ({@code lostPassword_mailSendFails_storesNothing}). {@link #recoveryAddressOf}'s own limits: + * it trusts {@code user.getEmail()} once it is address-shaped without requiring that value + * came from an EMAIL-source connection, matching every other email-matching path in this class. */ @Override public Mono lostPassword(String userEmail) { @@ -440,10 +468,14 @@ public Mono lostPassword(String userEmail) { .flatMap(tuple -> { User user = tuple.getT1(); String emailTemplate = tuple.getT2(); + Optional recoveryAddress = recoveryAddressOf(user); + if (recoveryAddress.isEmpty()) { + return Mono.empty(); + } String token = generateNewRandomPwd(); Instant tokenExpiry = Instant.now().plus(12, ChronoUnit.HOURS); - if (!emailCommunicationService.sendPasswordResetEmail(userEmail, token, emailTemplate)) { + if (!emailCommunicationService.sendPasswordResetEmail(recoveryAddress.get(), token, emailTemplate)) { return Mono.empty(); } user.setPasswordResetToken(HashUtils.hash(token.getBytes())); diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/organization/model/OrganizationCommonSettingsSanitizedTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/organization/model/OrganizationCommonSettingsSanitizedTest.java new file mode 100644 index 0000000000..d7ea2c821c --- /dev/null +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/organization/model/OrganizationCommonSettingsSanitizedTest.java @@ -0,0 +1,55 @@ +package org.lowcoder.domain.organization.model; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.lowcoder.domain.organization.model.Organization.OrganizationCommonSettings.NPM_REGISTRIES; +import static org.lowcoder.domain.organization.model.Organization.OrganizationCommonSettings.PASSWORD_RESET_EMAIL_TEMPLATE; +import static org.lowcoder.domain.organization.model.Organization.OrganizationCommonSettings.updateTimeKey; + +import org.junit.jupiter.api.Test; +import org.lowcoder.domain.organization.model.Organization.OrganizationCommonSettings; + +/** + * {@code sanitized()} must drop {@code npmRegistries} (a registry URL and its + * {@code auth.credentials}) and its update time, the same way it already drops the password-reset template. + */ +class OrganizationCommonSettingsSanitizedTest { + + private static final String OTHER_KEY = "defaultHomePage"; + private static final String NPM_REGISTRY_VALUE = "OrganizationCommonSettingsSanitizedTest.npmRegistryCredential"; + + @Test + void sanitized_dropsNpmRegistriesAndItsUpdateTime_keepsOtherKeys() { + OrganizationCommonSettings settings = new OrganizationCommonSettings(); + settings.put(NPM_REGISTRIES, NPM_REGISTRY_VALUE); + settings.put(updateTimeKey(NPM_REGISTRIES), 123L); + settings.put(PASSWORD_RESET_EMAIL_TEMPLATE, "template"); + settings.put(OTHER_KEY, "home"); + + OrganizationCommonSettings sanitized = settings.sanitized(); + + assertThat(sanitized).doesNotContainKey(NPM_REGISTRIES); + assertThat(sanitized).doesNotContainKey(updateTimeKey(NPM_REGISTRIES)); + assertThat(sanitized).doesNotContainKey(PASSWORD_RESET_EMAIL_TEMPLATE); + assertThat(sanitized).containsEntry(OTHER_KEY, "home"); + System.out.println("[OrganizationCommonSettingsSanitizedTest] sanitized=" + sanitized); + } + + @Test + void sanitized_doesNotModifyTheOriginalMap() { + OrganizationCommonSettings settings = new OrganizationCommonSettings(); + settings.put(NPM_REGISTRIES, NPM_REGISTRY_VALUE); + settings.put(OTHER_KEY, "home"); + + settings.sanitized(); + + assertThat(settings).containsEntry(NPM_REGISTRIES, NPM_REGISTRY_VALUE); + assertThat(settings).containsEntry(OTHER_KEY, "home"); + } + + @Test + void sanitized_emptyMap_answersEmpty() { + OrganizationCommonSettings settings = new OrganizationCommonSettings(); + + assertThat(settings.sanitized()).isEmpty(); + } +} diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/UserServiceImplPasswordTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/UserServiceImplPasswordTest.java index 513bccb50e..154de5a62a 100644 --- a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/UserServiceImplPasswordTest.java +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/UserServiceImplPasswordTest.java @@ -21,11 +21,15 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.NullAndEmptySource; +import java.util.Set; + import org.lowcoder.domain.organization.model.OrgMember; import org.lowcoder.domain.organization.model.Organization; import org.lowcoder.domain.organization.model.Organization.OrganizationCommonSettings; +import org.lowcoder.domain.user.model.Connection; import org.lowcoder.domain.user.model.User; import org.lowcoder.domain.user.model.UserState; +import org.lowcoder.sdk.constants.AuthSourceConstants; import org.lowcoder.sdk.exception.BizError; import org.lowcoder.sdk.exception.BizException; import org.lowcoder.sdk.util.HashUtils; @@ -343,6 +347,131 @@ void lostPassword_unknownAndDeletedAccount_sendNothing() { System.out.println("[UserServiceImplPasswordTest] unknown and deleted accounts -> no mail, no save"); } + private static final String TYPED_NAME = "UserServiceImplPasswordTest.typedDisplayName"; + private static final String ALIAS_THE_REQUESTER_OWNS = "attacker-alias@example.com"; + private static final String CONNECTION_EMAIL = "connection-lookup@example.com"; + private static final String QUALIFYING_RAW_ID = "UserServiceImplPasswordTest.qualifyingRawId@example.com"; + private static final String NOT_AN_ADDRESS = "UserServiceImplPasswordTest.notAnAddress"; + + private void stubNameLookup(String typed, User... users) { + when(fixture.repository.findByEmailOrConnections_Email(typed, typed)).thenReturn(Flux.empty()); + when(fixture.repository.findByName(typed)).thenReturn(Mono.just(users[0])); + } + + private static Connection emailConnection(String rawId) { + return Connection.builder().authId("auth-" + rawId).source(AuthSourceConstants.EMAIL).rawId(rawId).build(); + } + + /** + * An account resolved by DISPLAY NAME (the attacker typed an alias they own, which happens to be the + * account's display name) must still be mailed at its OWN address, never at the typed alias. + */ + @Test + void lostPassword_resolvedByName_mailsTheAccountsOwnAddressNeverTheTypedText() { + User user = User.builder().id(USER_ID).email(USER_EMAIL).build(); + stubNameLookup(ALIAS_THE_REQUESTER_OWNS, user); + stubOrgOfUser(); + when(fixture.emailCommunicationService.sendPasswordResetEmail(eq(USER_EMAIL), any(), any())).thenReturn(true); + + StepVerifier.create(service.lostPassword(ALIAS_THE_REQUESTER_OWNS)).verifyComplete(); + + verify(fixture.emailCommunicationService).sendPasswordResetEmail(eq(USER_EMAIL), any(), any()); + verify(fixture.emailCommunicationService, never()).sendPasswordResetEmail(eq(ALIAS_THE_REQUESTER_OWNS), any(), any()); + System.out.println("[UserServiceImplPasswordTest] account found by name -> mailed to its own address, not the typed alias"); + } + + /** No stored email, no EMAIL-source connection -> no address to recover, no mail, no save. */ + @Test + void lostPassword_noEmailAndNoEmailConnection_sendsNothing() { + User user = User.builder().id(USER_ID).email("").connections(Set.of()).build(); + stubEmailLookup(user); + stubOrgOfUser(); + + StepVerifier.create(service.lostPassword(USER_EMAIL)).verifyComplete(); + + verify(fixture.emailCommunicationService, never()).sendPasswordResetEmail(any(), any(), any()); + verify(fixture.repository, never()).save(any(User.class)); + } + + /** Resolved through a connection's own {@code email} field (the lookup keyspace); still mailed to the stored address. */ + @Test + void lostPassword_resolvedThroughConnectionEmail_mailsTheStoredAddress() { + User user = User.builder().id(USER_ID).email(USER_EMAIL).build(); + when(fixture.repository.findByEmailOrConnections_Email(CONNECTION_EMAIL, CONNECTION_EMAIL)).thenReturn(Flux.just(user)); + stubOrgOfUser(); + when(fixture.emailCommunicationService.sendPasswordResetEmail(eq(USER_EMAIL), any(), any())).thenReturn(true); + + StepVerifier.create(service.lostPassword(CONNECTION_EMAIL)).verifyComplete(); + + verify(fixture.emailCommunicationService).sendPasswordResetEmail(eq(USER_EMAIL), any(), any()); + } + + /** Blank stored email, one EMAIL connection with an address-shaped {@code rawId} -> mailed to that {@code rawId}. */ + @Test + void lostPassword_blankEmailOneQualifyingEmailConnection_mailsItsRawId() { + Connection connection = emailConnection(QUALIFYING_RAW_ID); + User user = User.builder().id(USER_ID).email("").connections(Set.of(connection)).build(); + stubEmailLookup(user); + stubOrgOfUser(); + when(fixture.emailCommunicationService.sendPasswordResetEmail(eq(QUALIFYING_RAW_ID), any(), any())).thenReturn(true); + + StepVerifier.create(service.lostPassword(USER_EMAIL)).verifyComplete(); + + verify(fixture.emailCommunicationService).sendPasswordResetEmail(eq(QUALIFYING_RAW_ID), any(), any()); + } + + /** + * A stored {@code email} that is not address-shaped (a display name, as changeset 023's legacy backfill left + * behind) and no EMAIL connection -> the invalid stored value must not be mailed to; no mail, no save. + */ + @Test + void lostPassword_storedEmailNotAddressShapedAndNoEmailConnection_sendsNothing() { + User user = User.builder().id(USER_ID).email(NOT_AN_ADDRESS).connections(Set.of()).build(); + stubEmailLookup(user); + stubOrgOfUser(); + + StepVerifier.create(service.lostPassword(USER_EMAIL)).verifyComplete(); + + verify(fixture.emailCommunicationService, never()).sendPasswordResetEmail(any(), any(), any()); + verify(fixture.repository, never()).save(any(User.class)); + } + + /** + * Blank stored email, MULTIPLE EMAIL connections with address-shaped {@code rawId}s -- with no timestamp to + * say which is current, the fix must not guess: no mail, no save. + */ + @Test + void lostPassword_blankEmailMultipleQualifyingEmailConnections_sendsNothing() { + User user = User.builder().id(USER_ID).email("") + .connections(Set.of(emailConnection("first-qualifying@example.com"), emailConnection("second-qualifying@example.com"))) + .build(); + stubEmailLookup(user); + stubOrgOfUser(); + + StepVerifier.create(service.lostPassword(USER_EMAIL)).verifyComplete(); + + verify(fixture.emailCommunicationService, never()).sendPasswordResetEmail(any(), any(), any()); + verify(fixture.repository, never()).save(any(User.class)); + } + + /** + * Blank stored email, exactly ONE EMAIL connection has an address-shaped {@code rawId} (another present EMAIL + * connection does not) -> mailed to the one qualifying {@code rawId}. + */ + @Test + void lostPassword_blankEmailExactlyOneQualifyingAmongSeveralEmailConnections_mailsThatOne() { + Connection nonQualifying = emailConnection(NOT_AN_ADDRESS); + Connection qualifying = emailConnection(QUALIFYING_RAW_ID); + User user = User.builder().id(USER_ID).email("").connections(Set.of(nonQualifying, qualifying)).build(); + stubEmailLookup(user); + stubOrgOfUser(); + when(fixture.emailCommunicationService.sendPasswordResetEmail(eq(QUALIFYING_RAW_ID), any(), any())).thenReturn(true); + + StepVerifier.create(service.lostPassword(USER_EMAIL)).verifyComplete(); + + verify(fixture.emailCommunicationService).sendPasswordResetEmail(eq(QUALIFYING_RAW_ID), any(), any()); + } + private static final Duration RESET_TOKEN_LIFETIME = Duration.ofHours(12); private static final String ORG_LOOKUP_ERROR_KEY = "INVALID_ORG_ID"; private static final String MEMBERSHIP_LOOKUP_FAILURE = "UserServiceImplPasswordTest.membership-lookup-failure"; diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImpl.java index 0ff4397dc2..79201f900d 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImpl.java @@ -36,6 +36,7 @@ import org.lowcoder.sdk.auth.AbstractAuthConfig; import org.lowcoder.sdk.config.AuthProperties; import org.lowcoder.sdk.config.CommonConfig; +import org.lowcoder.sdk.constants.AuthSourceConstants; import org.lowcoder.sdk.constants.WorkspaceMode; import org.lowcoder.sdk.exception.BizError; import org.lowcoder.sdk.exception.BizException; @@ -179,6 +180,17 @@ public Mono loginOrRegister(AuthUser authUser, ServerWebExchange exchange, .then(businessEventPublisher.publishUserLoginEvent(authUser.getSource())); } + /** + * Resolves the account for an authentication attempt, in order: (1) an existing connection of the same source + * and subject -- update it; (2) an account found by e-mail address not yet connected this way -- link it ONLY + * when {@link #linkByAddressOrRefuse} allows it, else refuse with no session opened; (3) register, or + * {@code USER_NOT_EXIST}. + *

+ * Limits: a person who already has an e-mail account and signs in with a provider + * for the first time is refused here and must link the provider from their profile instead of being linked by + * address automatically; the same for a SCIM-provisioned placeholder that already had a prior account. Identities + * remain keyed by provider type plus subject for branch 1/{@code updateConnection}, unchanged by this phase. + */ public Mono updateOrCreateUser(AuthUser authUser, boolean linkExistingUser, boolean isSuperAdmin) { if(linkExistingUser) { @@ -200,10 +212,9 @@ public Mono updateOrCreateUser(AuthUser authUser, boolean linkExistingUser } //If the user connection is not found with login id, but the user is - // found for the same id in some different connection, then just add a new connection to the user + // found for the same id in some different connection, then only link it when it is safe to if(findByAuthUserSecond.userExist()) { - User user = findByAuthUserSecond.user(); - return userService.addNewConnectionAndReturnUser(user.getId(), authUser); + return linkByAddressOrRefuse(authUser, findByAuthUserSecond.user(), isSuperAdmin); } if (authUser.getAuthContext().getAuthConfig().isEnableRegister()) { @@ -213,6 +224,47 @@ public Mono updateOrCreateUser(AuthUser authUser, boolean linkExistingUser }); } + /** + * An account found only by e-mail address (not by the same source/subject + * connection) is linked ONLY when that is safe, never merely because the address matches: + *

    + *
  • {@code isSuperAdmin}: the deployment-configured super-admin setup, unchanged;
  • + *
  • otherwise, only for a non-EMAIL source, an account with NO connections at all (a SCIM placeholder), AND an + * EXCLUSIVE raw membership of the provider's own workspace ({@code authUser.getOrgId()}) -- not merely "is a + * member of it among possibly others". A plain membership check is not enough: {@code + * UserController#createSCIMUserAndAddToOrg} lets an admin of ANY org pull an existing placeholder found by + * e-mail into their own org as a second raw membership regardless of its connection state, which would satisfy a + * looser check; requiring exactly one raw row defeats that, since the polluted placeholder then has two.
  • + *
+ * Every other match is refused, with no connection added and no account mutated: {@code USER_LOGIN_ID_EXIST} for + * an EMAIL-source (form) attempt, the answer of an existing login id; {@code ALREADY_BIND} for any other source. + * The raw memberships are read ONCE via {@link OrgMemberService#getRawOrgMemberships}, not {@code + * countAllActiveOrgs} (which is ENTERPRISE-mode-aware and collapses multiple real memberships down to one, so it + * would not catch a cross-org SCIM-pollution attack there) and not as two separate queries (which would reopen a + * race window against a concurrent {@code createSCIMUserAndAddToOrg} call between them). + */ + private Mono linkByAddressOrRefuse(AuthUser authUser, User found, boolean isSuperAdmin) { + if (isSuperAdmin) { + return userService.addNewConnectionAndReturnUser(found.getId(), authUser); + } + boolean isEmailSource = AuthSourceConstants.EMAIL.equals(authUser.getSource()); + if (isEmailSource) { + return Mono.error(new BizException(USER_LOGIN_ID_EXIST, "USER_LOGIN_ID_EXIST")); + } + if (CollectionUtils.isEmpty(found.getConnections())) { + return orgMemberService.getRawOrgMemberships(found.getId()) + .flatMap(orgMembers -> { + boolean isExclusiveMemberOfProviderOrg = orgMembers.size() == 1 + && orgMembers.get(0).getOrgId().equals(authUser.getOrgId()); + if (isExclusiveMemberOfProviderOrg) { + return userService.addNewConnectionAndReturnUser(found.getId(), authUser); + } + return Mono.error(new BizException(ALREADY_BIND, "ALREADY_BIND")); + }); + } + return Mono.error(new BizException(ALREADY_BIND, "ALREADY_BIND")); + } + protected Mono findByAuthUserSourceAndRawId(AuthUser authUser) { return userService.findByAuthUserSourceAndRawId(authUser) .map(user -> new FindByAuthUser(true, user)) diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/FolderApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/FolderApiServiceImpl.java index 0daf15d423..a743f5c493 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/FolderApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/FolderApiServiceImpl.java @@ -188,7 +188,7 @@ public Mono update(Folder folder) { newFolder.setCategory(folder.getCategory()); newFolder.setDescription(folder.getDescription()); newFolder.setImage(folder.getImage()); - return checkManagePermission(folder.getId()) + return checkManagePermissionInCurrentOrg(folder.getId()) .flatMap(orgMember -> checkFolderExist(folder.getId()) .flatMap(existing -> checkFolderNameUnique(existing.getParentFolderId(), folder.getName(), orgMember.getOrgId(), existing.getId()))) @@ -401,12 +401,45 @@ private Mono isCreator(String folderId) { .flatMap(folder -> sessionUserService.getVisitorId().map(s -> s.equals(folder.getCreatedBy()))); } + /** + * {@code checkManagePermission} passes any ADMIN/SUPER_ADMIN of the visitor's CURRENT + * org for ANY folder id, whichever org owns it -- this additive check compares the folder's own + * {@code organizationId} against the visitor's current org first, so a folder of another workspace is refused + * with {@code FOLDER_OPERATE_NO_PERMISSION} regardless of the visitor's role, before any admin/creator rule is + * even considered. Used ONLY by {@link #update}, {@link #grantPermission}, {@link #updatePermission} and + * {@link #removePermission} -- deliberately NOT by {@link #delete}, whose tree lookup (built from the current + * org's own folders) already scopes it to the current org, and which has its own pinned behaviour for an admin + * (never looks the folder up) and for a non-admin on an unknown id (completes empty, not an error) that a + * shared rewrite would break. A blank id falls back to the old, unchanged {@link #checkManagePermission} exactly + * (BF-159: {@code updatePermission}/{@code removePermission} with a null folder id must still be refused by + * {@code checkPermissionResource}'s own foreign-permission check, not by an eager {@code FOLDER_NOT_EXIST} from + * this method's new lookup). + */ + private Mono checkManagePermissionInCurrentOrg(String folderId) { + if (StringUtils.isBlank(folderId)) { + return checkManagePermission(folderId); + } + return sessionUserService.getVisitorOrgMemberCache() + .zipWith(checkFolderExist(folderId)) + .flatMap(tuple -> { + OrgMember orgMember = tuple.getT1(); + Folder folder = tuple.getT2(); + if (!orgMember.getOrgId().equals(folder.getOrganizationId())) { + return ofError(FOLDER_OPERATE_NO_PERMISSION, "FOLDER_OPERATE_NO_PERMISSION"); + } + if (isOrgAdmin(orgMember) || orgMember.getUserId().equals(folder.getCreatedBy())) { + return Mono.just(orgMember); + } + return ofError(FOLDER_OPERATE_NO_PERMISSION, "FOLDER_OPERATE_NO_PERMISSION"); + }); + } + @Override public Mono grantPermission(String folderId, Set userIds, Set groupIds, ResourceRole role) { if (CollectionUtils.isEmpty(userIds) && CollectionUtils.isEmpty(groupIds)) { return Mono.empty(); } - return Mono.from(checkManagePermission(folderId)) + return Mono.from(checkManagePermissionInCurrentOrg(folderId)) .then(checkFolderExist(folderId)) .then(Mono.defer(() -> resourcePermissionService.insertBatchPermission(ResourceType.FOLDER, folderId, userIds, groupIds, role))) .then(); @@ -414,7 +447,7 @@ public Mono grantPermission(String folderId, Set userIds, Set updatePermission(String folderId, String permissionId, ResourceRole role) { - return Mono.from(checkManagePermission(folderId)) + return Mono.from(checkManagePermissionInCurrentOrg(folderId)) .then(checkPermissionResource(permissionId, folderId)) .then(resourcePermissionService.updateRoleById(permissionId, role)) .then(); @@ -422,7 +455,7 @@ public Mono updatePermission(String folderId, String permissionId, Resourc @Override public Mono removePermission(String folderId, String permissionId) { - return Mono.from(checkManagePermission(folderId)) + return Mono.from(checkManagePermissionInCurrentOrg(folderId)) .then(checkPermissionResource(permissionId, folderId)) .then(resourcePermissionService.removeById(permissionId)) .then(); diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserApiServiceImpl.java index 6d018984fd..5b8b50a408 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserApiServiceImpl.java @@ -58,12 +58,44 @@ private Mono checkAdminPermissionAndUserBelongsToCurrentOrg(String userId) }); } + /** + * After the existing admin/membership check, a target that is SUPER_ADMIN of the + * visitor's current org, or whose account-wide {@code superAdmin} flag is set (the instance super admin is a + * SUPER_ADMIN member of every workspace), is refused with {@code UNSUPPORTED_OPERATION} unless the visitor is + * resetting their OWN password -- the same rank rule {@code OrgApiServiceImpl#checkSuperAdminRoleUnchanged} + * applies to a role change. Limits: an ADMIN may still reset another ADMIN's password (unchanged, by design); + * no session of the target is ended by a reset, fixed or not (tracked separately). + */ @Override public Mono resetPassword(String userId) { return checkAdminPermissionAndUserBelongsToCurrentOrg(userId) + .then(checkResetTargetBelowSuperAdmin(userId)) .then(userService.resetPassword(userId)); } + private Mono checkResetTargetBelowSuperAdmin(String userId) { + return sessionUserService.getVisitorId() + .flatMap(visitorId -> { + if (visitorId.equals(userId)) { + return Mono.empty(); + } + return sessionUserService.getVisitorOrgMemberCache() + .flatMap(visitorOrgMember -> orgMemberService.getOrgMember(visitorOrgMember.getOrgId(), userId)) + .flatMap(targetOrgMember -> { + if (targetOrgMember.isSuperAdmin()) { + return ofError(UNSUPPORTED_OPERATION, "BAD_REQUEST"); + } + return userService.findById(userId) + .flatMap(user -> { + if (Boolean.TRUE.equals(user.getSuperAdmin())) { + return ofError(UNSUPPORTED_OPERATION, "BAD_REQUEST"); + } + return Mono.empty(); + }); + }); + }); + } + @Override public Mono lostPassword(String userEmail) { return userService.lostPassword(userEmail); diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserController.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserController.java index 5e0d3656c0..bbc4e31e2e 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserController.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserController.java @@ -199,8 +199,8 @@ public Mono> update(@RequestBody UpdateUserRequest @Override public Mono> update(@PathVariable String orgId, @PathVariable String userId, @RequestBody UpdateUserRequest updateUserRequest, ServerWebExchange exchange) { - return orgApiService.checkVisitorAdminRole(orgId) - .flatMap(__ -> updateUser(userId, updateUserRequest, exchange)); + return checkVisitorManagesMember(orgId, userId) + .flatMap(__ -> updateManagedUser(userId, updateUserRequest)); } public Mono> updateUser(String userId, @RequestBody UpdateUserRequest updateUserRequest, ServerWebExchange exchange) { @@ -226,9 +226,9 @@ public Mono> uploadProfilePhoto(@RequestPart("file") Mono< @Override public Mono> uploadProfilePhotoById(@PathVariable String orgId, @PathVariable String userId, @RequestPart("file") Mono fileMono) { - return orgApiService.checkVisitorAdminRole(orgId).flatMap(__ -> userService.findById(userId)) - .zipWith(fileMono) - .flatMap(tuple -> userService.saveProfilePhoto(tuple.getT2(), tuple.getT1())) + return checkVisitorManagesMember(orgId, userId) + .then(userService.findById(userId)) + .flatMap(user -> fileMono.flatMap(file -> userService.saveProfilePhoto(file, user))) .map(ResponseView::success); } @@ -241,7 +241,7 @@ public Mono> deleteProfilePhoto() { @Override public Mono> deleteProfilePhotoById(@PathVariable String orgId, @PathVariable String userId) { - return orgApiService.checkVisitorAdminRole(orgId).flatMap(__ -> userService.findById(userId)) + return checkVisitorManagesMember(orgId, userId).then(userService.findById(userId)) .flatMap(user -> userService.deleteProfilePhoto(user) .map(ResponseView::success)); } @@ -323,4 +323,67 @@ public Mono> getUserDetail(@PathVariable("id") String userId) { return userApiService.getUserDetailById(userId) .map(ResponseView::success); } + + /** + * The admin route's own mutation: same field mapping as {@link #updateUser}, but answers the reduced + * {@link #managedUserView(User)} instead of {@link UserHomeApiService#buildUserProfileView}, so the target's + * session tokens and other workspaces never go back to the admin that renamed them. + */ + private Mono> updateManagedUser(String userId, UpdateUserRequest updateUserRequest) { + User updateUser = new User(); + if (StringUtils.isNotBlank(updateUserRequest.getName())) { + updateUser.setName(updateUserRequest.getName()); + updateUser.setHasSetNickname(true); + } + if (StringUtils.isNotBlank(updateUserRequest.getUiLanguage())) { + updateUser.setUiLanguage(updateUserRequest.getUiLanguage()); + } + return userService.update(userId, updateUser) + .map(UserController::managedUserView) + .map(ResponseView::success); + } + + /** + * The admin route's answer for a managed user: only the UI-relevant fields an admin needs to see the + * result of a rename or photo change. {@code UserProfileView} actually serializes 19 top-level keys, not its + * 17 fields (Jackson's duplicate aliases for {@code isAnonymous}/{@code isEnabled}, and {@code isOrgDev} + * serializing as {@code orgDev}) -- every key this method leaves + * unset stays at the builder's default, so the target's session tokens ({@code connections}), other + * workspaces ({@code orgAndRoles}), current org, status, IP and creation time never reach the caller. + */ + private static UserProfileView managedUserView(User user) { + return UserProfileView.builder() + .id(user.getId()) + .username(user.getName()) + .isAnonymous(user.isAnonymous()) + .uiLanguage(user.getUiLanguage()) + .avatarUrl(user.getAvatarUrl()) + .avatar(user.getAvatar()) + .hasSetNickname(user.isHasSetNickname()) + .isEnabled(org.apache.commons.lang3.BooleanUtils.isNotFalse(user.getIsEnabled())) + .build(); + } + + /** + * The visitor must be ADMIN or SUPER_ADMIN of {@code orgId} ({@link OrgApiService#checkVisitorAdminRole}), and + * {@code userId} must be a member of {@code orgId} -- else {@code NOT_AUTHORIZED}, the same answer for both, + * so "no such user" and "not in this workspace" cannot be told apart. A SUPER_ADMIN target can only be + * managed by itself or another SUPER_ADMIN of {@code orgId}, the same rank rule + * {@code OrgApiServiceImpl#checkSuperAdminRoleUnchanged} applies to a role change; otherwise + * {@code UNSUPPORTED_OPERATION}. Limits: check-then-act, not fixed here -- a role or membership change between + * this check and the caller's mutation is not caught. + */ + private Mono checkVisitorManagesMember(String orgId, String userId) { + return orgApiService.checkVisitorAdminRole(orgId) + .flatMap(visitor -> orgMemberService.getOrgMember(orgId, userId) + .switchIfEmpty(ofError(BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED")) + .flatMap(target -> { + boolean visitorIsTarget = visitor.getUserId().equals(userId); + boolean visitorIsSuperAdmin = visitor.getRole() == MemberRole.SUPER_ADMIN; + if (target.getRole() == MemberRole.SUPER_ADMIN && !visitorIsTarget && !visitorIsSuperAdmin) { + return ofError(BizError.UNSUPPORTED_OPERATION, "BAD_REQUEST"); + } + return Mono.just(target); + })); + } } diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImplEmailLinkTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImplEmailLinkTest.java new file mode 100644 index 0000000000..30195ea51b --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImplEmailLinkTest.java @@ -0,0 +1,239 @@ +package org.lowcoder.api.authentication.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.lowcoder.api.authentication.request.AuthRequestFactory; +import org.lowcoder.api.authentication.service.factory.AuthConfigFactory; +import org.lowcoder.api.authentication.util.JWTUtils; +import org.lowcoder.api.home.SessionUserService; +import org.lowcoder.api.usermanagement.InvitationApiService; +import org.lowcoder.api.usermanagement.OrgApiService; +import org.lowcoder.api.usermanagement.UserApiService; +import org.lowcoder.api.util.BusinessEventPublisher; +import org.lowcoder.domain.authentication.AuthenticationService; +import org.lowcoder.domain.authentication.context.AuthRequestContext; +import org.lowcoder.domain.authentication.context.FormAuthRequestContext; +import org.lowcoder.domain.group.service.GroupMemberService; +import org.lowcoder.domain.organization.model.MemberRole; +import org.lowcoder.domain.organization.model.OrgMember; +import org.lowcoder.domain.organization.service.OrgMemberService; +import org.lowcoder.domain.organization.service.OrganizationService; +import org.lowcoder.domain.user.model.AuthUser; +import org.lowcoder.domain.user.model.Connection; +import org.lowcoder.domain.user.model.User; +import org.lowcoder.domain.user.service.UserService; +import org.lowcoder.sdk.auth.AbstractAuthConfig; +import org.lowcoder.sdk.config.AuthProperties; +import org.lowcoder.sdk.config.CommonConfig; +import org.lowcoder.sdk.constants.AuthSourceConstants; +import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; +import org.lowcoder.sdk.util.CookieHelper; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** + * {@code AuthenticationApiServiceImpl#updateOrCreateUser}'s branch 2 -- an account + * found by e-mail address, not by the same source/subject connection -- must link ONLY when that is safe, + * never merely because the address matches. Mock style of {@link AuthenticationApiServiceImplMutationsTest}. + */ +@ExtendWith(MockitoExtension.class) +class AuthenticationApiServiceImplEmailLinkTest { + + private static final String ORG_ID = "org-1"; + private static final String OTHER_ORG_ID = "org-2"; + private static final String USER_ID = "user-1"; + private static final String UID = "uid-1"; + private static final String CONFIG_A = "cfg-a"; + private static final String SOURCE_GENERIC = "GENERIC"; + private static final String STUB_TYPE = "STUB"; + + @Mock private OrgApiService orgApiService; + @Mock private OrganizationService organizationService; + @Mock private AuthRequestFactory authRequestFactory; + @Mock private AuthenticationService authenticationService; + @Mock private UserService userService; + @Mock private InvitationApiService invitationApiService; + @Mock private BusinessEventPublisher businessEventPublisher; + @Mock private SessionUserService sessionUserService; + @Mock private CookieHelper cookieHelper; + @Mock private AuthConfigFactory authConfigFactory; + @Mock private UserApiService userApiService; + @Mock private OrgMemberService orgMemberService; + @Mock private JWTUtils jwtUtils; + @Mock private AuthProperties authProperties; + @Mock private GroupMemberService groupMemberService; + + private AuthenticationApiServiceImpl service; + + private static class StubAuthConfig extends AbstractAuthConfig { + StubAuthConfig(String id, String source, boolean enable, boolean enableRegister, String authType) { + super(id, source, source, enable, enableRegister, authType); + } + + @Override + public void merge(AbstractAuthConfig oldConfig) { + } + } + + @BeforeEach + void setUp() { + service = new AuthenticationApiServiceImpl(orgApiService, organizationService, authRequestFactory, + authenticationService, userService, invitationApiService, businessEventPublisher, sessionUserService, + cookieHelper, authConfigFactory, userApiService, orgMemberService, jwtUtils, authProperties, + new CommonConfig(), groupMemberService); + } + + private static AuthUser authUser(String source, String orgId) { + FormAuthRequestContext context = new FormAuthRequestContext("login", "pw", false, orgId); + context.setAuthConfig(new StubAuthConfig(CONFIG_A, source, true, true, STUB_TYPE)); + return AuthUser.builder().uid(UID).orgId(orgId).authContext(context).build(); + } + + private static OrgMember member(String orgId) { + return OrgMember.builder().orgId(orgId).userId(USER_ID).role(MemberRole.MEMBER).build(); + } + + private static Connection connection(String source) { + return Connection.builder().authId("auth-" + source).source(source).rawId("raw-" + source).build(); + } + + /** Resolves branch 2 (found by raw id, not by source+id): {@code findByAuthUserSourceAndRawId} empty, {@code findByAuthUserRawId} hits {@code found}. */ + private void resolvesByRawIdOnly(AuthUser authUser, User found) { + when(userService.findByAuthUserSourceAndRawId(authUser)).thenReturn(Mono.empty()); + when(userService.findByAuthUserRawId(authUser)).thenReturn(Mono.just(found)); + } + + private static void assertBizError(Throwable throwable, BizError expected) { + assertThat(throwable).isInstanceOf(BizException.class); + assertThat(((BizException) throwable).getError()).isEqualTo(expected); + } + + /** Case 1: a GENERIC sign-in whose claimed address resolves to an account that ALREADY has connections -> {@code ALREADY_BIND}, never linked. */ + @Test + void genericSource_accountFoundByAddressWithConnections_refusedAlreadyBind() { + User found = User.builder().id(USER_ID).connections(new HashSet<>(Set.of(connection("GOOGLE")))).build(); + AuthUser authUser = authUser(SOURCE_GENERIC, ORG_ID); + resolvesByRawIdOnly(authUser, found); + + StepVerifier.create(service.updateOrCreateUser(authUser, false, false)) + .expectErrorSatisfies(e -> assertBizError(e, BizError.ALREADY_BIND)) + .verify(); + + verify(userService, never()).addNewConnectionAndReturnUser(any(), any()); + verify(orgMemberService, never()).getRawOrgMemberships(any()); + System.out.println("[AuthenticationApiServiceImplEmailLinkTest] account with existing connections -> ALREADY_BIND, never linked"); + } + + /** Case 2: an EMAIL (form) sign-up whose typed address resolves to a provider-only account -> {@code USER_LOGIN_ID_EXIST}, never linked. */ + @Test + void emailSourceRegister_providerOnlyAccountFoundByAddress_refusedUserLoginIdExist() { + User found = User.builder().id(USER_ID).connections(new HashSet<>(Set.of(connection("GOOGLE")))).build(); + AuthUser authUser = authUser(AuthSourceConstants.EMAIL, ORG_ID); + resolvesByRawIdOnly(authUser, found); + + StepVerifier.create(service.updateOrCreateUser(authUser, false, false)) + .expectErrorSatisfies(e -> assertBizError(e, BizError.USER_LOGIN_ID_EXIST)) + .verify(); + + verify(userService, never()).addNewConnectionAndReturnUser(any(), any()); + assertThat(found.getPassword()).isNull(); + System.out.println("[AuthenticationApiServiceImplEmailLinkTest] EMAIL register against a provider-only account -> USER_LOGIN_ID_EXIST"); + } + + /** Case 3: GENERIC, a placeholder with no connections and an exclusive raw membership of the provider's own org -> linked. */ + @Test + void genericSource_placeholderExclusiveMemberOfProviderOrg_linked() { + User placeholder = User.builder().id(USER_ID).connections(new HashSet<>()).build(); + AuthUser authUser = authUser(SOURCE_GENERIC, ORG_ID); + resolvesByRawIdOnly(authUser, placeholder); + when(orgMemberService.getRawOrgMemberships(USER_ID)).thenReturn(Mono.just(List.of(member(ORG_ID)))); + when(userService.addNewConnectionAndReturnUser(USER_ID, authUser)).thenReturn(Mono.just(placeholder)); + + StepVerifier.create(service.updateOrCreateUser(authUser, false, false)).expectNext(placeholder).verifyComplete(); + + verify(userService).addNewConnectionAndReturnUser(USER_ID, authUser); + System.out.println("[AuthenticationApiServiceImplEmailLinkTest] placeholder, exclusive member of provider org -> linked"); + } + + /** Case 4: same placeholder, but its single raw membership is NOT the provider's org -> {@code ALREADY_BIND}. */ + @Test + void genericSource_placeholderMemberOfADifferentOrg_refusedAlreadyBind() { + User placeholder = User.builder().id(USER_ID).connections(new HashSet<>()).build(); + AuthUser authUser = authUser(SOURCE_GENERIC, ORG_ID); + resolvesByRawIdOnly(authUser, placeholder); + when(orgMemberService.getRawOrgMemberships(USER_ID)).thenReturn(Mono.just(List.of(member(OTHER_ORG_ID)))); + + StepVerifier.create(service.updateOrCreateUser(authUser, false, false)) + .expectErrorSatisfies(e -> assertBizError(e, BizError.ALREADY_BIND)) + .verify(); + + verify(userService, never()).addNewConnectionAndReturnUser(any(), any()); + System.out.println("[AuthenticationApiServiceImplEmailLinkTest] placeholder, not a member of the provider's org -> ALREADY_BIND"); + } + + /** + * Case 5: the cross-org SCIM-pollution scenario of plan section 3 -- the placeholder has TWO raw memberships + * (the provider's org, and one other an attacker admin pulled it into via {@code createSCIMUserAndAddToOrg}) -> + * {@code ALREADY_BIND}, not linked, since the membership is no longer exclusive. + */ + @Test + void genericSource_placeholderWithTwoRawMemberships_refusedAlreadyBindNotFooledByPollution() { + User placeholder = User.builder().id(USER_ID).connections(new HashSet<>()).build(); + AuthUser authUser = authUser(SOURCE_GENERIC, ORG_ID); + resolvesByRawIdOnly(authUser, placeholder); + when(orgMemberService.getRawOrgMemberships(USER_ID)).thenReturn(Mono.just(List.of(member(ORG_ID), member(OTHER_ORG_ID)))); + + StepVerifier.create(service.updateOrCreateUser(authUser, false, false)) + .expectErrorSatisfies(e -> assertBizError(e, BizError.ALREADY_BIND)) + .verify(); + + verify(userService, never()).addNewConnectionAndReturnUser(any(), any()); + System.out.println("[AuthenticationApiServiceImplEmailLinkTest] placeholder polluted with a second org membership -> ALREADY_BIND"); + } + + /** Case 6: EMAIL source against a placeholder (case (b) explicitly excludes EMAIL) -> {@code USER_LOGIN_ID_EXIST}. */ + @Test + void emailSource_placeholder_refusedUserLoginIdExist() { + User placeholder = User.builder().id(USER_ID).connections(new HashSet<>()).build(); + AuthUser authUser = authUser(AuthSourceConstants.EMAIL, ORG_ID); + resolvesByRawIdOnly(authUser, placeholder); + + StepVerifier.create(service.updateOrCreateUser(authUser, false, false)) + .expectErrorSatisfies(e -> assertBizError(e, BizError.USER_LOGIN_ID_EXIST)) + .verify(); + + verify(userService, never()).addNewConnectionAndReturnUser(any(), any()); + verify(orgMemberService, never()).getRawOrgMemberships(any()); + System.out.println("[AuthenticationApiServiceImplEmailLinkTest] EMAIL source against a placeholder -> USER_LOGIN_ID_EXIST, case (b) excludes EMAIL"); + } + + /** Case 7: {@code isSuperAdmin = true} links as before, regardless of connections or membership. */ + @Test + void isSuperAdmin_linksAsBefore_regardlessOfConnectionsOrMembership() { + User found = User.builder().id(USER_ID).connections(new HashSet<>(Set.of(connection("GOOGLE")))).build(); + AuthUser authUser = authUser(SOURCE_GENERIC, ORG_ID); + resolvesByRawIdOnly(authUser, found); + when(userService.addNewConnectionAndReturnUser(USER_ID, authUser)).thenReturn(Mono.just(found)); + + StepVerifier.create(service.updateOrCreateUser(authUser, false, true)).expectNext(found).verifyComplete(); + + verify(userService).addNewConnectionAndReturnUser(USER_ID, authUser); + verify(orgMemberService, never()).getRawOrgMemberships(any()); + System.out.println("[AuthenticationApiServiceImplEmailLinkTest] isSuperAdmin=true -> linked unconditionally"); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImplMutationsTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImplMutationsTest.java index 1235224146..431daf7b64 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImplMutationsTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/service/AuthenticationApiServiceImplMutationsTest.java @@ -699,19 +699,23 @@ void updateOrCreateUser_foundBySourceAndRawId_updatesTheConnection_andSaves() { System.out.println("[AuthenticationApiServiceImplMutationsTest] source+rawId hit -> connection updated and user saved"); } - /** Catches the cross-source link being lost: a user known only by raw id gets the new connection added. */ + /** + * Catches the cross-source link being lost: a user known only by raw id, with no connections of its own (a SCIM + * placeholder) and an exclusive raw membership of the provider's own org, gets the new connection added. + */ @Test - void updateOrCreateUser_foundOnlyByRawId_addsANewConnection() { + void updateOrCreateUser_foundOnlyByRawId_placeholderExclusiveMemberOfProviderOrg_addsANewConnection() { User user = User.builder().id(USER_ID).build(); AuthUser authUser = authUser(SOURCE_GOOGLE, UID, ORG_ID, CONFIG_A, true); when(userService.findByAuthUserSourceAndRawId(authUser)).thenReturn(Mono.empty()); when(userService.findByAuthUserRawId(authUser)).thenReturn(Mono.just(user)); + when(orgMemberService.getRawOrgMemberships(USER_ID)).thenReturn(Mono.just(List.of(member(MemberRole.MEMBER)))); when(userService.addNewConnectionAndReturnUser(USER_ID, authUser)).thenReturn(Mono.just(user)); StepVerifier.create(service.updateOrCreateUser(authUser, false, false)).expectNext(user).verifyComplete(); verify(userService, never()).saveUser(any()); - System.out.println("[AuthenticationApiServiceImplMutationsTest] rawId-only hit -> new connection added"); + System.out.println("[AuthenticationApiServiceImplMutationsTest] rawId-only hit, exclusive member of provider org -> new connection added"); } /** Catches link-existing mode searching for a user: it must attach the connection to the current visitor. */ diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/UserEndpointsContractTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/UserEndpointsContractTest.java index 845adf01de..d184bab016 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/UserEndpointsContractTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/UserEndpointsContractTest.java @@ -112,6 +112,8 @@ class UserEndpointsContractTest { static final String VISITOR_ID = VISITOR.getId(); static final OrgMember VISITOR_ORG_MEMBER = new OrgMember(UserManagementSamples.orgViewOrganization().getId(), VISITOR_ID, MemberRole.ADMIN, "UserEndpointsContractTest.state", 3_000_000_150L); + /** The path's user, a plain member of {@code ORG_ID}, for the admin routes' membership check. */ + static final OrgMember TARGET_MEMBER = new OrgMember(ORG_ID, USER_ID, MemberRole.MEMBER, "UserEndpointsContractTest.targetState", 3_000_000_151L); static final int PAGE_NUM = 2; static final int PAGE_SIZE = 1; static final long ORG_TOTAL = 3; @@ -147,6 +149,9 @@ void mocks() { Mockito.when(orgApiService.checkVisitorAdminRole(ORG_ID)).thenReturn(Mono.just(VISITOR_ORG_MEMBER)); Mockito.when(orgApiService.switchCurrentOrganizationTo(anyString(), eq(ORG_ID))).thenReturn(Mono.just(Boolean.TRUE)); Mockito.when(orgMemberService.tryAddOrgMember(eq(ORG_ID), anyString(), eq(MemberRole.MEMBER))).thenReturn(Mono.just(Boolean.TRUE)); + // The three admin-on-member routes also require USER_ID to be a member of + // ORG_ID (UserController#checkVisitorManagesMember); the happy-path tests below rely on this default. + Mockito.when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(TARGET_MEMBER)); } @AfterAll @@ -310,10 +315,87 @@ void update() { assertUpdate(UPDATE_SELF, VISITOR_ID); } - /** An admin updates another member: same body, same answer, for the path's user. */ + /** + * An admin updates another member with the same body, but the answer is the REDUCED + * {@code UserProfileView} ({@code UserController#managedUserView}), not the full profile {@code buildUserProfileView} + * builds for the self route -- the target's session tokens and other workspaces must never reach the admin. + */ @Test void updateById() { - assertUpdate(UPDATE_BY_ID, USER_ID, ORG_ID, USER_ID); + User updated = UserSamples.user(); + Mockito.when(userService.update(eq(USER_ID), any())).thenReturn(Mono.just(updated)); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, UPDATE_BY_ID, Map.of(), + EndpointContract.d1(UpdateUserRequest.class), ORG_ID, USER_ID); + EndpointContract.assertResponse(result, HttpStatus.OK, + EndpointContract.success(EndpointContract.fixture(UserProfileView.class, "Reduced"))); + Mockito.verifyNoInteractions(userHomeApiService); + ArgumentCaptor partial = ArgumentCaptor.forClass(User.class); + Mockito.verify(userService).update(eq(USER_ID), partial.capture()); + UpdateUserRequest expected = (UpdateUserRequest) PayloadSamples.of(UpdateUserRequest.class).value(); + assertThat(partial.getValue().getName()).isEqualTo(expected.getName()); + assertThat(partial.getValue().getUiLanguage()).isEqualTo(expected.getUiLanguage()); + assertThat(partial.getValue().isHasSetNickname()).isTrue(); + } + } + + /** The visitor is not ADMIN/SUPER_ADMIN of {@code orgId} -> {@code NOT_AUTHORIZED}, nothing read or written. */ + @Test + void updateById_visitorNotAdmin_denied() { + Mockito.when(orgApiService.checkVisitorAdminRole(ORG_ID)) + .thenReturn(Mono.error(new org.lowcoder.sdk.exception.BizException(BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED"))); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, UPDATE_BY_ID, Map.of(), + EndpointContract.d1(UpdateUserRequest.class), ORG_ID, USER_ID); + EndpointContract.assertBizError(result, BizError.NOT_AUTHORIZED, BizError.NOT_AUTHORIZED.name()); + Mockito.verify(userService, Mockito.never()).update(any(), any()); + Mockito.verifyNoInteractions(userHomeApiService); + } + } + + /** The {@code userId} is not a member of {@code orgId} -> the SAME {@code NOT_AUTHORIZED} answer, nothing read or written. */ + @Test + void updateById_targetNotAMember_denied() { + Mockito.when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.empty()); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, UPDATE_BY_ID, Map.of(), + EndpointContract.d1(UpdateUserRequest.class), ORG_ID, USER_ID); + EndpointContract.assertBizError(result, BizError.NOT_AUTHORIZED, BizError.NOT_AUTHORIZED.name()); + Mockito.verify(userService, Mockito.never()).update(any(), any()); + Mockito.verifyNoInteractions(userHomeApiService); + } + } + + /** The target is SUPER_ADMIN and the visitor is a plain ADMIN (not SUPER_ADMIN, not the target) -> {@code UNSUPPORTED_OPERATION}. */ + @Test + void updateById_targetSuperAdminVisitorAdmin_denied() { + Mockito.when(orgMemberService.getOrgMember(ORG_ID, USER_ID)) + .thenReturn(Mono.just(new OrgMember(ORG_ID, USER_ID, MemberRole.SUPER_ADMIN, "UserEndpointsContractTest.targetState", TARGET_MEMBER.getJoinTime()))); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, UPDATE_BY_ID, Map.of(), + EndpointContract.d1(UpdateUserRequest.class), ORG_ID, USER_ID); + EndpointContract.assertBizError(result, BizError.UNSUPPORTED_OPERATION, "BAD_REQUEST"); + Mockito.verify(userService, Mockito.never()).update(any(), any()); + Mockito.verifyNoInteractions(userHomeApiService); + } + } + + /** The target is SUPER_ADMIN and the visitor is ALSO SUPER_ADMIN of {@code orgId} -> allowed. */ + @Test + void updateById_targetSuperAdminVisitorSuperAdmin_allowed() { + Mockito.when(orgApiService.checkVisitorAdminRole(ORG_ID)).thenReturn(Mono.just( + new OrgMember(VISITOR_ORG_MEMBER.getOrgId(), VISITOR_ID, MemberRole.SUPER_ADMIN, "UserEndpointsContractTest.state", VISITOR_ORG_MEMBER.getJoinTime()))); + Mockito.when(orgMemberService.getOrgMember(ORG_ID, USER_ID)) + .thenReturn(Mono.just(new OrgMember(ORG_ID, USER_ID, MemberRole.SUPER_ADMIN, "UserEndpointsContractTest.targetState", TARGET_MEMBER.getJoinTime()))); + User updated = UserSamples.user(); + Mockito.when(userService.update(eq(USER_ID), any())).thenReturn(Mono.just(updated)); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, UPDATE_BY_ID, Map.of(), + EndpointContract.d1(UpdateUserRequest.class), ORG_ID, USER_ID); + EndpointContract.assertResponse(result, HttpStatus.OK, + EndpointContract.success(EndpointContract.fixture(UserProfileView.class, "Reduced"))); + Mockito.verify(userService).update(eq(USER_ID), any()); + } } /** NEW-136: a language-only body must leave the nickname flag unset in the partial, so the update does not write it. */ @@ -350,6 +432,55 @@ void uploadProfilePhotoById() { } } + /** + * The {@code userId} is not a member of {@code orgId} -> {@code NOT_AUTHORIZED}; the uploaded part is never + * saved, proving the sequencing fix runs the membership check before {@code fileMono} + * is ever subscribed. {@code userService.findById} IS still invoked as a plain Java call while the chain is + * assembled (the same eager-assembly behaviour {@code .then(mono)} has throughout this codebase); it is stubbed + * here only so that call does not NPE -- the resulting {@code Mono} is never subscribed because + * {@code checkVisitorManagesMember} errors before it, so no real lookup happens and nothing is saved. + */ + @Test + void uploadProfilePhotoById_targetNotAMember_denied() { + Mockito.when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.empty()); + Mockito.when(userService.findById(USER_ID)).thenReturn(Mono.just(UserSamples.user())); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchangeMultipart(client, "uploadProfilePhotoById", Map.of(), photo(), ORG_ID, USER_ID); + EndpointContract.assertBizError(result, BizError.NOT_AUTHORIZED, BizError.NOT_AUTHORIZED.name()); + Mockito.verify(userService, Mockito.never()).saveProfilePhoto(any(), any()); + } + } + + /** The target is SUPER_ADMIN and the visitor is a plain ADMIN -> {@code UNSUPPORTED_OPERATION}, nothing saved. */ + @Test + void uploadProfilePhotoById_targetSuperAdminVisitorAdmin_denied() { + Mockito.when(orgMemberService.getOrgMember(ORG_ID, USER_ID)) + .thenReturn(Mono.just(new OrgMember(ORG_ID, USER_ID, MemberRole.SUPER_ADMIN, "UserEndpointsContractTest.targetState", TARGET_MEMBER.getJoinTime()))); + Mockito.when(userService.findById(USER_ID)).thenReturn(Mono.just(UserSamples.user())); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchangeMultipart(client, "uploadProfilePhotoById", Map.of(), photo(), ORG_ID, USER_ID); + EndpointContract.assertBizError(result, BizError.UNSUPPORTED_OPERATION, "BAD_REQUEST"); + Mockito.verify(userService, Mockito.never()).saveProfilePhoto(any(), any()); + } + } + + /** The visitor is SUPER_ADMIN of {@code orgId} replacing another SUPER_ADMIN's photo -> allowed. */ + @Test + void uploadProfilePhotoById_targetSuperAdminVisitorSuperAdmin_allowed() { + Mockito.when(orgApiService.checkVisitorAdminRole(ORG_ID)).thenReturn(Mono.just( + new OrgMember(VISITOR_ORG_MEMBER.getOrgId(), VISITOR_ID, MemberRole.SUPER_ADMIN, "UserEndpointsContractTest.state", VISITOR_ORG_MEMBER.getJoinTime()))); + Mockito.when(orgMemberService.getOrgMember(ORG_ID, USER_ID)) + .thenReturn(Mono.just(new OrgMember(ORG_ID, USER_ID, MemberRole.SUPER_ADMIN, "UserEndpointsContractTest.targetState", TARGET_MEMBER.getJoinTime()))); + User member = UserSamples.user(); + Mockito.when(userService.findById(USER_ID)).thenReturn(Mono.just(member)); + AtomicReference received = stubPhotoUpload(member); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchangeMultipart(client, "uploadProfilePhotoById", Map.of(), photo(), ORG_ID, USER_ID); + EndpointContract.assertResponse(result, HttpStatus.OK, EndpointContract.success(TRUE)); + assertPhotoPart(member, received); + } + } + /** * {@code deleteProfilePhoto} maps the service's {@code Mono} to a {@code ResponseView}, which never happens: * the answer is HTTP 200 with a JSON {@code Content-Type} and an empty body, not an envelope (O21). @@ -377,6 +508,54 @@ void deleteProfilePhotoById() { } } + /** + * The {@code userId} is not a member of {@code orgId} -> {@code NOT_AUTHORIZED}, nothing deleted. + * {@code userService.findById} IS still invoked as a plain Java call while the chain is assembled (the same + * eager-assembly behaviour {@code .then(mono)} has throughout this codebase); it is stubbed here only so that + * call does not NPE -- the resulting {@code Mono} is never subscribed because {@code checkVisitorManagesMember} + * errors before it, so no real lookup happens and nothing is deleted. + */ + @Test + void deleteProfilePhotoById_targetNotAMember_denied() { + Mockito.when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.empty()); + Mockito.when(userService.findById(USER_ID)).thenReturn(Mono.just(UserSamples.user())); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "deleteProfilePhotoById", Map.of(), null, ORG_ID, USER_ID); + EndpointContract.assertBizError(result, BizError.NOT_AUTHORIZED, BizError.NOT_AUTHORIZED.name()); + Mockito.verify(userService, Mockito.never()).deleteProfilePhoto(any()); + } + } + + /** The target is SUPER_ADMIN and the visitor is a plain ADMIN -> {@code UNSUPPORTED_OPERATION}, nothing deleted. */ + @Test + void deleteProfilePhotoById_targetSuperAdminVisitorAdmin_denied() { + Mockito.when(orgMemberService.getOrgMember(ORG_ID, USER_ID)) + .thenReturn(Mono.just(new OrgMember(ORG_ID, USER_ID, MemberRole.SUPER_ADMIN, "UserEndpointsContractTest.targetState", TARGET_MEMBER.getJoinTime()))); + Mockito.when(userService.findById(USER_ID)).thenReturn(Mono.just(UserSamples.user())); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "deleteProfilePhotoById", Map.of(), null, ORG_ID, USER_ID); + EndpointContract.assertBizError(result, BizError.UNSUPPORTED_OPERATION, "BAD_REQUEST"); + Mockito.verify(userService, Mockito.never()).deleteProfilePhoto(any()); + } + } + + /** The visitor is SUPER_ADMIN of {@code orgId} deleting another SUPER_ADMIN's photo -> allowed. */ + @Test + void deleteProfilePhotoById_targetSuperAdminVisitorSuperAdmin_allowed() { + Mockito.when(orgApiService.checkVisitorAdminRole(ORG_ID)).thenReturn(Mono.just( + new OrgMember(VISITOR_ORG_MEMBER.getOrgId(), VISITOR_ID, MemberRole.SUPER_ADMIN, "UserEndpointsContractTest.state", VISITOR_ORG_MEMBER.getJoinTime()))); + Mockito.when(orgMemberService.getOrgMember(ORG_ID, USER_ID)) + .thenReturn(Mono.just(new OrgMember(ORG_ID, USER_ID, MemberRole.SUPER_ADMIN, "UserEndpointsContractTest.targetState", TARGET_MEMBER.getJoinTime()))); + User member = UserSamples.user(); + Mockito.when(userService.findById(USER_ID)).thenReturn(Mono.just(member)); + Mockito.when(userService.deleteProfilePhoto(member)).thenReturn(Mono.empty()); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "deleteProfilePhotoById", Map.of(), null, ORG_ID, USER_ID); + EndpointContract.assertEmptyResponse(result, HttpStatus.OK, MediaType.APPLICATION_JSON); + Mockito.verify(userService).deleteProfilePhoto(member); + } + } + /** The visitor's avatar, written by the service as the asset service writes it: the image bytes, not JSON. */ @Test void getProfilePhoto() { diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderApiServiceImplTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderApiServiceImplTest.java index cfe839dea0..df2dd6c108 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderApiServiceImplTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderApiServiceImplTest.java @@ -504,6 +504,95 @@ void update_toASiblingsName_isRejected_andNotWrittenWithoutPermission() { assertThat(written).as("a member who is not the creator writes nothing").isFalse(); } + // ---------------------------------------------------- cross-org manage + + /** + * An ADMIN of the visitor's CURRENT org on ANOTHER org's folder -> {@code + * FOLDER_OPERATE_NO_PERMISSION} for all four operations {@code checkManagePermissionInCurrentOrg} guards, with + * nothing written -- proved with the file's subscription-flag pattern, not {@code verify(..., never())}, since + * each of {@code update}'s {@code updateById}, {@code updatePermission}'s {@code updateRoleById} and {@code + * removePermission}'s {@code removeById} is the argument of a {@code .then(mono)} call and is INVOKED while the + * chain is assembled even when the preceding check fails. + */ + @Test + void crossOrgAdmin_update_grant_updatePermission_removePermission_refusedFolderOperateNoPermission() { + signedInAs(MemberRole.ADMIN); + when(folderService.findById("foreign")).thenReturn(Mono.just(folder("foreign", OTHER_ORG, null, "foreign", OTHER_USER))); + + AtomicBoolean updateWritten = new AtomicBoolean(); + when(folderService.updateById(eq("foreign"), any(Folder.class))).thenReturn(flagged(updateWritten, true)); + expectBizError(service.update(request("foreign", null, "renamed")), BizError.FOLDER_OPERATE_NO_PERMISSION); + assertThat(updateWritten).as("cross-org admin update must not write anything").isFalse(); + + AtomicBoolean granted = new AtomicBoolean(); + when(permissionService.insertBatchPermission(any(), anyString(), any(), any(), any())).thenReturn(flaggedVoid(granted)); + expectBizError(service.grantPermission("foreign", Set.of("u2"), Set.of(), ResourceRole.VIEWER), BizError.FOLDER_OPERATE_NO_PERMISSION); + verify(permissionService, never()).insertBatchPermission(any(), anyString(), any(), any(), any()); + assertThat(granted).as("cross-org admin grant must not insert anything").isFalse(); + + when(permissionService.getById("p-foreign-folder")).thenReturn(Mono.just(ResourcePermission.builder().id("p-foreign-folder").resourceId("foreign").build())); + AtomicBoolean updatedRole = new AtomicBoolean(); + when(permissionService.updateRoleById(anyString(), any())).thenReturn(flagged(updatedRole, true)); + expectBizError(service.updatePermission("foreign", "p-foreign-folder", ResourceRole.EDITOR), BizError.FOLDER_OPERATE_NO_PERMISSION); + assertThat(updatedRole).as("cross-org admin updatePermission must not write anything").isFalse(); + + AtomicBoolean removed = new AtomicBoolean(); + when(permissionService.removeById(anyString())).thenReturn(flagged(removed, true)); + expectBizError(service.removePermission("foreign", "p-foreign-folder"), BizError.FOLDER_OPERATE_NO_PERMISSION); + assertThat(removed).as("cross-org admin removePermission must not remove anything").isFalse(); + + System.out.println("[FolderApiServiceImplTest] cross-org admin refused on update/grant/updatePermission/removePermission, nothing written"); + } + + /** The folder's own creator, whose CURRENT org is a different one now, is refused the same way an admin is. */ + @Test + void crossOrgCreator_update_refusedFolderOperateNoPermission() { + when(folderService.findById("foreign")).thenReturn(Mono.just(folder("foreign", OTHER_ORG, null, "foreign", VISITOR))); + AtomicBoolean written = new AtomicBoolean(); + when(folderService.updateById(eq("foreign"), any(Folder.class))).thenReturn(flagged(written, true)); + + expectBizError(service.update(request("foreign", null, "renamed")), BizError.FOLDER_OPERATE_NO_PERMISSION); + + assertThat(written).as("the creator's own org no longer matches the folder's -> refused, nothing written").isFalse(); + } + + /** + * An unknown folder id for update/grantPermission/updatePermission/removePermission answers {@code + * FOLDER_NOT_EXIST} -- a NEW answer for these four operations (distinct from {@code delete}'s own pinned + * unknown-id behaviour, unaffected: {@link #delete_unknownFolder_asANonAdmin_completesEmpty_withoutDeleting} + * and {@link #delete_unknownFolderInTheTree_asAnAdmin_failsWithFolderNotExist} above still pass unchanged). + */ + @Test + void unknownFolderId_update_grant_updatePermission_removePermission_answerFolderNotExist() { + signedInAs(MemberRole.ADMIN); + when(folderService.findById("ghost")).thenReturn(Mono.empty()); + // Each mutation call below is the argument of a .then(mono) call and so is INVOKED while its chain is + // assembled, even though checkManagePermissionInCurrentOrg errors before any of them is ever subscribed + // (the file's own eager-.then() gotcha, documented at the top of this class) -- stub them so the eager + // Java call does not NPE on an unstubbed mock. + when(folderService.updateById(eq("ghost"), any(Folder.class))).thenReturn(Mono.just(true)); + when(permissionService.getById(anyString())).thenReturn(Mono.just(ResourcePermission.builder().id("p").resourceId("ghost").build())); + when(permissionService.updateRoleById(anyString(), any())).thenReturn(Mono.just(true)); + when(permissionService.removeById(anyString())).thenReturn(Mono.just(true)); + + expectBizError(service.update(request("ghost", null, "renamed")), BizError.FOLDER_NOT_EXIST); + expectBizError(service.grantPermission("ghost", Set.of("u2"), Set.of(), ResourceRole.VIEWER), BizError.FOLDER_NOT_EXIST); + expectBizError(service.updatePermission("ghost", "p", ResourceRole.VIEWER), BizError.FOLDER_NOT_EXIST); + expectBizError(service.removePermission("ghost", "p"), BizError.FOLDER_NOT_EXIST); + } + + /** A non-admin, non-creator member of the SAME org as the folder is still refused -- the pre-existing rule, unaffected. */ + @Test + void sameOrgNonAdminNonCreator_update_refusedFolderOperateNoPermission() { + when(folderService.findById("f1")).thenReturn(Mono.just(folder("f1", ORG, null, "f1", OTHER_USER))); + AtomicBoolean written = new AtomicBoolean(); + when(folderService.updateById(eq("f1"), any(Folder.class))).thenReturn(flagged(written, true)); + + expectBizError(service.update(request("f1", null, "renamed")), BizError.FOLDER_OPERATE_NO_PERMISSION); + + assertThat(written).isFalse(); + } + // ------------------------------------------------------------- move/bundle private Mono doMove(boolean bundle, String id, String target) { @@ -767,6 +856,10 @@ void grantPermission_requiresManagePermissionAndAnExistingFolder() { @Test void updateAndRemovePermission_rejectUnknownAndForeignPermissionIds_beforeMutating() { signedInAs(MemberRole.ADMIN); + // checkManagePermissionInCurrentOrg looks the folder up for every caller, admin + // included (unlike the old checkManagePermission, which never called findById for an admin) -- stub it so + // the admin path still succeeds past the new lookup. + when(folderService.findById("f1")).thenReturn(Mono.just(folder("f1", ORG, null, "f1", OTHER_USER))); AtomicBoolean updated = new AtomicBoolean(); AtomicBoolean removed = new AtomicBoolean(); when(permissionService.updateRoleById(anyString(), any())).thenReturn(flagged(updated, true)); diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/InvitationAndUserApiServiceTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/InvitationAndUserApiServiceTest.java index 3d2014cc4f..ec519b159b 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/InvitationAndUserApiServiceTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/InvitationAndUserApiServiceTest.java @@ -463,6 +463,10 @@ static Stream gateRows() { void userOperation_requiresAnAdminOfTheVisitorsOrgAndATargetInThatOrg(UserOperation operation, MemberRole role, boolean targetInOrg, boolean allowed) { when(sessionUserService.getVisitorOrgMemberCache()).thenReturn(Mono.just(new OrgMember(ORG_ID, VISITOR_ID, role, "current", 0L))); + // resetPassword's checkResetTargetBelowSuperAdmin reads the visitor id first + // (to detect a self-reset), whatever the visitor's role -- stubbed here even for the GET_DETAIL rows, + // which never call it, since the row is parameterized across both operations. + lenient().when(sessionUserService.getVisitorId()).thenReturn(Mono.just(VISITOR_ID)); lenient().when(orgMemberService.getOrgMember(ORG_ID, TARGET_ID)).thenReturn( targetInOrg ? Mono.just(new OrgMember(ORG_ID, TARGET_ID, MemberRole.MEMBER, "normal", 0L)) : Mono.empty()); User target = user(TARGET_ID, "Target"); @@ -477,7 +481,11 @@ void userOperation_requiresAnAdminOfTheVisitorsOrgAndATargetInThatOrg(UserOperat if (allowed) { Object expected = operation == UserOperation.GET_DETAIL ? detail : "new-password"; StepVerifier.create(result.map(value -> (Object) value)).expectNext(expected).verifyComplete(); - assertThat(events).isEqualTo(operation == UserOperation.GET_DETAIL ? List.of("findById", "detail") : List.of("reset")); + // resetPassword's new checkResetTargetBelowSuperAdmin also calls + // userService.findById(userId) (to read the superAdmin flag) before userService.resetPassword, reusing + // this test's existing logged("findById", target) stub -- so the allowed case now logs "findById" too. + assertThat(events).isEqualTo(operation == UserOperation.GET_DETAIL + ? List.of("findById", "detail") : List.of("findById", "reset")); } else { StepVerifier.create(result) .expectErrorSatisfies(error -> assertBizError(error, BizError.UNSUPPORTED_OPERATION, "BAD_REQUEST")) diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetPasswordTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetPasswordTest.java new file mode 100644 index 0000000000..cd3a8628b7 --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetPasswordTest.java @@ -0,0 +1,209 @@ +package org.lowcoder.api.usermanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lowcoder.api.home.SessionUserService; +import org.lowcoder.domain.organization.model.MemberRole; +import org.lowcoder.domain.organization.model.OrgMember; +import org.lowcoder.domain.organization.service.OrgMemberService; +import org.lowcoder.domain.user.model.User; +import org.lowcoder.domain.user.repository.UserRepository; +import org.lowcoder.domain.user.service.UserService; +import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; + +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** + * {@code UserApiServiceImpl#resetPassword} must refuse to reset a SUPER_ADMIN (by role or + * by the account-wide {@code superAdmin} flag), unless the visitor is resetting their own password. + * + *

{@code resetPassword}'s chain is {@code checkAdminPermissionAndUserBelongsToCurrentOrg(userId) + * .then(checkResetTargetBelowSuperAdmin(userId)).then(userService.resetPassword(userId))}: the last {@code .then}'s + * argument, {@code userService.resetPassword(userId)}, is a Java method call evaluated while the chain is + * ASSEMBLED, even when an earlier step fails and the resulting {@code Mono} is never subscribed (the same pattern + * documented in {@code OrgApiServiceImplTest} for {@code updateRoleForMember}/{@code removeUserFromOrg}, and in + * {@code FolderApiServiceImplTest} as {@code flagged}/{@code flaggedVoid}). So "nothing was reset" is asserted with + * a subscription flag, never {@code verify(..., never()).resetPassword(...)}. + */ +class UserApiServiceImplResetPasswordTest { + + private static final String ORG_ID = "org-1"; + private static final String VISITOR_ID = "visitor-1"; + private static final String TARGET_ID = "target-1"; + private static final String NEW_PASSWORD = "UserApiServiceImplResetPasswordTest.newPassword"; + + private SessionUserService sessionUserService; + private OrgMemberService orgMemberService; + private UserService userService; + private UserApiServiceImpl service; + + @BeforeEach + void setUp() { + sessionUserService = mock(SessionUserService.class); + orgMemberService = mock(OrgMemberService.class); + userService = mock(UserService.class); + service = new UserApiServiceImpl(sessionUserService, orgMemberService, userService, mock(UserRepository.class)); + } + + private void visitorIs(String visitorId, MemberRole visitorRole) { + when(sessionUserService.getVisitorId()).thenReturn(Mono.just(visitorId)); + when(sessionUserService.getVisitorOrgMemberCache()) + .thenReturn(Mono.just(new OrgMember(ORG_ID, visitorId, visitorRole, "visitor-state", 0L))); + } + + private void targetIs(MemberRole targetRole, boolean superAdminFlag) { + when(orgMemberService.getOrgMember(ORG_ID, TARGET_ID)) + .thenReturn(Mono.just(new OrgMember(ORG_ID, TARGET_ID, targetRole, "target-state", 0L))); + User target = User.builder().id(TARGET_ID).superAdmin(superAdminFlag).build(); + when(userService.findById(TARGET_ID)).thenReturn(Mono.just(target)); + } + + private static Mono flagged(AtomicBoolean subscribed, T value) { + return Mono.defer(() -> { + subscribed.set(true); + return Mono.justOrEmpty(value); + }); + } + + private static void assertUnsupportedOperation(Mono result) { + StepVerifier.create(result) + .expectErrorSatisfies(throwable -> { + assertThat(throwable).isInstanceOf(BizException.class); + assertThat(((BizException) throwable).getError()).isEqualTo(BizError.UNSUPPORTED_OPERATION); + assertThat(((BizException) throwable).getMessageKey()).isEqualTo("BAD_REQUEST"); + }) + .verify(); + } + + /** Target SUPER_ADMIN role, ADMIN-role visitor -> refused, nothing reset. */ + @Test + void targetSuperAdminRole_adminVisitor_refusedD40() { + visitorIs(VISITOR_ID, MemberRole.ADMIN); + targetIs(MemberRole.SUPER_ADMIN, false); + AtomicBoolean reset = new AtomicBoolean(); + when(userService.resetPassword(TARGET_ID)).thenReturn(flagged(reset, NEW_PASSWORD)); + + assertUnsupportedOperation(service.resetPassword(TARGET_ID)); + + assertThat(reset).as("userService.resetPassword must never be subscribed").isFalse(); + } + + /** Target ADMIN role but the account-wide superAdmin flag is set, ADMIN-role visitor -> refused, nothing reset. */ + @Test + void targetSuperAdminFlagRoleAdmin_adminVisitor_refusedD40() { + visitorIs(VISITOR_ID, MemberRole.ADMIN); + targetIs(MemberRole.ADMIN, true); + AtomicBoolean reset = new AtomicBoolean(); + when(userService.resetPassword(TARGET_ID)).thenReturn(flagged(reset, NEW_PASSWORD)); + + assertUnsupportedOperation(service.resetPassword(TARGET_ID)); + + assertThat(reset).as("userService.resetPassword must never be subscribed").isFalse(); + } + + /** + * The same two protected-target denials, but with a SUPER_ADMIN-role VISITOR: the refusal must not depend on + * the visitor's own role, only on the target's role/flag and on self-identity. An implementation that wrongly + * exempts every SUPER_ADMIN-role visitor from the check would pass the two tests above but fail these. + */ + @Test + void targetSuperAdminRole_superAdminVisitor_nonSelf_refusedD40() { + visitorIs(VISITOR_ID, MemberRole.SUPER_ADMIN); + targetIs(MemberRole.SUPER_ADMIN, false); + AtomicBoolean reset = new AtomicBoolean(); + when(userService.resetPassword(TARGET_ID)).thenReturn(flagged(reset, NEW_PASSWORD)); + + assertUnsupportedOperation(service.resetPassword(TARGET_ID)); + + assertThat(reset).isFalse(); + } + + @Test + void targetSuperAdminFlagRoleAdmin_superAdminVisitor_nonSelf_refusedD40() { + visitorIs(VISITOR_ID, MemberRole.SUPER_ADMIN); + targetIs(MemberRole.ADMIN, true); + AtomicBoolean reset = new AtomicBoolean(); + when(userService.resetPassword(TARGET_ID)).thenReturn(flagged(reset, NEW_PASSWORD)); + + assertUnsupportedOperation(service.resetPassword(TARGET_ID)); + + assertThat(reset).isFalse(); + } + + /** A plain MEMBER target, superAdmin flag false -> reset (unaffected, the baseline allowed case). */ + @Test + void targetMemberRole_notSuperAdminFlag_resetD40() { + visitorIs(VISITOR_ID, MemberRole.ADMIN); + targetIs(MemberRole.MEMBER, false); + when(userService.resetPassword(TARGET_ID)).thenReturn(Mono.just(NEW_PASSWORD)); + + StepVerifier.create(service.resetPassword(TARGET_ID)).expectNext(NEW_PASSWORD).verifyComplete(); + } + + /** + * An ADMIN target, superAdmin flag false, is still resettable -- section 3's rule refuses only a SUPER_ADMIN + * role or a true superAdmin flag. Required so an implementation that wrongly blocks EVERY ADMIN target would + * fail here while still passing every other planned case. + */ + @Test + void targetAdminRole_notSuperAdminFlag_resetD40() { + visitorIs(VISITOR_ID, MemberRole.ADMIN); + targetIs(MemberRole.ADMIN, false); + when(userService.resetPassword(TARGET_ID)).thenReturn(Mono.just(NEW_PASSWORD)); + + StepVerifier.create(service.resetPassword(TARGET_ID)).expectNext(NEW_PASSWORD).verifyComplete(); + } + + /** + * The visitor resets ITSELF, visitor/target role ADMIN with superAdmin=true -> allowed. Matches + * {@link #targetSuperAdminFlagRoleAdmin_adminVisitor_refusedD40} in every respect except that {@code userId} now + * equals the visitor's own id, isolating the self-exception precisely. + */ + @Test + void selfReset_adminRoleWithSuperAdminFlag_allowedD40() { + visitorIs(VISITOR_ID, MemberRole.ADMIN); + // checkAdminPermissionAndUserBelongsToCurrentOrg (unchanged by this phase) still looks up the visitor's own + // membership of its current org, self-reset included -- the visitor is necessarily a member of it. + when(orgMemberService.getOrgMember(ORG_ID, VISITOR_ID)) + .thenReturn(Mono.just(new OrgMember(ORG_ID, VISITOR_ID, MemberRole.ADMIN, "visitor-state", 0L))); + // checkResetTargetBelowSuperAdmin's self path returns before reading the target's membership or user + // record a SECOND time, so no additional stub for them is needed or expected to be consulted. + when(userService.resetPassword(VISITOR_ID)).thenReturn(Mono.just(NEW_PASSWORD)); + + StepVerifier.create(service.resetPassword(VISITOR_ID)).expectNext(NEW_PASSWORD).verifyComplete(); + } + + /** Visitor not an admin -> unchanged answer (the existing, unaffected check runs first). */ + @Test + void visitorNotAnAdmin_refusedUnchangedD40() { + visitorIs(VISITOR_ID, MemberRole.MEMBER); + AtomicBoolean reset = new AtomicBoolean(); + when(userService.resetPassword(eq(TARGET_ID))).thenReturn(flagged(reset, NEW_PASSWORD)); + + assertUnsupportedOperation(service.resetPassword(TARGET_ID)); + + assertThat(reset).isFalse(); + } + + /** Target not a member of the visitor's current org -> unchanged answer (the existing, unaffected check runs first). */ + @Test + void targetNotAMember_refusedUnchangedD40() { + visitorIs(VISITOR_ID, MemberRole.ADMIN); + when(orgMemberService.getOrgMember(ORG_ID, TARGET_ID)).thenReturn(Mono.empty()); + AtomicBoolean reset = new AtomicBoolean(); + when(userService.resetPassword(eq(TARGET_ID))).thenReturn(flagged(reset, NEW_PASSWORD)); + + assertUnsupportedOperation(service.resetPassword(TARGET_ID)); + + assertThat(reset).isFalse(); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/organization/OrgMemberServiceImplEnterpriseEnrolmentPinMongoTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/organization/OrgMemberServiceImplEnterpriseEnrolmentPinMongoTest.java index 83c25cf40e..f21e32c93e 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/organization/OrgMemberServiceImplEnterpriseEnrolmentPinMongoTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/organization/OrgMemberServiceImplEnterpriseEnrolmentPinMongoTest.java @@ -105,6 +105,32 @@ void aMemberOfTheEnterpriseOrgIsAnsweredWithoutEnrollingAgainBF131() { assertThat(rows(ORG_MEMBER, enterpriseOrg, user)).hasSize(1); } + /** + * {@code getRawOrgMemberships} must answer EVERY raw membership row, even in + * ENTERPRISE mode with an {@code enterpriseOrgId} configured, where {@code countAllActiveOrgs} collapses + * multiple real memberships down to one (BF-131's own collapsing, exercised above) -- the exact gap this new + * method exists to close for the branch-2 exclusivity check. + */ + @Test + void getRawOrgMembershipsAnswersEveryRowEvenWhenCountAllActiveOrgsCollapsesThemInEnterpriseMode() { + String enterpriseOrg = createActiveOrg(); + String otherOrg = createActiveOrg(); + String user = newId(); + orgMemberService.addMember(enterpriseOrg, user, MemberRole.ADMIN).block(TIMEOUT); + orgMemberService.addMember(otherOrg, user, MemberRole.ADMIN).block(TIMEOUT); + enterpriseMode(enterpriseOrg); + + Long collapsedCount = orgMemberService.countAllActiveOrgs(user).block(TIMEOUT); + List rawOrgIds = orgMemberService.getRawOrgMemberships(user).block(TIMEOUT) + .stream().map(OrgMember::getOrgId).toList(); + + System.out.println("[OrgMemberServiceImplEnterpriseEnrolmentPinMongoTest] collapsed count=" + collapsedCount + + " raw memberships=" + rawOrgIds); + assertThat(collapsedCount).as("countAllActiveOrgs collapses to 1 in enterprise mode").isEqualTo(1L); + assertThat(rawOrgIds).as("getRawOrgMemberships must not be fooled by the enterprise-mode collapsing") + .containsExactlyInAnyOrder(enterpriseOrg, otherOrg); + } + private void enterpriseMode(String enterpriseOrgId) { commonConfig.getWorkspace().setMode(WorkspaceMode.ENTERPRISE); commonConfig.getWorkspace().setEnterpriseOrgId(enterpriseOrgId); diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.Reduced.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.Reduced.json new file mode 100644 index 0000000000..207c348faa --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.Reduced.json @@ -0,0 +1 @@ +{"id":"User.id","orgAndRoles":null,"currentOrgId":null,"username":"User.name","connections":null,"uiLanguage":"User.uiLanguage","avatar":"User.avatar","avatarUrl":"","hasPassword":false,"hasSetNickname":true,"hasShownNewUserGuidance":false,"userStatus":null,"createdTimeMs":0,"ip":null,"enabled":false,"anonymous":true,"orgDev":false,"isAnonymous":true,"isEnabled":false} \ No newline at end of file From 731662a8510e574f1cc5e40adb13d20af6361f23 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Mon, 23 Nov 2026 09:57:28 +0100 Subject: [PATCH 02/20] test: add an e2e scenario proving two chat sessions exchange messages in the same room S18 chat controller only had connectivity coverage until now. This adds the complementary happy-path case to the existing cross-workspace isolation test: two independent sessions viewing the same published app each share a value through the chat controller and must receive the other's, with both coexisting afterward. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/README.md | 4 +- e2e/tests/components/chat.spec.ts | 70 ++++++++++++++++++++++++++++++- 2 files changed, 71 insertions(+), 3 deletions(-) diff --git a/e2e/README.md b/e2e/README.md index 18bbc52091..7151df8ee1 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -325,7 +325,7 @@ also carry `@superadmin` need both variables), `@superadmin` 5 (the four SEC-R16 | modules/module-editor-host.spec.ts | M3: host built in the editor, D-3 retry and handler retry | @slow | 1 | | modules/module-helpers.spec.ts | unit tests of `src/modules/moduleScenario.ts` | none | 6 | -### components (101 default, 214 with S1 and the quarantined one) +### components (102 default, 215 with S1 and the quarantined one) | File | Proves | Tags | Tests | |---|---|---|---| @@ -342,7 +342,7 @@ also carry `@superadmin` need both variables), `@superadmin` 5 (the four SEC-R16 | components/media.spec.ts | S12 image, carousel, avatarGroup, comment, card, audio, video, fileViewer | none | 8 | | components/lists.spec.ts | S13 listView and grid rows | none | 5 | | components/timer.spec.ts | S14 display runs, stops after Pause, `pause` event (CD-3 limits it) | none | 1 | -| components/chat.spec.ts | S17 AI Chat, S18 chat controller, S20 chat box | none | 7 | +| components/chat.spec.ts | S17 AI Chat, S18 chat controller (two viewers exchange messages in the same room), S20 chat box | none | 8 | | components/iframe.spec.ts | S18 `url` decides `src` | none | 1 | | components/npm-components.spec.ts | S15 npm components render; calendar with a pinned clock; barChart bound to a query (annotation CD-5) | @npm @slow | 26 | | components/npm-plugins.spec.ts | S16/S19 npm plugin and template listed, kept after reload | @npm | 3 | diff --git a/e2e/tests/components/chat.spec.ts b/e2e/tests/components/chat.spec.ts index ccd229f872..7d94ae4402 100644 --- a/e2e/tests/components/chat.spec.ts +++ b/e2e/tests/components/chat.spec.ts @@ -1,10 +1,12 @@ import type { Page } from "@playwright/test"; -import { createApp, publishApp } from "../../src/api/client"; +import { createApp, publishApp, setPublicToAll } from "../../src/api/client"; import { NEGATIVE_EVENT_WINDOW_MS } from "../../src/constants"; import { appDsl, + button, component, eventHandler, + executeComp, jsQuery, recordedHookOf, setTempState, @@ -142,6 +144,72 @@ test.describe("S18 chat controller", () => { "the network guard blocked no WebSocket", ).toEqual([]); }); + + const SEND_A_TEST_ID = "e2e-chat-send-a"; + const SEND_B_TEST_ID = "e2e-chat-send-b"; + const SHARED_TEST_ID = "e2e-chat-shared"; + const READY_TEST_ID = "e2e-chat-ready"; + const MESSAGE_FROM_A = "hello from viewer A"; + const MESSAGE_FROM_B = "hello from viewer B"; + const EMPTY_SHARED_TEXT = "shared={}"; + + /** A chat controller (default room, no `applicationId` override) with one share button per viewer and the room's state as text. */ + function twoWayRoomApp(): object { + const controller = recordedHookOf("chatController"); + return appDsl( + stackItems([ + button({ + id: "ba", + name: "shareA", + text: "Share A", + testId: SEND_A_TEST_ID, + onEvent: [eventHandler("click", executeComp("chatController1", "setSharedState", [{ name: "key", value: "fromA" }, { name: "value", value: MESSAGE_FROM_A }]))], + }), + button({ + id: "bb", + name: "shareB", + text: "Share B", + testId: SEND_B_TEST_ID, + onEvent: [eventHandler("click", executeComp("chatController1", "setSharedState", [{ name: "key", value: "fromB" }, { name: "value", value: MESSAGE_FROM_B }]))], + }), + text({ id: "tr", name: "ready", text: "ready={{chatController1.ready}}", testId: READY_TEST_ID }), + text({ id: "ts", name: "shared", text: "shared={{JSON.stringify(chatController1.sharedState)}}", testId: SHARED_TEST_ID }), + ]), + { hooks: [controller] }, + ); + } + + test("two viewers in the same room: each one's share reaches the other", async ({ page, apiUser, newUserSession }) => { + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: "e2e-chat-two-way", dsl: twoWayRoomApp() }); + await publishApp(page.request, appId); + // Viewer B is a second, independent session with no login of its own (`newUserSession`); the app must be public + // for it to open the view at all (`apps/public-app.spec.ts`). + await setPublicToAll(page.request, appId, true); + + const viewA = new AppViewPage(page); + await viewA.open(appId); + const sessionB = await newUserSession(); + const viewB = new AppViewPage(sessionB.page); + await viewB.open(appId); + + // Same connection-establishment budget as "the chat controller connects..." above. + await expect(viewA.byTestId(READY_TEST_ID), "before: A's controller is connected to the room").toHaveText("ready=true", { timeout: CONNECTION_FRAME_TIMEOUT_MS }); + await expect(viewB.byTestId(READY_TEST_ID), "before: B's controller is connected to the same room").toHaveText("ready=true", { timeout: CONNECTION_FRAME_TIMEOUT_MS }); + await expect(viewA.byTestId(SHARED_TEST_ID), "before: the room is empty for A").toHaveText(EMPTY_SHARED_TEXT); + await expect(viewB.byTestId(SHARED_TEST_ID), "before: the room is empty for B").toHaveText(EMPTY_SHARED_TEXT); + + await viewA.buttonByTestId(SEND_A_TEST_ID).click(); + await expect(viewA.byTestId(SHARED_TEST_ID), "control: A's own view carries A's message").toContainText(MESSAGE_FROM_A); + await expect(viewB.byTestId(SHARED_TEST_ID), "B receives A's message").toContainText(MESSAGE_FROM_A); + + await viewB.buttonByTestId(SEND_B_TEST_ID).click(); + await expect(viewB.byTestId(SHARED_TEST_ID), "control: B's own view carries B's message").toContainText(MESSAGE_FROM_B); + await expect(viewA.byTestId(SHARED_TEST_ID), "A receives B's message").toContainText(MESSAGE_FROM_B); + + // Both messages coexist (the second share did not overwrite the first) on both sides. + await expect(viewA.byTestId(SHARED_TEST_ID), "A still has A's own message after B's share").toContainText(MESSAGE_FROM_A); + await expect(viewB.byTestId(SHARED_TEST_ID), "B still has A's message after sharing its own").toContainText(MESSAGE_FROM_A); + }); }); test.describe("S20 chat box", () => { From 7b8e5c3b974f3431baf0b513a480477fbed12891 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Mon, 23 Nov 2026 14:27:26 +0100 Subject: [PATCH 03/20] fix: pin redis-server and redis-tools to the available 8.12.0 build The jammy repo no longer serves redis-server/redis-tools 8.10.3, which the image's apt-get install implicitly pulled in via the redis metapackage, breaking the build with an unsatisfiable version constraint. Pin all three redis packages to 8.12.0, the version actually available. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- deploy/docker/Dockerfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index d7b13da787..8c9d40976d 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -371,7 +371,9 @@ RUN curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg - RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get -y install --no-install-recommends -y \ nginx=1.31.9-1~jammy \ mongodb-org=7.0.48 \ - redis=6:8.10.3-1rl1~jammy1 \ + redis=6:8.12.0-1rl1~jammy1 \ + redis-server=6:8.12.0-1rl1~jammy1 \ + redis-tools=6:8.12.0-1rl1~jammy1 \ supervisor \ gosu \ nodejs=22.23.5-1nodesource1 \ From e938e9a37ad67f272f7cc6d075df0761057530ff Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 14:31:24 +0100 Subject: [PATCH 04/20] fix: close security gaps across org membership, auth, data access and workspace lifecycle, with e2e coverage Fixes the security findings from the 2026-11-21 research pass (D-6 through D-63): missing or wrong permission checks on applications, bundles, folders, data sources and history snapshots; sessions and API keys that survive a password change; weak-password sign-up and set-password paths; CORS/CSRF exposure; npm registry and actuator metrics reachable without the right grant; stale membership-removal cleanup (folders, bundles); and a handful of related functional/display defects found while building the tests (mail-link double slash, invite dialog translation key, system-group rename, profile app count). Adds or updates Java unit/contract/Mongo-integration tests and e2e Playwright scenarios (security, lifecycle and foundation suites) for every fix, and removes each fixed scenario from the e2e quarantine list. Confirmed with a combined e2e run against an image built from this branch: 693/696 default tests passed; the 3 failures are pre-existing suite drift unrelated to this work (documented in their own README rows). Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- .../src/comps/comps/remoteComp/remoteComp.tsx | 5 +- .../pages/ApplicationV2/UserProfileLayout.tsx | 11 +- .../src/pages/common/inviteDialog.tsx | 2 +- ...alEditorContext.hostApplicationId.test.tsx | 21 + .../src/util/context/ExternalEditorContext.ts | 12 +- deploy/docker/README.md | 4 +- deploy/docker/default.env | 7 +- deploy/helm/README.md | 2 +- docs/setup-and-run/self-hosting/README.md | 9 +- e2e/AGENTS.md | 4 +- e2e/README.md | 281 ++++++------- e2e/playwright.config.ts | 2 + e2e/scripts/run-in-docker.sh | 3 +- e2e/src/api/client.ts | 29 +- e2e/src/constants.ts | 19 +- e2e/src/lifecycle/mail.ts | 21 +- e2e/src/pages/SettingPage.ts | 3 + e2e/src/run-selection.ts | 6 +- e2e/src/security/quarantine.ts | 137 +++---- e2e/tests/account/password.spec.ts | 13 +- e2e/tests/auth/password-recovery.spec.ts | 36 +- e2e/tests/auth/providers-login.spec.ts | 20 +- e2e/tests/auth/signup-edge.spec.ts | 31 +- e2e/tests/foundation/lifecycle-mail.spec.ts | 13 +- .../lifecycle-recovery-helpers.spec.ts | 5 +- e2e/tests/foundation/run-selection.spec.ts | 2 +- e2e/tests/foundation/security-api-raw.spec.ts | 24 +- .../foundation/security-constants.spec.ts | 3 + e2e/tests/foundation/security-helpers.spec.ts | 40 +- .../foundation/security-quarantine.spec.ts | 52 ++- e2e/tests/security/bundles.spec.ts | 42 +- e2e/tests/security/credentials.spec.ts | 3 +- e2e/tests/security/cross-org.spec.ts | 38 +- e2e/tests/security/draft-queries.spec.ts | 161 ++++++++ e2e/tests/security/enterprise.spec.ts | 44 ++ e2e/tests/security/membership-changes.spec.ts | 15 +- e2e/tests/security/outbound.spec.ts | 105 ++++- e2e/tests/security/public-leakage.spec.ts | 19 +- e2e/tests/security/roles.spec.ts | 146 ++++++- e2e/tests/workspace/groups-gui.spec.ts | 14 +- e2e/tests/workspace/leave-removal.spec.ts | 108 ++++- .../model/ApplicationHistorySnapshot.java | 5 + .../model/ApplicationHistorySnapshotTS.java | 5 + .../ApplicationHistorySnapshotService.java | 5 + ...ApplicationHistorySnapshotServiceImpl.java | 1 + .../bundle/repository/BundleRepository.java | 2 + .../domain/bundle/service/BundleService.java | 2 + .../bundle/service/BundleServiceImpl.java | 5 + .../organization/model/Organization.java | 6 + .../service/BundlePermissionHandler.java | 6 + .../service/DatasourcePermissionHandler.java | 9 + .../service/ResourcePermissionHandler.java | 124 +++++- .../service/ResourcePermissionService.java | 6 +- .../ResourcePermissionServiceImpl.java | 14 +- .../user/repository/CustomUserRepository.java | 10 + .../repository/CustomUserRepositoryImpl.java | 42 ++ .../user/repository/UserRepository.java | 2 +- .../EmailCommunicationServiceImpl.java | 3 +- .../domain/user/service/UserService.java | 13 +- .../domain/user/service/UserServiceImpl.java | 13 +- ...icationHistorySnapshotServiceImplTest.java | 51 +++ .../model/OrganizationJsonTest.java | 96 +++++ .../service/BundlePermissionHandlerTest.java | 90 +++++ .../DatasourcePermissionHandlerTest.java | 113 ++++++ .../service/PermissionTestFixtures.java | 5 + .../ResourcePermissionHandlerTest.java | 219 ++++++++++ .../ResourcePermissionServiceImplTest.java | 79 ++++ .../EmailCommunicationServiceImplTest.java | 18 + .../service/UserServiceImplPasswordTest.java | 58 ++- .../org/lowcoder/sdk/config/CommonConfig.java | 9 + .../org/lowcoder/sdk/exception/BizError.java | 1 + .../org/lowcoder/sdk/util/PasswordRule.java | 41 ++ .../src/main/resources/locale_de.properties | 3 + .../src/main/resources/locale_en.properties | 3 + .../src/main/resources/locale_zh.properties | 3 + .../lowcoder/sdk/config/CommonConfigTest.java | 19 + .../lowcoder/sdk/util/PasswordRuleTest.java | 94 +++++ .../ApplicationApiServiceImpl.java | 11 +- .../ApplicationHistorySnapshotController.java | 85 +++- .../ApplicationRecordApiServiceImpl.java | 24 +- .../request/form/FormAuthRequest.java | 6 + .../api/bundle/BundleApiServiceImpl.java | 76 +++- .../datasource/DatasourceApiServiceImpl.java | 3 +- .../framework/security/SecurityConfig.java | 131 ++++-- .../api/home/FolderApiServiceImpl.java | 53 ++- .../lowcoder/api/home/SessionUserService.java | 9 + .../api/home/SessionUserServiceImpl.java | 46 +++ .../org/lowcoder/api/meta/MetaEndpoints.java | 7 +- .../api/npm/PrivateNpmRegistryController.java | 19 +- .../query/ApplicationQueryApiServiceImpl.java | 50 ++- .../usermanagement/GroupApiServiceImpl.java | 8 + .../usermanagement/InvitationController.java | 7 +- .../api/usermanagement/OrgApiServiceImpl.java | 7 +- .../api/usermanagement/OrgDevChecker.java | 19 + .../usermanagement/UserApiServiceImpl.java | 19 +- .../api/usermanagement/UserController.java | 20 +- .../OrgAndGroupEventListener.java | 34 +- ...ApplicationApiServiceImplBranchesTest.java | 163 +++++++- ...plicationHistorySnapshotEndpointsTest.java | 378 +++++++++++++++++- .../ApplicationRecordApiServiceImplTest.java | 132 +++++- .../AuthenticationControllerTest.java | 47 ++- .../EmailBackfillEndToEndTest.java | 8 +- .../EmailNormalizationTest.java | 2 +- .../GenericAuthenticateTest.java | 2 +- .../request/form/FormAuthRequestTest.java | 74 +++- .../BundleApiServiceImplPermissionsTest.java | 235 ++++++++++- .../ApplicationEndpointsContractTest.java | 6 +- ...nHistorySnapshotEndpointsContractTest.java | 59 ++- .../InvitationEndpointsContractTest.java | 23 ++ .../OrganizationEndpointsContractTest.java | 15 +- ...rivateNpmRegistryEndpointContractTest.java | 6 + .../endpoint/UserEndpointsContractTest.java | 108 ++++- .../contract/support/OrganizationSamples.java | 6 +- .../support/UserManagementSamples.java | 4 +- .../DatasourceApiServiceImplTest.java | 35 +- .../security/AbstractCorsCredentialsTest.java | 86 ++++ .../security/AnonymousRoutesSecurityTest.java | 129 ++++++ .../CorsAllowedDomainsPreflightTest.java | 6 +- .../CorsCredentialsListedOriginTest.java | 34 ++ .../CorsCredentialsMixedConfigTest.java | 38 ++ .../CorsCredentialsWildcardOnlyTest.java | 22 + ...CorsCredentialsWildcardSubPatternTest.java | 36 ++ .../api/home/FolderApiServiceImplTest.java | 145 ++++++- ...lderPermissionListThroughTheStackTest.java | 208 ++++++++++ ...SessionUserServiceImplEndSessionsTest.java | 234 +++++++++++ ...teNpmRegistryControllerPermissionTest.java | 146 +++++++ .../ApplicationQueryApiServiceImplTest.java | 354 ++++++++++++++-- .../GroupApiServiceImplTest.java | 50 +++ .../InvitationAndUserApiServiceTest.java | 13 +- .../api/usermanagement/OrgDevCheckerTest.java | 146 +++++++ ...erApiServiceImplResetLostPasswordTest.java | 100 +++++ .../UserApiServiceImplResetPasswordTest.java | 83 ++++ .../UserCreateInOrgPasswordRuleTest.java | 109 +++++ .../UserSetPasswordIfAbsentMongoTest.java | 177 ++++++++ ...positoryFindByOrganizationIdMongoTest.java | 71 ++++ ...urcePermissionBatchWorkspaceMongoTest.java | 366 +++++++++++++++++ .../OrgAndGroupEventListenerTest.java | 172 +++++++- .../json-contract/contract-registry.tsv | 52 +-- ...lowcoder.api.home.UserHomepageView.S1.json | 2 +- ....api.home.UserHomepageView.S1Internal.json | 1 - ...er.api.home.UserHomepageView.S1Public.json | 1 - ...Endpoints$ResetLostPasswordRequest.D1.json | 2 +- ...serEndpoints$UpdatePasswordRequest.D1.json | 2 +- ...agement.view.OrgAndVisitorRoleView.S1.json | 2 +- ...view.OrgAndVisitorRoleView.S1Internal.json | 1 - ...t.view.OrgAndVisitorRoleView.S1Public.json | 1 - ...sermanagement.view.UserProfileView.S1.json | 2 +- ...ement.view.UserProfileView.S1Internal.json | 1 - ...agement.view.UserProfileView.S1Public.json | 1 - ...in.organization.model.Organization.S1.json | 2 +- ...ization.model.Organization.S1Internal.json | 1 - ...anization.model.Organization.S1Public.json | 1 - ...in.organization.model.Organization.S2.json | 2 +- 153 files changed, 6763 insertions(+), 660 deletions(-) create mode 100644 e2e/tests/security/draft-queries.spec.ts create mode 100644 server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/CustomUserRepository.java create mode 100644 server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/CustomUserRepositoryImpl.java create mode 100644 server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/application/service/impl/ApplicationHistorySnapshotServiceImplTest.java create mode 100644 server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/organization/model/OrganizationJsonTest.java create mode 100644 server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/ResourcePermissionServiceImplTest.java create mode 100644 server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/PasswordRule.java create mode 100644 server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/PasswordRuleTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/AbstractCorsCredentialsTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/AnonymousRoutesSecurityTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsListedOriginTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsMixedConfigTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsWildcardOnlyTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsWildcardSubPatternTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderPermissionListThroughTheStackTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/SessionUserServiceImplEndSessionsTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/npm/PrivateNpmRegistryControllerPermissionTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/OrgDevCheckerTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetLostPasswordTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserCreateInOrgPasswordRuleTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserSetPasswordIfAbsentMongoTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/bundle/BundleRepositoryFindByOrganizationIdMongoTest.java create mode 100644 server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/permission/ResourcePermissionBatchWorkspaceMongoTest.java delete mode 100644 server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1Internal.json delete mode 100644 server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1Public.json delete mode 100644 server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1Internal.json delete mode 100644 server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1Public.json delete mode 100644 server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1Internal.json delete mode 100644 server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1Public.json delete mode 100644 server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1Internal.json delete mode 100644 server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1Public.json diff --git a/client/packages/lowcoder/src/comps/comps/remoteComp/remoteComp.tsx b/client/packages/lowcoder/src/comps/comps/remoteComp/remoteComp.tsx index 529b3832ff..a977665cf2 100644 --- a/client/packages/lowcoder/src/comps/comps/remoteComp/remoteComp.tsx +++ b/client/packages/lowcoder/src/comps/comps/remoteComp/remoteComp.tsx @@ -16,7 +16,7 @@ import { CompContext } from "@lowcoder-ee/comps/utils/compContext"; import React from "react"; import type { AppState } from "@lowcoder-ee/redux/reducers"; import { useSelector } from "react-redux"; -import { ExternalEditorContext } from "@lowcoder-ee/util/context/ExternalEditorContext"; +import { ExternalEditorContext, readCheckedApplicationId } from "@lowcoder-ee/util/context/ExternalEditorContext"; /** Unique `key` per `RemoteCompView` so list/grid rows do not all share the same key (remounts + useMount re-runs on unrelated updates). */ let globalRemoteViewInstanceId = 0; @@ -67,7 +67,8 @@ const RemoteCompView = React.memo((props: React.PropsWithChildren state.npmPlugin.packageVersion['lowcoder-comps']); diff --git a/client/packages/lowcoder/src/pages/ApplicationV2/UserProfileLayout.tsx b/client/packages/lowcoder/src/pages/ApplicationV2/UserProfileLayout.tsx index 54373f6849..2ac8e911fd 100644 --- a/client/packages/lowcoder/src/pages/ApplicationV2/UserProfileLayout.tsx +++ b/client/packages/lowcoder/src/pages/ApplicationV2/UserProfileLayout.tsx @@ -11,7 +11,7 @@ import { getCurrentUser } from "../../redux/selectors/usersSelectors"; import { normalAppListSelector } from "../../redux/selectors/applicationSelector"; import { useLocation } from "react-router-dom"; -import { useMemo } from "react"; +import { useEffect, useMemo } from "react"; import history from "util/history"; import { trans, languageList } from "../../i18n"; import { ALL_APPLICATIONS_URL } from "constants/routesURL"; @@ -36,6 +36,7 @@ import { import { useDispatch } from "react-redux"; import { beforeImgUpload, getBase64 } from "util/fileUtils"; import { updateUserAction, updateUserSuccess } from "redux/reduxActions/userActions"; +import { fetchAllApplications } from "../../redux/reduxActions/applicationActions"; import { default as Upload, UploadChangeParam } from "antd/es/upload"; import { USER_HEAD_UPLOAD_URL } from "constants/apiConstants"; import { messageInstance } from "lowcoder-design/src/components/GlobalInstances"; @@ -156,6 +157,14 @@ export function UserProfileLayout(props: UserProfileLayoutProps) { const currentPath = useLocation().pathname; const dispatch = useDispatch(); + // The "Info" counts read the redux app list, which no other component on this page fills (its other callers fetch + // lazily and only when the list is empty), so fetch it on mount and whenever the workspace changes (D-63). + useEffect(() => { + if (currentOrgId) { + dispatch(fetchAllApplications({})); + } + }, [currentOrgId, dispatch]); + const handleUploadChange = (info: UploadChangeParam) => { if (info.file.status === "done") { getBase64(info.file.originFileObj, (imageUrl: string) => { diff --git a/client/packages/lowcoder/src/pages/common/inviteDialog.tsx b/client/packages/lowcoder/src/pages/common/inviteDialog.tsx index 49498788ff..28470611ae 100644 --- a/client/packages/lowcoder/src/pages/common/inviteDialog.tsx +++ b/client/packages/lowcoder/src/pages/common/inviteDialog.tsx @@ -46,7 +46,7 @@ function InviteContent(props: { inviteInfo: InviteInfo, onClose?: () => void }) try { const resp = await InviteApi.sendInvitations({emails: filteredEmails, orgId: inviteInfo.invitedOrganizationId}) if (validateResponse(resp) && resp.data.success) { - messageInstance.success(trans('membersSettings.inviteByEmailSuccess')); + messageInstance.success(trans('memberSettings.inviteByEmailSuccess')); onClose?.(); return; } diff --git a/client/packages/lowcoder/src/util/context/ExternalEditorContext.hostApplicationId.test.tsx b/client/packages/lowcoder/src/util/context/ExternalEditorContext.hostApplicationId.test.tsx index cbb138344f..4370d1fbbd 100644 --- a/client/packages/lowcoder/src/util/context/ExternalEditorContext.hostApplicationId.test.tsx +++ b/client/packages/lowcoder/src/util/context/ExternalEditorContext.hostApplicationId.test.tsx @@ -3,6 +3,7 @@ import { useContext, useMemo } from "react"; import { ExternalEditorContext, ExternalEditorContextState, + readCheckedApplicationId, } from "./ExternalEditorContext"; import { AppTypeEnum } from "constants/applicationConstants"; @@ -157,3 +158,23 @@ describe("ExternalEditorContext hostApplicationId threading", () => { expect(screen.getByTestId("host-id").textContent).toBe(NEW_HOST); }); }); + +const MODULE_ID = "module-app-id"; +const HOST_ID = "host-app-id"; +const APP_ID = "app-id"; + +describe("readCheckedApplicationId (D-35: the npm component loader's app id)", () => { + it("a module embedded in a host resolves to the host id", () => { + expect( + readCheckedApplicationId({ applicationId: MODULE_ID, hostApplicationId: HOST_ID, appType: AppTypeEnum.Module }) + ).toBe(HOST_ID); + }); + + it("a top-level app (no hostApplicationId) resolves to its own applicationId", () => { + expect(readCheckedApplicationId({ applicationId: APP_ID, appType: AppTypeEnum.Application })).toBe(APP_ID); + }); + + it("no app (the loader then uses 'none') resolves to an empty string", () => { + expect(readCheckedApplicationId({ applicationId: "", appType: AppTypeEnum.Application })).toBe(""); + }); +}); diff --git a/client/packages/lowcoder/src/util/context/ExternalEditorContext.ts b/client/packages/lowcoder/src/util/context/ExternalEditorContext.ts index d076565003..b5c49b9b49 100644 --- a/client/packages/lowcoder/src/util/context/ExternalEditorContext.ts +++ b/client/packages/lowcoder/src/util/context/ExternalEditorContext.ts @@ -16,7 +16,7 @@ export interface ExternalEditorContextState { * was actually granted READ on -- not an embedded module's own id, which may not itself be directly * READ-checked -- reads this field instead. Unset at the top level (the host page itself, module or not); a * module propagates it from its own enclosing context so nested modules keep pointing at the same, outermost - * host (see moduleComp.tsx). + * host (see moduleComp.tsx). e.g. the chat controller, the npm component loader. */ hostApplicationId?: string; @@ -63,6 +63,16 @@ export interface ExternalEditorContextState { changeExternalState?: (state: Partial) => void; } +/** + * The app id the viewer was actually READ-checked on: the outermost host app id when set, otherwise the context's + * own `applicationId`. Used by the npm component loader (D-35) so a component embedded in a module resolves + * registries through the host app's workspace, which the viewer was granted READ on, rather than the module's own + * (possibly ungranted) id. + */ +export function readCheckedApplicationId(state: ExternalEditorContextState): string { + return state.hostApplicationId ?? state.applicationId; +} + export const ExternalEditorContext = createContext({ applicationId: "", appType: AppTypeEnum.Application, diff --git a/deploy/docker/README.md b/deploy/docker/README.md index 0b7d329c66..2c834560c5 100644 --- a/deploy/docker/README.md +++ b/deploy/docker/README.md @@ -66,7 +66,7 @@ Image can be configured by setting environment variables. | `LOWCODER_REDIS_URL` | Redis server URL | `redis://localhost:6379` | | `LOWCODER_DB_ENCRYPTION_PASSWORD` | Encryption password | `lowcoder.org` | | `LOWCODER_DB_ENCRYPTION_SALT` | Salt used for encrypting password | `lowcoder.org` | -| `LOWCODER_CORS_DOMAINS` | CORS allowed domains | `*` | +| `LOWCODER_CORS_DOMAINS` | CORS allowed domains, comma-separated; only a listed, non-wildcard origin's own script may read a credentialed answer cross-origin (not a CSRF defense) | `*` | | `LOWCODER_PUBLIC_URL` | The URL of the public User Interface | `localhost:3000` | | `LOWCODER_MAX_REQUEST_SIZE` | Lowcoder max request size | `20m` | | `LOWCODER_MAX_QUERY_TIMEOUT` | Lowcoder max query timeout (in seconds) | `120` | @@ -148,7 +148,7 @@ Image can be configured by setting environment variables. | `LOWCODER_REDIS_URL` | Redis server URL | `redis://localhost:6379` | | `LOWCODER_DB_ENCRYPTION_PASSWORD` | Encryption password | `lowcoder.org` | | `LOWCODER_DB_ENCRYPTION_SALT` | Salt used for encrypting password | `lowcoder.org` | -| `LOWCODER_CORS_DOMAINS` | CORS allowed domains | `*` | +| `LOWCODER_CORS_DOMAINS` | CORS allowed domains, comma-separated; only a listed, non-wildcard origin's own script may read a credentialed answer cross-origin (not a CSRF defense) | `*` | | `LOWCODER_PUBLIC_URL` | The URL of the public User Interface | `localhost:3000` | | `LOWCODER_MAX_ORGS_PER_USER` | Default maximum organizations per user | `100` | | `LOWCODER_MAX_MEMBERS_PER_ORG` | Default maximum members per organization | `1000` | diff --git a/deploy/docker/default.env b/deploy/docker/default.env index c62a59c58a..572df33997 100644 --- a/deploy/docker/default.env +++ b/deploy/docker/default.env @@ -91,7 +91,12 @@ LOWCODER_APP_SNAPSHOT_RETENTIONTIME=30 LOWCODER_DB_ENCRYPTION_PASSWORD="lowcoder.org" LOWCODER_DB_ENCRYPTION_SALT="lowcoder.org" -# CORS allowed domains +# CORS allowed domains (comma-separated; a wildcard sub-pattern such as https://*.example.com is allowed and still +# counts as listed). Controls only whether the browser lets a cross-origin caller's own script READ a credentialed +# answer from the API: only an origin listed here gets that. "*" by itself lets any origin reach the API +# cross-origin, but its own script cannot read a credentialed answer; embedding a private app or using the SDK from +# another site needs that site's own origin listed here. This is NOT a CSRF defense: it does not stop the browser +# from sending the session cookie on a plain cross-site request in the first place (CSRF protection is separate). LOWCODER_CORS_DOMAINS="*" # # API-KEY secret - should be a string of at least 32 random characters diff --git a/deploy/helm/README.md b/deploy/helm/README.md index 933f33031f..220b0bee75 100644 --- a/deploy/helm/README.md +++ b/deploy/helm/README.md @@ -192,7 +192,7 @@ you do not use the meeting components. Without credentials `/rte/...` answers HT | `global.config.workspaceMode` | Sets the workspace mode. Possible types are: SAAS, ENTERPRISE | `SAAS` | | `global.config.userId` | User ID of user running Lowcoder server application in container | `9001` | | `global.config.groupId` | Group ID of user running Lowcoder server application in container | `9001` | -| `global.config.corsAllowedDomains` | CORS allowed domains | `*` | +| `global.config.corsAllowedDomains` | CORS allowed domains, comma-separated; only a listed, non-wildcard origin's own script may read a credentialed answer cross-origin (not a CSRF defense) | `*` | | `global.config.enableUserSignUp` | Enable users signing up to lowcoder via login page | `true` | | `global.config.enableEmailAuth` | Controls whether authentication via email is enabled | `true` | | `global.config.emailNotificationSender` | Email used in notifications from lowcoder | `info@localhost` | diff --git a/docs/setup-and-run/self-hosting/README.md b/docs/setup-and-run/self-hosting/README.md index 989a6ec1a3..f01f854c6d 100644 --- a/docs/setup-and-run/self-hosting/README.md +++ b/docs/setup-and-run/self-hosting/README.md @@ -282,7 +282,7 @@ ENV Variables for Helm, Docker Compose, and Docker installations are to find in This image contains all services needed to run Lowcoder platform in one container. -
Environment variableDescriptionDefault-Value
LOWCODER_REDIS_ENABLEDIf true redis server is started in the containertrue
LOWCODER_MONGODB_ENABLEDIf true mongo database is started in the containertrue
LOWCODER_MONGODB_EXPOSEDIf true mongo database accept connections from outside the dockerfalse
LOWCODER_API_SERVICE_ENABLEDIf true lowcoder api-service is started in the containertrue
LOWCODER_NODE_SERVICE_ENABLEDIf true lowcoder node-service is started in the containertrue
LOWCODER_FRONTEND_ENABLEDIf true lowcoder web frontend is started in the containertrue
LOWCODER_PUIDID of user running services. It will own all created logs and data.9001
LOWCODER_PGIDID of group of the user running services.9001
LOWCODER_MONGODB_URLMongo database connection stringmongodb://localhost:27017/lowcoder?authSource=admin
LOWCODER_REDIS_URLRedis server URLredis://localhost:6379
LOWCODER_DB_ENCRYPTION_PASSWORDEncryption passwordlowcoder.org
LOWCODER_DB_ENCRYPTION_SALTSalt used for encrypting passwordlowcoder.org
LOWCODER_CORS_DOMAINSCORS allowed domains*
LOWCODER_PUBLIC_URLThe URL of the public User Interfacelocalhost:3000
LOWCODER_MAX_REQUEST_SIZELowcoder max request size20m
LOWCODER_MAX_QUERY_TIMEOUTLowcoder max query timeout (in seconds)120
LOWCODER_DEFAULT_QUERY_TIMEOUTLowcoder default query timeout (in seconds)10
LOWCODER_API_RATE_LIMITNumber of max Request per Second100
LOWCODER_API_SERVICE_URLLowcoder API service URLhttp://localhost:8080
LOWCODER_NODE_SERVICE_URLLowcoder Node service (js executor) URLhttp://localhost:6060
LOWCODER_MAX_ORGS_PER_USERDefault maximum organizations per user100
LOWCODER_MAX_MEMBERS_PER_ORGDefault maximum members per organization1000
LOWCODER_MAX_GROUPS_PER_ORGDefault maximum groups per organization100
LOWCODER_MAX_APPS_PER_ORGDefault maximum applications per organization1000
LOWCODER_MAX_DEVELOPERSDefault maximum developers100
LOWCODER_WORKSPACE_MODESAAS to activate, ENTERPRISE to switch off - WorkspacesSAAS
LOWCODER_EMAIL_SIGNUP_ENABLEDControl if users create their own Workspace automatic when Sign Uptrue
LOWCODER_EMAIL_AUTH_ENABLEDControl if Users can Sign Up / Login using the Standard Email Fieldtrue
LOWCODER_CREATE_WORKSPACE_ON_SIGNUPIF LOWCODER_WORKSPACE_MODE = SAAS, controls if a own workspace is created for the user after sign uptrue
LOWCODER_MARKETPLACE_PRIVATE_MODEControl if not to show Apps on the local Marketplace to anonymous userstrue
LOWCODER_SUPERUSER_USERNAMEUsername of the Super-User of an Lowcoder Installationadmin@localhost
LOWCODER_SUPERUSER_PASSWORDPassword of the Super-User, if not present or empty, it will be generated`generated and printed into log file
+
Environment variableDescriptionDefault-Value
LOWCODER_REDIS_ENABLEDIf true redis server is started in the containertrue
LOWCODER_MONGODB_ENABLEDIf true mongo database is started in the containertrue
LOWCODER_MONGODB_EXPOSEDIf true mongo database accept connections from outside the dockerfalse
LOWCODER_API_SERVICE_ENABLEDIf true lowcoder api-service is started in the containertrue
LOWCODER_NODE_SERVICE_ENABLEDIf true lowcoder node-service is started in the containertrue
LOWCODER_FRONTEND_ENABLEDIf true lowcoder web frontend is started in the containertrue
LOWCODER_PUIDID of user running services. It will own all created logs and data.9001
LOWCODER_PGIDID of group of the user running services.9001
LOWCODER_MONGODB_URLMongo database connection stringmongodb://localhost:27017/lowcoder?authSource=admin
LOWCODER_REDIS_URLRedis server URLredis://localhost:6379
LOWCODER_DB_ENCRYPTION_PASSWORDEncryption passwordlowcoder.org
LOWCODER_DB_ENCRYPTION_SALTSalt used for encrypting passwordlowcoder.org
LOWCODER_CORS_DOMAINSCORS allowed domains, comma-separated; only a listed, non-wildcard origin's own script may read a credentialed answer cross-origin (not a CSRF defense)*
LOWCODER_PUBLIC_URLThe URL of the public User Interfacelocalhost:3000
LOWCODER_MAX_REQUEST_SIZELowcoder max request size20m
LOWCODER_MAX_QUERY_TIMEOUTLowcoder max query timeout (in seconds)120
LOWCODER_DEFAULT_QUERY_TIMEOUTLowcoder default query timeout (in seconds)10
LOWCODER_API_RATE_LIMITNumber of max Request per Second100
LOWCODER_API_SERVICE_URLLowcoder API service URLhttp://localhost:8080
LOWCODER_NODE_SERVICE_URLLowcoder Node service (js executor) URLhttp://localhost:6060
LOWCODER_MAX_ORGS_PER_USERDefault maximum organizations per user100
LOWCODER_MAX_MEMBERS_PER_ORGDefault maximum members per organization1000
LOWCODER_MAX_GROUPS_PER_ORGDefault maximum groups per organization100
LOWCODER_MAX_APPS_PER_ORGDefault maximum applications per organization1000
LOWCODER_MAX_DEVELOPERSDefault maximum developers100
LOWCODER_WORKSPACE_MODESAAS to activate, ENTERPRISE to switch off - WorkspacesSAAS
LOWCODER_EMAIL_SIGNUP_ENABLEDControl if users create their own Workspace automatic when Sign Uptrue
LOWCODER_EMAIL_AUTH_ENABLEDControl if Users can Sign Up / Login using the Standard Email Fieldtrue
LOWCODER_CREATE_WORKSPACE_ON_SIGNUPIF LOWCODER_WORKSPACE_MODE = SAAS, controls if a own workspace is created for the user after sign uptrue
LOWCODER_MARKETPLACE_PRIVATE_MODEControl if not to show Apps on the local Marketplace to anonymous userstrue
LOWCODER_SUPERUSER_USERNAMEUsername of the Super-User of an Lowcoder Installationadmin@localhost
LOWCODER_SUPERUSER_PASSWORDPassword of the Super-User, if not present or empty, it will be generated`generated and printed into log file
#### API Key Secret @@ -298,7 +298,7 @@ To enable secure Password Reset flow for the users, you need to configure your o ### ENV Variables for the api-service image -
Environment variableDescriptionDefault-Value
LOWCODER_PUIDID of user running services. It will own all created logs and data.9001
LOWCODER_PGIDID of group of the user running services.9001
LOWCODER_MONGODB_URLMongo database connection stringmongodb://localhost:27017/lowcoder?authSource=admin
LOWCODER_REDIS_URLRedis server URLredis://localhost:6379
LOWCODER_DB_ENCRYPTION_PASSWORDEncryption passwordlowcoder.org
LOWCODER_DB_ENCRYPTION_SALTSalt used for encrypting passwordlowcoder.org
LOWCODER_CORS_DOMAINSCORS allowed domains*
LOWCODER_PUBLIC_URLThe URL of the public User Interfacelocalhost:3000
LOWCODER_MAX_ORGS_PER_USERDefault maximum organizations per user100
LOWCODER_MAX_MEMBERS_PER_ORGDefault maximum members per organization1000
LOWCODER_MAX_GROUPS_PER_ORGDefault maximum groups per organization100
LOWCODER_MAX_APPS_PER_ORGDefault maximum applications per organization1000
LOWCODER_MAX_DEVELOPERSDefault maximum developers100
LOWCODER_MAX_REQUEST_SIZELowcoder max request size20m
LOWCODER_MAX_QUERY_TIMEOUTLowcoder max query timeout (in seconds)120
LOWCODER_DEFAULT_QUERY_TIMEOUTLowcoder default query timeout (in seconds)10
LOWCODER_WORKSPACE_MODESAAS to activate, ENTERPRISE to switch off - WorkspacesSAAS
LOWCODER_EMAIL_SIGNUP_ENABLEDControl is users can create their own Workspace when Sign Uptrue
LOWCODER_CREATE_WORKSPACE_ON_SIGNUPIF LOWCODER_WORKSPACE_MODE = SAAS, controls if a own workspace is created for the user after sign uptrue
LOWCODER_MARKETPLACE_PRIVATE_MODEControl if not to show Apps on the local Marketplace to anonymous userstrue
LOWCODER_SUPERUSER_USERNAMEUsername of the Super-User of an Lowcoder Installationadmin@localhost
LOWCODER_SUPERUSER_PASSWORDPassword of the Super-User, if not present or empty, it will be generated`generated and printed into log file
+
Environment variableDescriptionDefault-Value
LOWCODER_PUIDID of user running services. It will own all created logs and data.9001
LOWCODER_PGIDID of group of the user running services.9001
LOWCODER_MONGODB_URLMongo database connection stringmongodb://localhost:27017/lowcoder?authSource=admin
LOWCODER_REDIS_URLRedis server URLredis://localhost:6379
LOWCODER_DB_ENCRYPTION_PASSWORDEncryption passwordlowcoder.org
LOWCODER_DB_ENCRYPTION_SALTSalt used for encrypting passwordlowcoder.org
LOWCODER_CORS_DOMAINSCORS allowed domains, comma-separated; only a listed, non-wildcard origin's own script may read a credentialed answer cross-origin (not a CSRF defense)*
LOWCODER_PUBLIC_URLThe URL of the public User Interfacelocalhost:3000
LOWCODER_MAX_ORGS_PER_USERDefault maximum organizations per user100
LOWCODER_MAX_MEMBERS_PER_ORGDefault maximum members per organization1000
LOWCODER_MAX_GROUPS_PER_ORGDefault maximum groups per organization100
LOWCODER_MAX_APPS_PER_ORGDefault maximum applications per organization1000
LOWCODER_MAX_DEVELOPERSDefault maximum developers100
LOWCODER_MAX_REQUEST_SIZELowcoder max request size20m
LOWCODER_MAX_QUERY_TIMEOUTLowcoder max query timeout (in seconds)120
LOWCODER_DEFAULT_QUERY_TIMEOUTLowcoder default query timeout (in seconds)10
LOWCODER_WORKSPACE_MODESAAS to activate, ENTERPRISE to switch off - WorkspacesSAAS
LOWCODER_EMAIL_SIGNUP_ENABLEDControl is users can create their own Workspace when Sign Uptrue
LOWCODER_CREATE_WORKSPACE_ON_SIGNUPIF LOWCODER_WORKSPACE_MODE = SAAS, controls if a own workspace is created for the user after sign uptrue
LOWCODER_MARKETPLACE_PRIVATE_MODEControl if not to show Apps on the local Marketplace to anonymous userstrue
LOWCODER_SUPERUSER_USERNAMEUsername of the Super-User of an Lowcoder Installationadmin@localhost
LOWCODER_SUPERUSER_PASSWORDPassword of the Super-User, if not present or empty, it will be generated`generated and printed into log file
#### API Key Secret @@ -359,3 +359,8 @@ In response, you will get a 200 Status code if the service is up and running and } ``` +`GET /api/status/health` (and `/api/status/health/{component}`) stays open without authentication for probes. The +metrics endpoints `/api/status/metrics` (and `/api/status/metrics/{metricName}`) and `/api/status/prometheus` +require authentication: a request without a valid session cookie or API key (`Authorization: Bearer `) +gets 401. A Prometheus scraper must send an API key as a bearer token. + diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index bfc420aa68..52d5610bff 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -124,8 +124,8 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@core`: a main user flow of the base suite (auth, apps, editor, datasource, logic, workspace). - `@security`: an access-control test of `tests/security/` (`TAGS.SECURITY`); the P0 set also carries `@core` and is selected by its ids, see README "security". - `@lifecycle`: a user-lifecycle test (sign-up to deletion), ids `LC-`, details from `lifecycleTestDetails` / `lifecycleCandidateDetails` in `src/security/quarantine.ts` (`TAGS.LIFECYCLE`); in the default run, quarantined through the same two maps as the security ids. -- `@superadmin`: the four instance-super-admin tests SEC-R16a to SEC-R16d (`TAGS.SUPERADMIN`, pass `[TAGS.SUPERADMIN]` as `extraTags` of `securityTestDetails`). Opt-in like `@quarantine`: out of the default run and of the `@security` and P0 runs, in only with `E2E_INCLUDE_SUPERADMIN=1` (README, D-47). A test that also carries `@quarantine` (R16c, R16d) needs both variables. -- `@enterprise`: a test of the second stack in ENTERPRISE workspace mode (SEC-E01 to SEC-E06b, `TAGS.ENTERPRISE`, pass it in `extraTags` of `securityTestDetails`). Never runs on the default stack; with `E2E_STACK_PROFILE=enterprise` it is the only selection (README, "ENTERPRISE stack"). All its tests share ONE workspace: name only your own users, never count the members, never remove, demote or re-password the super admin. SEC-E05 resets the super admin's password, so it also carries `@enterprise-takeover` (`TAGS.ENTERPRISE_TAKEOVER`), which every run leaves out unless `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` (enterprise profile, with `E2E_INCLUDE_QUARANTINE=1`); then it is the ONLY test of the run. Its file keeps trace, screenshot and video off and passes no response body to an assertion (the reset answer holds a password). +- `@superadmin`: the four instance-super-admin tests SEC-R16a to SEC-R16d (`TAGS.SUPERADMIN`, pass `[TAGS.SUPERADMIN]` as `extraTags` of `securityTestDetails`). Opt-in like `@quarantine`: out of the default run and of the `@security` and P0 runs, in only with `E2E_INCLUDE_SUPERADMIN=1` (README, D-47). A test that carried both `@quarantine` and `@superadmin` would need both variables (none does since SEC-R16c and SEC-R16d left the quarantine). +- `@enterprise`: a test of the second stack in ENTERPRISE workspace mode (SEC-E01 to SEC-E07b, `TAGS.ENTERPRISE`, pass it in `extraTags` of `securityTestDetails`). Never runs on the default stack; with `E2E_STACK_PROFILE=enterprise` it is the only selection (README, "ENTERPRISE stack"). All its tests share ONE workspace: name only your own users, never count the members, never remove, demote or re-password the super admin. SEC-E05 resets the super admin's password, so it also carries `@enterprise-takeover` (`TAGS.ENTERPRISE_TAKEOVER`), which every run leaves out unless `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` (enterprise profile, with `E2E_INCLUDE_QUARANTINE=1`); then it is the ONLY test of the run. Its file keeps trace, screenshot and video off and passes no response body to an assertion (the reset answer holds a password). - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. diff --git a/e2e/README.md b/e2e/README.md index 7151df8ee1..2f8e1afd6b 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -25,6 +25,10 @@ lifecycle (insert, save, publish, load) is covered by S1 when `@insert-all` runs `data-testid="insert-comp-"` on insert-panel tiles, `role="tab"`/`role="tablist"`, `data-comp-name`), but it also touches the editor's save code (`appEditorInternal.tsx`). A defect found on this image is assumed to exist in 3.0.0 only where the patch does not touch the involved code; that equivalence is NOT VERIFIED. The image is a locally built tag. + The latest assessed image is `lowcoderorg/lowcoder-ce:3.0.1-e2e` (run of 2026-11-22; the plain `3.0.0-e2e` rows below were measured on the + earlier image). `client-hooks.patch` no longer applies to `dev`: the test hooks are committed there (from the repository root, + `git apply --check e2e/client-hooks.patch` fails and `git apply --check -R e2e/client-hooks.patch` succeeds, checked 2026-11-22), so the patch is + needed only to rebuild an image from the `3.0.0` tag. - **Isolated Docker network per run:** `scripts/run-in-docker.sh` creates `lowcoder-e2e--net`, starts the app container and a PostgreSQL sidecar, waits for `GET /api/configs`, runs Playwright from `mcr.microsoft.com/playwright:v1.64.0-noble` with `e2e/` bound at `/work`, and removes everything on exit. Every run @@ -51,10 +55,10 @@ lifecycle (insert, save, publish, load) is covered by S1 when `@insert-all` runs DATA, RSET, NOOP and QUIT are understood, anything else is 502. The `mailbox` fixture (`mailsTo`, `waitForMail`) reads it with Node's `fetch`, never a Playwright request context: a context created during a test lands in the trace, and the mails hold reset tokens (measured: a trace of a `newContext` read held the mail body, a trace of the `fetch` read held none). `src/lifecycle/mail.ts` parses a mail (nested multipart, 7bit, 8bit, - binary, quoted-printable, base64, charsets, encoded-word subjects) and takes the token out of a reset link (`resetTokenOf`) or the code out of an - invitation (`inviteCodeOf`). Limits: no STARTTLS, no AUTH, and mails live for the whole run, so a test uses an address of its own. The links of the - mails carry the configured public URL as is; the run script's URL ends in a slash, so the links read `http://lowcoder-e2e-app:3000//user/auth/lost-password?token=...` - (a property of this run's setting, not a defect). + binary, quoted-printable, base64, charsets, encoded-word subjects) and takes the token out of a reset link (`resetTokenOf`), or returns the reset link + (`resetLinkOf`) or the invitation link (`inviteLinkOf`) exactly as mailed, to open as a page. Limits: no STARTTLS, no AUTH, and mails live for the whole run, so a test uses an address of its own. The links of the + mails carry the configured public URL without its trailing slashes (D-54), so they read `http://lowcoder-e2e-app:3000/user/auth/lost-password?token=...` + whatever run of slashes the run script's configured URL ends in. - **Fixed app host name `lowcoder-e2e-app`** (`scripts/app-host.sh`): network alias of the app container; `LOWCODER_BASE_URL` is `http://lowcoder-e2e-app:3000`. Reason: the client's hocuspocus URL (`REACT_APP_HOCUSPOCUS_URL=ws://lowcoder-e2e-app:3000/hocuspocus`) is baked in at client build time and the guard @@ -123,7 +127,7 @@ e2e/scripts/run-in-docker.sh --grep @smoke # by tag: @s E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --grep @quarantine E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin # SEC-R16a, SEC-R16b (R16c, R16d also need E2E_INCLUDE_QUARANTINE=1) E2E_INCLUDE_INSERT_ALL=1 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh # everything on the default stack (not the @enterprise tests) -E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh tests/security/enterprise.spec.ts # the ENTERPRISE stack, SEC-E01 to E04, E06a, E06b +E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh tests/security/enterprise.spec.ts # the ENTERPRISE stack, SEC-E01 to E04, E06a, E06b, E07a, E07b E2E_STACK_PROFILE=signup-disabled e2e/scripts/run-in-docker.sh tests/auth/signup-disabled.spec.ts # the stack with e-mail sign-up switched off, LC-AU20 to AU24 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_ENTERPRISE_TAKEOVER=1 E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh # SEC-E05 ALONE (no other test), on its own stack ``` @@ -140,7 +144,7 @@ E2E_INCLUDE_INSERT_ALL=1 e2e/scripts/run-in-docker.sh --grep @insert-all --worke # M3, the module host built in the editor (repository root) e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/modules/module-editor-host.spec.ts -# The ENTERPRISE stack (SEC-E01 to E04, E06a, E06b): not part of the P0 set, not pull-request blocking (repository root) +# The ENTERPRISE stack (SEC-E01 to E04, E06a, E06b, E07a, E07b): not part of the P0 set, not pull-request blocking (repository root) E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/security/enterprise.spec.ts ``` @@ -157,17 +161,17 @@ Tags (`TAGS` in `src/constants.ts`): | `@core` | main user flows of the base suite | yes | | `@slow` | noticeably longer (PostgreSQL, npm, many steps) | yes | | `@npm` | needs the app container to reach the npm registry | yes | -| `@quarantine` | asserts the desired behaviour of a known product defect and fails today | no, `E2E_INCLUDE_QUARANTINE=1` | +| `@quarantine` | asserts the desired behaviour of a known product defect and fails today (on 3.0.1-e2e, 2026-11-22) | no, `E2E_INCLUDE_QUARANTINE=1` | | `@insert-all` | S1: insert, save, publish and load each of the 112 types | no, `E2E_INCLUDE_INSERT_ALL=1` | | `@security` | access-control tests of `tests/security/` | yes (except the rows that also carry an opt-in tag) | -| `@lifecycle` | user-lifecycle tests, ids `LC-` (areas `AU PR AK WM GR SH PW DL IP OT`; `src/security/quarantine.ts`) | yes (quarantined ones excluded like `@security`) | -| `@enterprise` | the second stack in ENTERPRISE workspace mode (SEC-E01 to SEC-E06b, `tests/security/enterprise*.spec.ts`); SEC-E05 also carries `@quarantine`, `@enterprise-takeover` and `@superadmin` | no, never on the default stack; the only ones with `E2E_STACK_PROFILE=enterprise` (SEC-E05 aside) | -| `@enterprise-takeover` | SEC-E05 only: it resets the super admin's password, so it never shares a stack with another test | no, never on the default stack; on the enterprise profile only with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` (plus `E2E_INCLUDE_QUARANTINE=1`), and then it is the ONLY test of the run | +| `@lifecycle` | user-lifecycle tests, ids `LC-` (areas `AU PR AK WM GR SH PW DL IP OT`; `src/security/quarantine.ts`) | yes (the quarantined ones, 12 of 109 as of D-34 and D-49 (LC-PR13 and LC-PW08 left the quarantine; the rest of this count predates several later fixes and is pending the combined final re-measurement), are excluded like `@security`) | +| `@enterprise` | the second stack in ENTERPRISE workspace mode (SEC-E01 to SEC-E07b, `tests/security/enterprise*.spec.ts`); SEC-E05 also carries `@enterprise-takeover` and `@superadmin`, SEC-E07a and SEC-E07b also carry `@superadmin` | no, never on the default stack; the only ones with `E2E_STACK_PROFILE=enterprise` (SEC-E05 aside) | +| `@enterprise-takeover` | SEC-E05 only: it resets the super admin's password, so it never shares a stack with another test | no, never on the default stack; on the enterprise profile only with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1`, and then it is the ONLY test of the run | | `@signup-disabled` | the third stack with `LOWCODER_EMAIL_SIGNUP_ENABLED=false` (LC-AU20 to LC-AU24, `tests/auth/signup-disabled.spec.ts`): every fixture that makes a user signs up, so nothing else runs there | no, never on another stack; the only tests of a run with `E2E_STACK_PROFILE=signup-disabled` | | `@superadmin` | every test that uses the `superAdmin` fixture: SEC-R16a to SEC-R16d and the fixture test of `foundation/security-helpers.spec.ts` (D-47: they break a stack of more than about 420 workspaces); a guard test in `foundation/run-selection.spec.ts` fails when a spec has a test with that fixture and without the tag | no, `E2E_INCLUDE_SUPERADMIN=1` | Untagged is normal (most component, unit and helper tests). The three opt-in variables are independent; a test with several -opt-in tags runs only when all their variables are set (SEC-R16c and SEC-R16d carry `@quarantine` and `@superadmin`) (`src/run-selection.ts`). Tag strings inside `foundation/run-selection.spec.ts` are test +opt-in tags runs only when all their variables are set (SEC-E05 carries `@enterprise-takeover` and `@superadmin`, two opt-in tags; no `@quarantine` test also carries another opt-in tag any more since SEC-R16c, SEC-R16d and SEC-E05 left the quarantine) (`src/run-selection.ts`). Tag strings inside `foundation/run-selection.spec.ts` are test data; its tests are untagged. | Variable | Read by | Effect | @@ -176,8 +180,8 @@ data; its tests are untagged. | `PLAYWRIGHT_IMAGE` | run-in-docker.sh | runner image; version must equal `@playwright/test` in `package-lock.json` (1.64.0) | | `POSTGRES_IMAGE` | run-in-docker.sh | PostgreSQL sidecar image | | `E2E_INCLUDE_QUARANTINE`, `E2E_INCLUDE_INSERT_ALL`, `E2E_INCLUDE_SUPERADMIN` | script and config | non-empty: include that opt-in group | -| `E2E_STACK_PROFILE` | run-in-docker.sh, config | `default` (the default), `signup-disabled` (the app container gets `LOWCODER_EMAIL_SIGNUP_ENABLED=false` and the run keeps only the `@signup-disabled` tests; `E2E_INCLUDE_QUARANTINE` is the only flag that applies) or `enterprise`: the app container gets `LOWCODER_WORKSPACE_MODE=ENTERPRISE` and the run keeps only the `@enterprise` tests (`grep`); another value stops the run. On the enterprise profile `E2E_INCLUDE_QUARANTINE` still opens the quarantined test (SEC-E05), `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` change nothing (the stack has one workspace, so the D-47 limit does not arise). A `--grep` of the command line narrows the profile's selection further; it does not replace it (measured with Playwright 1.64: enterprise profile with `--grep SEC-R01b` lists 0 tests, with `--grep SEC-E02` lists 1, with the default profile `--grep SEC-E02` lists 0) | -| `E2E_INCLUDE_ENTERPRISE_TAKEOVER` | run-in-docker.sh, config | non-empty, enterprise profile only (any other profile stops the script): run SEC-E05 alone; it is also quarantined, so `E2E_INCLUDE_QUARANTINE=1` is needed too | +| `E2E_STACK_PROFILE` | run-in-docker.sh, config | `default` (the default), `signup-disabled` (the app container gets `LOWCODER_EMAIL_SIGNUP_ENABLED=false` and the run keeps only the `@signup-disabled` tests; `E2E_INCLUDE_QUARANTINE` is the only flag that applies) or `enterprise`: the app container gets `LOWCODER_WORKSPACE_MODE=ENTERPRISE` and the run keeps only the `@enterprise` tests (`grep`); another value stops the run. On the enterprise profile `E2E_INCLUDE_QUARANTINE` opens nothing extra (no enterprise test is quarantined any more), `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` change nothing (the stack has one workspace, so the D-47 limit does not arise). A `--grep` of the command line narrows the profile's selection further; it does not replace it (measured with Playwright 1.64: enterprise profile with `--grep SEC-R01b` lists 0 tests, with `--grep SEC-E02` lists 1, with the default profile `--grep SEC-E02` lists 0) | +| `E2E_INCLUDE_ENTERPRISE_TAKEOVER` | run-in-docker.sh, config | non-empty, enterprise profile only (any other profile stops the script): run SEC-E05 alone | | `E2E_HOST_PORT` | run-in-docker.sh | publish the app on `127.0.0.1:` while the run lasts | | `E2E_WORKERS` | playwright.config.ts | worker count, effective only when `playwright test` is run directly; NOT forwarded by the script | | `CI` | script, config | `forbidOnly` and one retry | @@ -231,7 +235,7 @@ e2e/ Test titles carry these ids. -- LC- user-lifecycle tests (`@lifecycle`, quarantined through the same two maps as the SEC ids). Built: OT01 to OT05 (the new-user tour, the profile counts, navigation by role, the member detail and the admin sign-in page, `apps/onboarding.spec.ts` and `account/other.spec.ts`), AU20 to AU24 (the sign-up-disabled stack, `auth/signup-disabled.spec.ts`), AU01 to AU16 (sign-up and sign-in edge cases, `auth/signup-edge.spec.ts` and `auth/signin-session.spec.ts`), PR01 to PR15 (profile and password, `account/profile.spec.ts` and `account/password.spec.ts`), PW01 to PW15 (password recovery and invitation mails, `auth/password-recovery.spec.ts`), DL01 to DL11 (leaving, removal and workspace deletion, `workspace/leave-removal.spec.ts`), IP01 to IP05, IP07, IP08 (sign-in provider configuration, `auth/providers-config.spec.ts`), IP10 to IP15 (sign-in through a mock provider, `auth/providers-login.spec.ts`), AK01 to AK08 (API keys, `account/api-keys.spec.ts`), WM01, WM03, WM04, WM06, WM08 to WM12 (members and workspaces in the UI, `workspace/members-gui.spec.ts` and `workspace/workspaces-gui.spec.ts`), GR01 to GR10 (groups, `workspace/groups-gui.spec.ts`), SH01 to SH06 (sharing, `workspace/share-gui.spec.ts`). +- LC- user-lifecycle tests (`@lifecycle`, quarantined through the same two maps as the SEC ids). Built: OT01 to OT05 (the new-user tour, the profile counts, navigation by role, the member detail and the admin sign-in page, `apps/onboarding.spec.ts` and `account/other.spec.ts`), AU20 to AU24 (the sign-up-disabled stack, `auth/signup-disabled.spec.ts`), AU01 to AU16 (sign-up and sign-in edge cases, `auth/signup-edge.spec.ts` and `auth/signin-session.spec.ts`), PR01 to PR15 (profile and password, `account/profile.spec.ts` and `account/password.spec.ts`), PW01 to PW16 (password recovery and invitation mails, `auth/password-recovery.spec.ts`), DL01 to DL15 (leaving, removal and workspace deletion, `workspace/leave-removal.spec.ts`), IP01 to IP05, IP07, IP08 (sign-in provider configuration, `auth/providers-config.spec.ts`), IP10 to IP15 (sign-in through a mock provider, `auth/providers-login.spec.ts`), AK01 to AK08 (API keys, `account/api-keys.spec.ts`), WM01, WM03, WM04, WM06, WM08 to WM12 (members and workspaces in the UI, `workspace/members-gui.spec.ts` and `workspace/workspaces-gui.spec.ts`), GR01 to GR10 (groups, `workspace/groups-gui.spec.ts`), SH01 to SH06 (sharing, `workspace/share-gui.spec.ts`). - S1 insert, save, publish, load every one of the 112 types (`@insert-all`; catalog unit tests in `insert-catalog.spec.ts`). - S2 text inputs; S3 choice components; S4 date and time; S5 sliders and colour picker; S6 buttons and menus; S7 display components. @@ -244,12 +248,12 @@ Test titles carry these ids. ## Test catalogue -Counts: `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`: -default **612 tests in 102 files**; with `E2E_INCLUDE_QUARANTINE=1` **684 in 104**; with `E2E_INCLUDE_SUPERADMIN=1` **615 in 102**; with both of those **689 in 104**; -with `E2E_INCLUDE_INSERT_ALL=1` **724 in 103**; with all three opt-in variables **801 in 105** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: -**6 in 1** (SEC-E01 to E04, E06a, E06b; also with `E2E_INCLUDE_QUARANTINE=1` alone), **1 in 1** with `E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` (SEC-E05 alone), **0** with the takeover variable alone (SEC-E05 is quarantined too); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 7 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts: `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 99. On request: `@quarantine` 74 (72 with `E2E_INCLUDE_QUARANTINE=1` alone; the two that -also carry `@superadmin` need both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. `@lifecycle` 88 (user-lifecycle tests, ids `LC-`, default run; 21 more are quarantined: LC-AK04, LC-AK08, LC-AU07, LC-AU15, LC-GR03, LC-GR09, LC-PR06, LC-PR13, LC-PR14, LC-PW08, LC-PW09, LC-PW10, LC-PW11, LC-PW12, LC-PW14, LC-PW15, LC-DL03, LC-DL04, LC-IP07, LC-IP14, LC-OT02). +Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`, after this branch's security fixes; this is a static listing, not a Docker run. A combined final run against an image built from this branch (tag `secfix-combined-e2e`) has since confirmed pass/fail for every scenario named in the per-defect rows below: 693/696 default tests passed, the 3 failures pre-existing or unrelated suite drift (documented in their own rows below)): +default **696 tests in 104 files**; with `E2E_INCLUDE_QUARANTINE=1` **709 in 105**; with `E2E_INCLUDE_SUPERADMIN=1` **701 in 104**; with both of those **714 in 105**; +with `E2E_INCLUDE_INSERT_ALL=1` **808 in 105**; with all three opt-in variables **826 in 106** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: +**8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111. On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). +Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -260,25 +264,25 @@ also carry `@superadmin` need both variables), `@superadmin` 5 (the four SEC-R16 | smoke/editor-drag.spec.ts | a component dragged from the insert panel is on the canvas and saved (D-3 prone) | @smoke | 1 | | smoke/network-guard.spec.ts | requests to lowcoder.cloud are blocked, the app is let through | @smoke | 1 | -### auth, workspace, apps (52), account (23) +### auth, workspace, apps (88 default, 95 with the quarantined), account (25 default, 27 with the quarantined) | File | Proves | Tags | Tests | |---|---|---|---| | auth/login.spec.ts | sign-in and sign-out; wrong password stays on sign-in | @core | 2 | -| auth/signup-edge.spec.ts | LC-AU01 to AU08, AU15, AU16: a registered address in any casing, a malformed address, the password rules of the form, the invitation link, a workspace sign-up page, a mismatched confirmation (LC-AU07 and LC-AU15 are quarantined: D-48 password rule, D-30) | @lifecycle, @core for AU08, @quarantine for 2 | 10 (8 default) | +| auth/signup-edge.spec.ts | LC-AU01 to AU08, AU15 to AU17: a registered address in any casing, a malformed address, the password rules of the form, the invitation link, a workspace sign-up page, a mismatched confirmation, an admin's create-user route with a weak password (LC-AU15 is quarantined: D-30; LC-AU07 fixed on this branch: D-48) | @lifecycle, @core for AU08, @quarantine for 1 | 11 (10 default) | | auth/signin-session.spec.ts | LC-AU09 to AU14: unknown address, choosing among two workspaces, UI sign-out ends the server session, cookie lifetime, redirects of signed-in and anonymous visitors | @lifecycle, @core for AU11 | 6 | -| auth/password-recovery.spec.ts | LC-PW01 to PW15: the forgot page mails one reset link, the reset page sets the password from the link, a token works once, a new request kills the earlier token, a wrong or another user's token is refused, the answer hides whether an address has an account, the invitation mail from the dialog lets the addressee in (LC-PW08 D-34, PW09 D-56, PW10 D-57, PW11 D-58, PW12 D-54, PW14 D-18, PW15 D-55 quarantined). Trace off: the pages and requests carry tokens | @lifecycle, @core for PW02, @quarantine for 7 | 15 (8 default) | +| auth/password-recovery.spec.ts | LC-PW01 to PW16: the forgot page mails one reset link, the reset page sets the password from the link as mailed (PW02), a token works once, a new request kills the earlier token, a wrong or another user's token is refused, the answer hides whether an address has an account, the invitation mail from the dialog is opened as mailed and lets the addressee in with one slash before `invite/` (PW13), a reset to a weak password is refused and the token stays usable, the invite dialog's success notice is the exact localized text (PW15, fixed on this branch: D-55); PW08 fixed on this branch: D-34, PW12 fixed on this branch: D-54, PW16 fixed on this branch: D-48, all four Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`); PW09, PW10, PW11 and PW14 pass and run by default, PW11 fixed on this branch: D-58. Trace off: the pages and requests carry tokens | @lifecycle, @core for PW02 | 16 (16 default) | | auth/signup-disabled.spec.ts | LC-AU20 to AU24 on the sign-up-disabled stack: a sign-up through the API is refused (400 / 5003), the register page redirects to the sign-in page, the sign-in page and an invitation page offer no sign-up, an admin's create-user call is refused | @lifecycle, @signup-disabled | 5 (0 on the default stack) | -| auth/providers-config.spec.ts | LC-IP01 to IP05, IP07, IP08: an admin adds a GitHub provider in the UI, the workspace's sign-in page offers it, a disabled one leaves the page, a deleted one is gone, the last sign-in method cannot be switched off in the UI (notice and disabled button), a second configuration of one type is refused (LC-IP07 quarantined: D-61), the Generic form requires its issuer endpoint. LC-IP06 is not built (O-17) | @lifecycle, @quarantine for 1 | 7 (6 default) | -| auth/providers-login.spec.ts | LC-IP10 to IP15: sign-in through a mock Generic OAuth provider on the test's echo target (`POST /api/auth/tp/login` with a made-up code): a first sign-in creates the user (one token call with client id, secret and code, one user-info call with the bearer), the same provider user is the same account, registration off refuses an unknown user (400 / 5618), an error answer of the token endpoint fails the sign-in (500 / 5601), the profile binds an e-mail with which the user then signs in (LC-IP14 quarantined: D-62, an address that belongs to a form user signs in as that user) | @lifecycle, @quarantine for 1 | 6 (5 default) | -| account/profile.spec.ts | LC-PR01 to PR08, PR15: display name on the profile page and in the My Profile modal, an empty name refused, avatar upload, SVG refused, an oversized avatar (LC-PR06 quarantined: D-50), delete, UI language, status flags | @lifecycle, @quarantine for 1 | 9 (8 default) | -| account/password.spec.ts | LC-PR09 to PR14: password change in the modal, a wrong old password, the rule, a blank old password, replacing a password without the old one (LC-PR13 quarantined: D-49), a weak new password (LC-PR14 quarantined: D-48) | @lifecycle, @core for PR09, @quarantine for 2 | 6 (4 default) | -| account/other.spec.ts | LC-OT02 to OT05: the profile's "Info" count of created apps (LC-OT02 quarantined: D-63), a plain member's "Homepage (Org)" tab and missing settings against a developer's, an admin's member "Detail" popup, the admin sign-in page signs in any user | @lifecycle, @quarantine for 1 | 4 (3 default) | -| account/api-keys.spec.ts | LC-AK01 to AK08: a key created in the UI authenticates, the token is shown once and listed masked, a key deleted in the UI stops working, no key card for a plain member, a name is required, a key follows the user's current workspace, two keys of one second never share a token (LC-AK04 quarantined: D-45; LC-AK08: D-51, both fixed on the branch) | @lifecycle, @quarantine for 2 | 8 (6 default) | +| auth/providers-config.spec.ts | LC-IP01 to IP05, IP07, IP08: an admin adds a GitHub provider in the UI, the workspace's sign-in page offers it, a disabled one leaves the page, a deleted one is gone, the last sign-in method cannot be switched off in the UI (notice and disabled button), a second configuration of one type is refused (LC-IP07 passes on 3.0.1-e2e, which fixes it only partly: a request with a made-up `id` is not covered, D-61), the Generic form requires its issuer endpoint. LC-IP06 is not built (O-17) | @lifecycle | 7 | +| auth/providers-login.spec.ts | LC-IP10 to IP17: sign-in through a mock Generic OAuth provider on the test's echo target (`POST /api/auth/tp/login` with a made-up code): a first sign-in creates the user (one token call with client id, secret and code, one user-info call with the bearer), the same provider user is the same account, registration off refuses an unknown user (400 / 5618), an error answer of the token endpoint fails the sign-in (500 / 5601), the profile binds an e-mail with which the user then signs in (LC-IP14 passes and runs by default, fixed on this branch: D-62, an address that belongs to a form user no longer signs in as that user), a provider-only user cannot set a weak first password (LC-IP17 fixed on this branch: D-48) | @lifecycle | 7 | +| account/profile.spec.ts | LC-PR01 to PR08, PR15: display name on the profile page and in the My Profile modal, an empty name refused, avatar upload, SVG refused, an oversized avatar (LC-PR06 passes on 3.0.1-e2e: D-50 fixed), delete, UI language, status flags | @lifecycle | 9 | +| account/password.spec.ts | LC-PR09 to PR14: password change in the modal, a wrong old password, the rule, a blank old password, replacing a password without the old one (LC-PR13 fixed on this branch: D-49, Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)), a weak new password (LC-PR14 fixed on this branch: D-48) | @lifecycle, @core for PR09 | 6 | +| account/other.spec.ts | LC-OT02 to OT05: the profile's "Info" count of created apps (LC-OT02, fixed on this branch: D-63), a plain member's "Homepage (Org)" tab and missing settings against a developer's, an admin's member "Detail" popup, the admin sign-in page signs in any user | @lifecycle | 4 (4 default) | +| account/api-keys.spec.ts | LC-AK01 to AK08: a key created in the UI authenticates, the token is shown once and listed masked, a key deleted in the UI stops working, no key card for a plain member, a name is required, a key follows the user's current workspace, two keys of one second never share a token (LC-AK04 quarantined: D-45 is fixed but this UI test is intermittent on 3.0.1-e2e, 2 of 3 passed; LC-AK08 passes: D-51 fixed) | @lifecycle, @quarantine for 1 | 8 (7 default) | | workspace/members-gui.spec.ts | LC-WM01, WM03, WM04, WM06, WM12: the All Users group page (group roles, Remove from Group leaves the membership: O-16), the invite dialog's link lets a user in, a plain member has no settings and the API leave works, an unknown invitation code | @lifecycle, @core for WM04 | 5 | | workspace/workspaces-gui.spec.ts | LC-WM08 to WM11: Create Workspace in the avatar menu, switching, renaming, deleting with the exact name | @lifecycle | 4 | -| workspace/leave-removal.spec.ts | LC-DL01 to DL11: a removed member leaves the groups and loses its app grants (and does not get them back on rejoin), a leave cleans the same, an app of a removed developer stays with the workspace, a removed user keeps its account and own workspace, a user in no workspace is told 'User not found', deleting a workspace removes it for its members and its groups can no longer be read, its apps can no longer be opened, its invitation admits nobody (LC-DL03 D-59 and LC-DL04 D-60 quarantined) | @lifecycle, @quarantine for 2 | 11 (9 default) | -| workspace/groups-gui.spec.ts | LC-GR01 to GR10: create, rename (an empty name refused), delete (a deleted group's grant stays: D-53, LC-GR03), add members, group roles, remove, exit (the only group admin cannot), the built-in groups (LC-GR09: D-52), the developers group makes a developer | @lifecycle, @quarantine for 2 | 10 (8 default) | +| workspace/leave-removal.spec.ts | LC-DL01 to DL15: a removed member leaves the groups and loses its app grants (and does not get them back on rejoin), a leave cleans the same, an app of a removed developer stays with the workspace, a removed user keeps its account and own workspace, a user in no workspace is told 'User not found', deleting a workspace removes it for its members and its groups can no longer be read, its apps can no longer be opened, its invitation admits nobody; a removed member's bundle grant does not survive a rejoin (LC-DL12); the creator-shortcut candidates (LC-DL13 to LC-DL15, quarantined) assert the denial the member-leave clean-up does not give a removed/rejoined creator of an app, a folder and a bundle (D-26, D-60 residuals, an open scope question for the owner) | @lifecycle, @quarantine for 3 | 15 (12 default) | +| workspace/groups-gui.spec.ts | LC-GR01 to GR10: create, rename (an empty name refused), delete (a deleted group's grant no longer stays on 3.0.1-e2e: D-53 fixed, LC-GR03 passes), add members, group roles, remove, exit (the only group admin cannot), the built-in groups (a rename refused with UNSUPPORTED_OPERATION, D-52 fixed), the developers group makes a developer | @lifecycle | 10 (10 default) | | workspace/share-gui.spec.ts | LC-SH01 to SH06: the share dialog of the editor (add a viewer, change to editor, remove, the public switch, no Publish button for a non-owner editor) and the data source's Access Control (Can Use) | @lifecycle, @core for SH01 | 6 | | workspace/member-access.spec.ts | invited member sees only shared apps; invitation link flow | @core | 2 | | apps/public-app.spec.ts | public app renders for an anonymous visitor, a private one does not | @core | 1 | @@ -306,7 +310,7 @@ also carry `@superadmin` need both variables), `@superadmin` 5 (the four SEC-R16 | datasource/query-feeds-components.spec.ts | D1: query feeds text and table, owner-scoped writes re-read, chart renders | @core @slow @npm | 1 | | datasource/notes-queries.spec.ts | unit tests of the query builders | none | 4 | -### logic (21) +### logic (22) | File | Proves | Tags | Tests | |---|---|---|---| @@ -351,23 +355,25 @@ also carry `@superadmin` need both variables), `@superadmin` 5 (the four SEC-R16 | components/scenario-helpers.spec.ts | unit tests of `src/components/scenario.ts` | none | 5 | | components/simple-helpers.spec.ts | unit tests of `src/simple-components/seed.ts` | none | 9 | -### security (98 default; 47 more with `E2E_INCLUDE_QUARANTINE=1`; 4 more with `E2E_INCLUDE_SUPERADMIN=1`, SEC-R16c and R16d only with both variables; needs the stack) +### security (157 default; 4 more with `E2E_INCLUDE_QUARANTINE=1`; 4 more with `E2E_INCLUDE_SUPERADMIN=1`; needs the stack; measured 2026-11-24 from `e2e/`: `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list --grep @security` and the same with each opt-in variable) -Access-control tests, API level plus UI checks in SEC-R01a, R02a, R04a+, R05b, R06b, R06d+, R07a, R07c, R08d, R10b, R11a, R13, A06a, A11 and the UI rows of the cross-workspace tests (page objects `SettingPage`, `DatasourcePage`, `AppListPage`, `AppViewPage`, `EditorPage`; where a measurement contradicts the expected UI behaviour, the test encodes what was measured and says so). +Access-control tests, API level plus UI checks in SEC-R01a, R01e, R02a, R04a+, R05b, R06b, R06d+, R07a, R07c, R08d, R10b, R11a, R13, A06a, A11 and the UI rows of the cross-workspace tests (page objects `SettingPage`, `DatasourcePage`, `AppListPage`, `AppViewPage`, `EditorPage`; where a measurement contradicts the expected UI behaviour, the test encodes what was measured and says so). Titles are `SEC- `, tags `@security` (the P0 set also `@core`); each denial asserts HTTP status and `code` (`API_ERRORS`; exceptions: SEC-A10b, whose desired answer is only "no workspace id in the body", SEC-R15c, which accepts the two refusals of the folder grant but asserts one exact answer for the decisive step, and the rows that are not a denial, SEC-A11 to A13); the scenarios that try to change something also read the resource back with the owner's session (read-only scenarios assert a before control -and the denial). A scenario that asserts the desired behaviour and fails on the 3.0.0 image is `@quarantine` with the `defect` annotation -of `src/security/quarantine.ts` (`FIXED_ON_BRANCH`, `OPEN_DEFECTS`); a failure nobody expected is first a "candidate" (`securityCandidateDetails`, annotation ` candidate: ...`) until it gets a D id in the table "Security findings" below; none is open now. +and the denial). A scenario that asserts the desired behaviour and fails on the image under test (latest assessed: 3.0.1-e2e) is `@quarantine` with the `defect` annotation +of `src/security/quarantine.ts` (`OPEN_DEFECTS`; `FIXED_ON_BRANCH` holds only LC-AK04, an intermittent UI test of a fixed defect); a failure nobody expected is first a "candidate" (`securityCandidateDetails`, annotation ` candidate: ...`) until it gets a D id in the table "Security findings" below; none is open now. The P0 set is 22 of them, selected by id (repository root; the trailing space in the pattern keeps `SEC-C03` from matching `SEC-C03x`): `e2e/scripts/run-in-docker.sh --grep "SEC-(C01a|C02a|C03|C06|C12a|C12b|C14a|C16d|R01b|R02a|R02b|R02c|R03d|R03e|R06a|R07a|R10b|R10c|A01a|A03a|A06a|A07b) "`. -The set tests the 3.0.0 server and the 3.0.0 client of the image, not a pull request's client. +The set tests the server and the client of the image under test (3.0.0-e2e or 3.0.1-e2e), not a pull request's client. Outbound requests of the server (SEC-X01a to X01d, X02a, X02b; the HTTP echo sidecar of "Architecture"): the app is pointed at the test's own echo target and the echo's records are read back. SEC-X01 (`security/outbound.spec.ts`): an org admin points the workspace's npm registry at the echo (`setNpmRegistry`, a dummy bearer token `e2e-dummy-`); X01a+ is the positive control (the admin's `GET /api/npm/registry/{app}/e2e-pkg` reaches the echo with -the token), X01b and X01c (D-35, open) assert that an anonymous caller and a signed-in outsider are refused (4xx) and that nothing of their -call reaches the echo (both are asserted softly, so a failure reports both dimensions; each is shown after the admin's control call, so the echo can receive from that path), X01d+ shows that an anonymous -call on a PUBLIC app still reaches the echo (intended use: public apps load their npm components). SEC-X02 (`security/outbound-n8n.spec.ts`): an n8n data +the token), X01b and X01c (D-35, fixed on this branch: the proxy now needs READ on the app before resolving the workspace or forwarding anything) assert +that nothing of an anonymous caller's or a signed-in outsider's call reaches the echo, read before asserting the exact `{status: 401, code: 5001}` +denial (soft before hard, so a failure reports both dimensions; each is shown after the admin's control call, so the echo can receive from that path), +X01d+ shows that an anonymous call on a PUBLIC app still reaches the echo (intended use: public apps load their npm components), X01e+ shows that a +viewer of a host app loads a module's npm component through the HOST app id (the module's own id is refused directly). SEC-X02 (`security/outbound-n8n.spec.ts`): an n8n data source (`createN8nDatasource`, spec v1.1.1; X02b sets `forwardAllCookies: true`, the form's "Forward All Cookies") whose `serverURL` is the echo target and a saved query "Retrieve all workflows" (`n8nWorkflowsQuery`, recorded in `fixtures/dsl/n8n/`); X02a+ is the positive control (the literal marker parameter and the data source's key arrive), X02b (D-27, fixed on this branch's server) asserts, after a positive control that a benign cookie set in A's browser context does reach the echo, that the caller's session cookie value is in no record: the parameter is `{{LOWCODER_CE_SELFHOST_TOKEN}}` as the WHOLE value, because the 3.0.0 server puts every @@ -386,26 +392,28 @@ test put the login body, with the password, into the trace and the HTML report). SEC-R16a: `find e2e/test-results e2e/playwright-report -name '*.zip' -exec unzip -p {} \; | grep -a -c '"loginId":"e2e-superadmin@example.test"'` printed 1 when the test signed the super admin in through `page.request` (positive control) and 0 with the fixture alone. SEC-R16b also proves identity (the request context is signed in as the fixture user, which is a `super_admin` member of the workspace while a plain member is not), because on the 3.0.0 image any signed-in user can write a config key. A run started without the two variables fails the super-admin tests at once with an error naming both variables; other tests are unaffected. -LIMIT (D-47, measured on the 3.0.0 image, cause not found, HEAD not measured): once the stack holds more than about 420 workspaces every +LIMIT (D-47, measured on the 3.0.0 image; a code reading of 2026-11-22 found the cause and shows it fixed at HEAD, not re-measured at 450 workspaces; see the table "Security findings"): once the stack holds more than about 420 workspaces every request of the super admin hangs until the gateway answers 504 (400 workspaces: about 100 ms; 450: 120 to 240 s; an early session does not help). Each security test creates one to three workspaces, so `--repeat-each=10 tests/security` (about 1000 workspaces) failed SEC-R16a and R16b from the third repeat. Therefore the four SEC-R16 tests carry the tag `@superadmin`: they are out of the default run and of every -`@security` or P0 run, and run only with `E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin` (R16c and R16d also carry -`@quarantine` and then need `E2E_INCLUDE_QUARANTINE=1` too). Keep such runs short. +`@security` or P0 run, and run only with `E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin` (R16c and R16d also carried +`@quarantine` until 3.0.1-e2e; now they need only this variable). Keep such runs short. -ENTERPRISE stack (SEC-E01 to SEC-E06b, `E2E_STACK_PROFILE=enterprise`): the same image started with `LOWCODER_WORKSPACE_MODE=ENTERPRISE` +ENTERPRISE stack (SEC-E01 to SEC-E07b, `E2E_STACK_PROFILE=enterprise`): the same image started with `LOWCODER_WORKSPACE_MODE=ENTERPRISE` (`run-in-docker.sh` adds the variable; there is no compose file). Measured on the 3.0.0 image: the container hands both `LOWCODER_WORKSPACE_MODE` and the super-admin variables to the server. The super admin's own workspace is the ONE enterprise workspace OE (SEC-E01: its name is "'s workspace", a new user's only workspace is OE, role `member`, the super admin is `super_admin` there and has no other workspace). Creating a workspace is refused with 400 / 5003 (SEC-E06a), and the -lookup of workspaces by e-mail answers OE for a known and for an unknown address alike (SEC-E06b). OE has no admin but the super admin, so a test -signs up an actor and the super admin promotes it (`enterpriseAdmin`). True deactivation (SEC-E02 to E04): a removal by an admin marks the +lookup of workspaces by e-mail answers OE for a known and for an unknown address alike (SEC-E06b). An admin's password reset of another +member ends that member's sessions, and an admin's self-reset keeps only the session that asked for it (SEC-E07a, SEC-E07b, D-34). OE has +no admin but the super admin, so a test signs up an actor and the super admin promotes it (`enterpriseAdmin`). True deactivation (SEC-E02 to E04): a removal by an admin marks the user deleted (`markUserDeletedAndInvalidConnectionsAtEnterpriseMode`, state DELETED, connection sources renamed); measured: the removed user's session and API key answer 401 without a body at once, and signing in again with its password answers 403 / 5608 (`INVALID_PASSWORD`, the answer of -a wrong password; no session results, the context stays anonymous). SEC-E05 (D-40) resets the super admin's password on a server with the -defect, so it lives alone in `security/enterprise-takeover.spec.ts`, tagged `@enterprise-takeover`, and runs on a stack of its own: the tag is -left out of every run unless `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` is set (with the enterprise profile and `E2E_INCLUDE_QUARANTINE=1`), and a run with -the flag selects that one test only (`grep` is then `/@enterprise-takeover/`), so it cannot break other tests; measured: the reset answers 200. +a wrong password; no session results, the context stays anonymous). SEC-E05 (D-40, fixed on this branch) resets the super admin's password, +so it lives alone in `security/enterprise-takeover.spec.ts`, tagged `@enterprise-takeover`, and runs on a stack of its own: the tag is +left out of every run unless `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` is set (with the enterprise profile), and a run with +the flag selects that one test only (`grep` is then `/@enterprise-takeover/`), so it cannot break other tests; measured on this branch +(run 2026-11-23): the reset is refused. That file turns trace, screenshot and video off and passes no response body to any assertion, because the reset answer carries a new password Leak check, measured on the 3.0.0 image: the run `E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_ENTERPRISE_TAKEOVER=1 E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh` failed as expected (200 instead of 400 / 5003). A script searched `test-results/`, `playwright-report/` (zip archives unpacked) and the run log for the two new @@ -426,24 +434,25 @@ first makes sure some admin exists (accepting both answers), so none depends on | File | Proves | Tags | Tests | |---|---|---|---| -| security/enterprise.spec.ts | SEC-E01 (new users join the super admin's workspace as members), E02 and E03 (a removed user's session and API key stop at once), E04 (a removed user cannot sign in again), E06a (no second workspace), E06b (no account oracle in the e-mail lookup) | @security, @enterprise, @superadmin for E01 to E04 and E06a | 6, only with `E2E_STACK_PROFILE=enterprise` | -| security/enterprise-takeover.spec.ts | SEC-E05 (D-40): an admin resets the super admin's password; alone on its own stack | @security, @enterprise, @enterprise-takeover, @superadmin, @quarantine | 1, only with `E2E_STACK_PROFILE=enterprise`, `E2E_INCLUDE_QUARANTINE=1` and `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` | -| security/cross-org.spec.ts | cross-workspace rows (C01 to C22): another workspace's app, datasource, query, settings, roles, members, folders, groups, permission rows; 18 tests are `@quarantine` (C09, C10, C11, C13, C15, C16b, C16c, C16f, C17a, C17b, C17c, C18b, C19a, C19b, C20, C21, C22e) | @security, @core for 8 (the P0 rows), @quarantine for 18 | 24 default + 18 quarantined (C17c has an API and a UI test) | -| security/bundles.spec.ts | C23 (another workspace's bundle cannot be viewed, recycled, shared, reordered, published, renamed or created in; C23a and C23c `@quarantine`) and R17 (a developer's bundle: R17a+ positive, R17d viewer cannot recycle or delete, R17e editor cannot grant owner, R17f the creator's recycle; R17b, R17c and R17f `@quarantine`) | @security, @quarantine for 5 | 7 default + 5 quarantined | -| security/roles.spec.ts | R01 to R10: member without grant, viewer, editor, developer, plain member, anonymous visitor are held to their rights, the data source rows (R09), the workspace admin rows (R07, R08); R16: the instance super admin opens a private app's editing view and writes a config key (R16a, R16b), a workspace admin cannot demote or remove it (R16c D-23, R16d D-24); quarantined: R01d, R03b, R06c, R07d, R08c, R08d, R09c, R09d, R16c, R16d | @security, @core for the 10 P0 rows, @quarantine for 10, @superadmin for 4 (R16a to R16d) | 30 default + 8 quarantined + 2 `@superadmin` + 2 `@quarantine @superadmin` (R16c, R16d) | +| security/enterprise.spec.ts | SEC-E01 (new users join the super admin's workspace as members), E02 and E03 (a removed user's session and API key stop at once), E04 (a removed user cannot sign in again), E06a (no second workspace), E06b (no account oracle in the e-mail lookup), E07a and E07b (an admin's reset ends the member's sessions; a self-reset keeps the asking session and ends the others, D-34, Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)) | @security, @enterprise, @superadmin for E01 to E04, E06a, E07a, E07b | 8, only with `E2E_STACK_PROFILE=enterprise` | +| security/enterprise-takeover.spec.ts | SEC-E05 (D-40, fixed on this branch): an admin cannot reset the super admin's password; alone on its own stack | @security, @enterprise, @enterprise-takeover, @superadmin | 1, only with `E2E_STACK_PROFILE=enterprise` and `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` | +| security/cross-org.spec.ts | cross-workspace rows (C01 to C22): another workspace's app, datasource, query, settings, roles, members, folders, groups, permission rows; C16g+ (the app's editor may call the slug route), C16h (an unknown app id answers NO_RESOURCE_FOUND); 2 tests are `@quarantine` (C17c); C09, C10, C11, C13, C15, C16b, C16c, C16f, C16g+, C16h, C17a, C17b, C18b, C19a, C19b, C20, C21 and C22e pass and run by default (C09, C11, C19a, C19b and C22e fixed on this branch: D-7, D-6; C10 fixed on this branch: D-8; C16f, C16g+ and C16h fixed on this branch: D-37, the app slug route now needs EDIT_APPLICATIONS; C21 fixed on this branch: D-31; all four Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)) | @security, @core for 8 (the P0 rows), @quarantine for 1 | 41 default + 3 quarantined (C17c has an API and a UI test) | +| security/bundles.spec.ts | C23 (another workspace's bundle cannot be viewed, recycled, shared, reordered, published, renamed or created in; C23a and C23c pass on 3.0.1-e2e) and R17 (a developer's bundle: R17a+ positive, R17b a member whose own workspace is current cannot create a bundle in another workspace (D-11, D-41, fixed on this branch: the dev check now reads the target workspace, Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)), R17c viewer gets no editing DSL of an app it may not edit (D-42, Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)), R17d viewer cannot recycle or delete, R17e editor cannot grant owner, R17f the creator's recycle, R17g a public bundle's published view carries no app editing DSL, an anonymous caller is refused (401); only R17f `@quarantine`) | @security, @quarantine for 1 | 12 default + 1 quarantined | +| security/roles.spec.ts | R01 to R10: member without grant, viewer, editor, developer, plain member, anonymous visitor are held to their rights, the data source rows (R09), the workspace admin rows (R07, R08); R01d to R01g+: the app record route needs EDIT (member and viewer refused, the viewer still opens the published view; editor and workspace admin allowed, D-32, Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); R03f+: an owner of the app changes its status through the update route; R06c and R06e: a member whose own workspace is current cannot create an app or a data source in another workspace (D-11, D-41); R07d and R07e: no sign-in client secret in a member's workspace or profile answer (D-14); R16: the instance super admin opens a private app's editing view and writes a config key (R16a, R16b), a workspace admin cannot demote or remove it (R16c D-23, R16d D-24); no security test of this file is quarantined any more; R06c, R07d, R09d and R03b fixed on this branch (R06c: D-11, the dev check now reads the target workspace, not the visitor's current one; R07d: D-14; R09d: D-38, each data source of a batch is now decided in its own workspace, so it no longer borrows the admin role of E's own workspace and is no longer intermittent; R03b: D-9, a status change through the update route now needs MANAGE_APPLICATIONS, not just EDIT_APPLICATIONS; all four Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); R08c, R08d, R09c, R11b, R16c and R16d pass on 3.0.1-e2e | @security, @core for the 10 P0 rows, @superadmin for 4 (R16a to R16d) | 44 default + 0 quarantined + 4 `@superadmin` | +| security/draft-queries.spec.ts | R19 (D-10): R19a+ an app editor runs a draft-only query; R19b a viewer cannot run draft queries; R19c a host editor runs a module's published query, never its draft; R19d a host editor without a right on the module cannot run it through the host; R19e a never-published module's draft runs for a host editor who may read it, not in its own editor without edit | @security | 5 | | security/group-grants.spec.ts | R05 (group grants, a member removed from the group loses the right, UI after reload) and R14 (group administration) | @security | 6 | -| security/membership-changes.spec.ts | R11 to R13 (a removed member, a demoted admin, a removed permission row with a session open) and R15 (folder rights); quarantined: R11b, R15c | @security, @quarantine for 2 | 7 default + 2 quarantined | -| security/credentials.spec.ts | A01 to A05: forged, unsigned and wrongly signed tokens, API keys (a removed member's key, a member's key), logged-out and made-up cookies, forwarding headers; quarantined: A02a (D-45: the 3.0.0 server keeps the user's last API key after a delete), A04 | @security, @core for A01a and A03a, @quarantine for 2 | 7 default + 2 quarantined | -| security/mass-assignment.spec.ts | A06 to A08: a member cannot promote itself, an update cannot move an app or change its creator or public flag, a viewer's eight write routes (A08a to A08h); quarantined: A06b, A07a | @security, @core for A06a and A07b, @quarantine for 2 | 11 default + 2 quarantined | -| security/public-leakage.spec.ts | A09 and A10: what a public app and the session-free routes show an anonymous visitor (A09b and A09d are pins); quarantined: A09a, A09c, A10a, A10b, A10c | @security, @quarantine for 5 | 2 default + 5 quarantined | -| security/outbound.spec.ts | SEC-X01a to X01d: the npm registry proxy against the echo sidecar (X01a+ and X01d+ pass; X01b and X01c, D-35, `@quarantine`) | @security, @quarantine for 2 | 2 default + 2 quarantined | -| security/outbound-n8n.spec.ts | SEC-X02a and X02b: the n8n plugin's request against the echo sidecar (X02a+ passes; X02b, D-27, `@quarantine`); trace off for the file | @security, @quarantine for 1 | 1 default + 1 quarantined | -| security/collab-room.spec.ts | A11: a chat controller of another workspace joins the room of a private app (two browser sessions, the image's hocuspocus); `@quarantine` | @security, @quarantine | 1 quarantined | -| security/transport.spec.ts | A12 (CORS: a foreign origin is allowed with credentials, `@quarantine`) and A13 (session cookie flags) | @security, @quarantine for 1 | 1 default + 1 quarantined | +| security/membership-changes.spec.ts | R11 to R13 (a removed member, a demoted admin, a removed permission row with a session open) and R15 (folder rights); R11b passes on 3.0.1-e2e, R15c passes and runs by default, fixed on this branch: D-7 | @security | 9 | +| security/credentials.spec.ts | A01 to A05: forged, unsigned and wrongly signed tokens, API keys (a removed member's key, a member's key), logged-out and made-up cookies, forwarding headers; A04 fixed on this branch (D-34, Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); A02a passes on 3.0.1-e2e (D-45 fixed; the 3.0.0 server kept the user's last API key after a delete) | @security, @core for A01a and A03a | 9 default | +| security/mass-assignment.spec.ts | A06 to A08: a member cannot promote itself, an update cannot move an app or change its creator or public flag, a viewer's eight write routes (A08a to A08h); A06b and A07a pass on 3.0.1-e2e | @security, @core for A06a and A07b | 13 | +| security/public-leakage.spec.ts | A09 and A10: what a public app and the session-free routes show an anonymous visitor (A09b and A09d are pins); quarantined: A10b (A09a passes on 3.0.1-e2e; A09c, A10a and A10c are un-quarantined by this branch's fix, Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)) | @security, @quarantine for 1 | 6 default + 1 quarantined | +| security/outbound.spec.ts | SEC-X01a to X01e: the npm registry proxy against the echo sidecar (X01a+, X01d+ and X01e+ pass; X01b and X01c, D-35, fixed on this branch, Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`); X01e+: a module's npm component inside a host app loads through the host app id) | @security | 5 default | +| security/outbound-n8n.spec.ts | SEC-X02a and X02b: the n8n plugin's request against the echo sidecar (X02a+ and X02b pass; X02b, D-27, passes on 3.0.1-e2e); trace off for the file | @security | 2 | +| security/collab-room.spec.ts | A11: a chat controller of another workspace does not receive the room of a private app (two browser sessions, the image's hocuspocus); passes and runs by default, fixed on this branch: D-36 | @security | 1 | +| security/transport.spec.ts | A12 (CORS: a foreign origin is not allowed to read credentialed answers; passes and runs by default, fixed on this branch: D-33's CORS-credentials half) and A13 (session cookie flags) | @security | 2 | -Quarantined tests that behave unexpectedly on the 3.0.0 image: SEC-R09d is order-dependent (the batched data-source check; measured 8 failures and 2 passes in 10 repeats), so a quarantine run can show it passing. Accounting of `E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --workers=4 --reporter=list --grep "@quarantine" tests/security` (measured before the @superadmin tag existed, so it included SEC-R16c and R16d; they now need `E2E_INCLUDE_SUPERADMIN=1` as well): 44 listed, 43 failed, 1 passed (SEC-R09d), 0 skipped, 0 did not run; the two quarantined tests of `foundation/security-helpers.spec.ts` are outside that folder. +SEC-R09d (D-38) left the quarantine: the check took the workspace of the first id of a `HashSet`; each id is now decided in its own workspace (Java unit and MongoDB integration tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)). Accounting of the earlier 3.0.0 run `E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --workers=4 --reporter=list --grep "@quarantine" tests/security` (measured before the `@superadmin` tag existed and before the reassessment, so it listed 44 tests, 19 of which have since left the quarantine): 44 listed, 43 failed, 1 passed (SEC-R09d); the two quarantined tests of `foundation/security-helpers.spec.ts` are outside that folder. -### foundation (258, unit and builder tests; several touch the stack) +### foundation (264 default, 267 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) | File | Proves | Tags | Tests | |---|---|---|---| @@ -459,13 +468,13 @@ Quarantined tests that behave unexpectedly on the 3.0.0 image: SEC-R09d is order | foundation/products-table.spec.ts | products fixture and `TableView` | none | 2 | | foundation/table-view-header.spec.ts | header lookup is exact | none | 1 | | foundation/d3-threshold-reporter.spec.ts | D-3 gate verdicts of the reporter | none | 9 | -| foundation/security-helpers.spec.ts | the security helpers of `src/api/client.ts`, `src/security/actors.ts` and `src/security/scene.ts` against the stack (`apiRaw`, `actor`, `joinWorkspace`, `makeDeveloper`, grants, folders, datasources, API keys, bundles, `signIn`, `getApp`, `listGroupMembers`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `adminOfApiUser`, the `superAdmin` fixture, ...); 2 tests are `@quarantine` (D-45 API-key delete, D-46 bundle recycle) | none, @superadmin for 1, @quarantine for 2 | 36 default + 1 `@superadmin` + 2 quarantined | +| foundation/security-helpers.spec.ts | the security helpers of `src/api/client.ts`, `src/security/actors.ts` and `src/security/scene.ts` against the stack (`apiRaw`, `actor`, `joinWorkspace`, `makeDeveloper`, grants, folders, datasources, API keys, bundles, `publishBundle`, `setBundlePublicToAll`, `signIn`, `getApp`, `listGroupMembers`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `adminOfApiUser`, the `superAdmin` fixture, ...); 2 tests are `@quarantine` (D-45 API-key delete, D-46 bundle recycle) | none, @superadmin for 1, @quarantine for 2 | 37 default + 1 `@superadmin` + 2 quarantined | | foundation/security-pages.spec.ts | the page objects `SettingPage` (settings sidebar, members rows and role selects, provider page) and `DatasourcePage` (the form's save answer) as admin, developer and plain member, and `AppViewPage.openAndAwaitQuery` (the status of the query a seeded app runs on load) | none | 4 | | foundation/security-echo.spec.ts | the echo sidecar (`scripts/echo-server.js` started on a loopback port: record and read back, per-target prefixes, control paths, body cut, canned answers) and `src/security/echo.ts`, `n8nDatasourceBody`, `npmRegistryPath` (no stack) | none | 17 | -| foundation/security-api-raw.spec.ts | `apiRaw` against a local server: status, code, body, params, request and response headers (no stack) | none | 7 | +| foundation/security-api-raw.spec.ts | `apiRaw` against a local server: status, code, body, params, request and response headers; `executeAppQueryRaw`'s path (no stack) | none | 8 | | foundation/security-quarantine.spec.ts | `securityTestDetails`, `securityCandidateDetails`, `lifecycleTestDetails`, `lifecycleCandidateDetails` and the two quarantine maps (no stack) | none | 16 | | foundation/lifecycle-pages.spec.ts | `ProfilePage`, `ProfileModal`, `UserMenu` (profile, create and switch workspace), `ApiKeysCard`, `WorkspacesPage`, `GroupsPage`, `ShareDialog`, `SettingPage` (invite link, operations), `PasswordRecoveryPage`, `LoginPage.forgotPasswordLink`, the invite dialog of `SettingPage` (send, notice), `ProvidersPage`, `ProfilePage.infoCount`, `SettingPage.openDetailOf`, the navigation and tour locators of `AppListPage` (`tourClose` on a UI sign-up) | none | 14 | -| foundation/lifecycle-mail.spec.ts | `src/lifecycle/mail.ts` against the two recorded mails (`fixtures/mail/`) and built messages: encodings, charsets, nested multipart, encoded-word subjects, `resetTokenOf`, `inviteCodeOf`, the error types (no stack), `resetLinkOf` (cut at the token characters), `withSingleSlashes` | none | 13 | +| foundation/lifecycle-mail.spec.ts | `src/lifecycle/mail.ts` against the two recorded mails (`fixtures/mail/`) and built messages: encodings, charsets, nested multipart, encoded-word subjects, `resetTokenOf`, `inviteLinkOf`, the error types (no stack), `resetLinkOf` (cut at the token characters) | none | 13 | | foundation/lifecycle-mail-sink.spec.ts | the mail sink of `scripts/echo-server.js` on loopback ports with a raw SMTP client: a recorded conversation, case-insensitive match, dot-stuffing, 502, byte-by-byte commands, pipelining, a split terminator, RSET, 503, the over-long line, the body cut (also across writes, with the terminator split at the cut), `mailboxAt` (no stack) | none | 11 | | foundation/lifecycle-mail-stack.spec.ts | the sink on the stack: a reset request makes the server mail one reset link whose token the parser extracts | `@lifecycle` | 1 | | foundation/lifecycle-helpers.spec.ts | `registerRaw`, `signInRaw`, `updateProfile`, `deleteProfilePhoto`, `createOrganization`, `deleteOrganizationRaw`, `listAuthConfigs`, `addGithubConfigRaw`, `leaveOrganization`, the multipart option of `apiRaw`, `randomPng` | none | 7 | @@ -484,91 +493,89 @@ Quarantined tests that behave unexpectedly on the 3.0.0 image: SEC-R09d is order | D-3 | an edit made right after the editor opens can be lost; `EditorPage.open()` waits for `data-editor-ready` and `GRID_SETTLE_MS`, which narrows but does not close the race | tests that save through the editor poll the saved DSL; S1 and M3 retry once (below) | | D-5 | a component dropped right after ready is saved with width 0 | `GRID_SETTLE_MS` in `src/constants.ts`; `editor/drop-size.spec.ts` asserts the desired width and is `@quarantine` (no annotation) | | CD-3 | the timer's `start`/`resume` events and state do not reach bindings | `components/timer.spec.ts` asserts display text and the `pause` event only (no annotation) | -| CD-5 | an OBSERVATION, not a confirmed defect: `barChart1.data` reads empty while the chart draws the bound data | `components/npm-components.spec.ts` (bound barChart test) asserts today's `chart=0` and carries `{type:"defect", description:"CD-5"}`; `datasource/query-feeds-components.spec.ts` asserts the binding through a text | +| CD-5 | confirmed by code (2026-11-22 reading): the exposed `data` of `barChart` is hard-coded `func: (input) => []` (the same in 19 other charts); `barChart1.data` reads empty while the chart draws the bound data | `components/npm-components.spec.ts` (bound barChart test) asserts today's `chart=0` and carries `{type:"defect", description:"CD-5"}`; `datasource/query-feeds-components.spec.ts` asserts the binding through a text | | CD-7 | `setIn` with a bad path or on a scalar fails silently (query ends as success) | `logic/temporary-state.spec.ts` asserts today's behaviour, annotation `{type:"defect", description:"CD-7"}`, default run | -| CD-8 candidate | `transfer` list titles are in the wrong order | conditional `defect` annotation in `components/choices.spec.ts`; not confirmed as a defect yet | -| CD-9 candidate | an icon switched from a name to an image URL keeps the old icon | `components/displays.spec.ts`, `@quarantine`, `defect` annotation; not confirmed as a defect yet | +| CD-8 | `transfer` list titles are in the wrong order: confirmed by code (`titles={[targetTitle, sourceTitle]}`, 2026-11-22 reading) | conditional `defect` annotation in `components/choices.spec.ts` (the annotation still says candidate) | +| CD-9 | an icon switched from a name to an image URL keeps the old icon: confirmed (failed 3 of 3 on 3.0.1-e2e; code: the old icon is cached under the new URL and `undefined === undefined` keeps it) | `components/displays.spec.ts`, `@quarantine`, `defect` annotation (still named candidate there) | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | -| O-13 | observation: a mounted host never reloads a module that was republished under it while the module id is unchanged | `modules/module-versions.spec.ts` asserts the old version stays over `MOUNTED_HOST_OBSERVATION_MS` | +| O-13 | intended behaviour (code reading 2026-11-22: the module DSL is loaded once per app id): a mounted host never reloads a module that was republished under it while the module id is unchanged | `modules/module-versions.spec.ts` asserts the old version stays over `MOUNTED_HOST_OBSERVATION_MS` | | O-14 | observation: the chat controller's `messageSent` fires only when the answer succeeds, `messageReceived` fires either way | `components/chat.spec.ts` | -| O-15 | observation: the bound `connectionStatus` of the chat controller reads `Online` at its first read | `components/chat.spec.ts` uses a received frame as the signal of the connection | +| O-15 | intended behaviour (code reading 2026-11-22: the status is the socket transport state): the bound `connectionStatus` of the chat controller reads `Online` at its first read | `components/chat.spec.ts` uses a received frame as the signal of the connection | | O-16 | observation: the 3.0.0 client has no working page for a workspace's own members (`orgUsersPermission.tsx` is not routed): `/setting/permission/users` is the All Users group page with group roles, and its Remove from Group takes the user off that page but leaves the workspace membership; changing a workspace role or removing a member is API-only | `workspace/members-gui.spec.ts` LC-WM01, LC-WM03 (annotation `observation`) | | O-17 | observation: switching a workspace's e-mail sign-in off (`DELETE /api/auth/config/EMAIL` with a second provider present) answers 200 and ends the caller's session AND the instance super admin's (both answer 401 afterwards; the super admin is a member of every workspace and every worker shares its session), while an e-mail sign-in with and without the workspace id still answered 200 (measured on the image; whether the configuration was stored as disabled was not read back). A test of it would break the run, so LC-IP06 is not built; no test of the suite calls this route against the stack (LC-IP05 only reads the notice in the UI; the helper `removeAuthConfigRaw` is tested against a local server) | measured, not built | -| D-45 | on the 3.0.0 image `DELETE /api/auth/api-key/{id}` of the user's last key answers 200 but the key stays listed and keeps authenticating (fixed on the branch by `86fe43f9d`, NOT VERIFIED at runtime) | `security/credentials.spec.ts` SEC-A02a and the helper test in `foundation/security-helpers.spec.ts`, `@quarantine`, annotation `D-45`; LC-AK04 (the UI delete of the last key) | -| D-46 | on the 3.0.0 image recycling a bundle sets the status and answers 500 / 5005 (suspected open at HEAD, NOT VERIFIED) | `security/bundles.spec.ts` SEC-R17f and the helper test, `@quarantine`, annotation `D-46`; `recycleBundle` tolerates exactly this answer | +| D-45 | on the 3.0.0 image `DELETE /api/auth/api-key/{id}` of the user's last key answered 200 but the key stayed listed and kept authenticating; fixed on 3.0.1 (run 2026-11-22: SEC-A02a passes on lowcoder-ce:3.0.1-e2e and is in the default run) | `security/credentials.spec.ts` SEC-A02a (default run); the helper test in `foundation/security-helpers.spec.ts` is still `@quarantine`, annotation `D-45` (not part of the reassessment); LC-AK04 (the UI delete of the last key) is `@quarantine` because it is intermittent (2 of 3 passed; product or test not investigated) | +| D-46 | present, functional bug, cause: `BusinessEventPublisher` overload (after a successful recycle `BundleController` publishes an event through an overload that looks the bundle id up as an application and fails `NO_RESOURCE_FOUND`, answer 500 / 5005; still failing on 3.0.1-e2e, run 2026-11-22) | `security/bundles.spec.ts` SEC-R17f and the helper test, `@quarantine`, annotation `D-46`; `recycleBundle` tolerates exactly this answer | ## Security findings -Ids `D-6` to `D-47` are the defects the security tests use (annotation `{ type: "defect", description: "D-n" }`, and the maps `FIXED_ON_BRANCH` and -`OPEN_DEFECTS` of `src/security/quarantine.ts`). Status: `open` = present in the 3.0.0 image and in the code of this branch; -`fixed on branch` = present in the 3.0.0 image, fixed in this branch's server by the named commit (the image under test still has it, so the -test is `@quarantine`; it leaves the quarantine by deleting its id from `FIXED_ON_BRANCH` once a run against an updated server passes it); -`suspected` = read in the code, the runtime behaviour is not established. D-45, D-46 and D-47 were found by running tests; the other -findings were read in the code and each scenario asserts the desired behaviour. "pin" means the test asserts the current good behaviour +Ids `D-6` to `D-63` are the defects the security and lifecycle tests use (annotation `{ type: "defect", description: "D-n" }`, and the maps `FIXED_ON_BRANCH` and +`OPEN_DEFECTS` of `src/security/quarantine.ts`). Status as of the reassessment of 2026-11-22 (runtime on `lowcoderorg/lowcoder-ce:3.0.1-e2e` plus a code reading of the working tree at `9938649b1`): +`open` = present on 3.0.1-e2e and in the code, the test is `@quarantine`; `fixed on 3.0.1` = the test passed on 3.0.1-e2e, so it left the quarantine and is in the default run (the earlier commit hashes of "fixed on branch" are not in `dev`'s history, the fixes are there as rebased commits with other hashes, so they are no longer cited); `present (code read, firm)` = the code reading shows the flaw, no runtime failure of its own test beyond the quarantined one. D-45, D-46 and D-47 were found by running tests; the other +findings were read in the code and each scenario asserts the desired behaviour. Rows whose test passes on 3.0.1 say only that the test passes; where the code reading found a limit, the row says so. "pin" means the test asserts the current good behaviour and passes. | Id | Finding | Status | Scenarios | |---|---|---|---| -| D-6 | an admin of any workspace renames any user or replaces or deletes their photo (the route checks the admin role of the path's workspace, not that the user belongs to it) | open | SEC-C19a, C19b | -| D-7 | any workspace admin renames another workspace's folder and grants permissions on it; a plain member can escalate inside a workspace through folder grants copied onto later apps | open | SEC-C09, C11, C22e, R15c | -| D-8 | any signed-in user reads the permission list of any folder | open | SEC-C10 | -| D-9 | an app editor sets the app's status (recycled, deleted) through the update route, which needs only edit rights | suspected | SEC-R03b | -| D-10 | viewers, and anonymous visitors of public apps, run unpublished (draft) queries | suspected | SEC-A09c | -| D-11 | a plain member creates apps in a workspace when it is a developer in its current workspace | suspected | SEC-R06c | -| D-12 | anonymous callers resolve names of apps, users, workspaces and more by id (`POST /api/meta/`) | open | SEC-A10a | +| D-6 | an admin of any workspace renames any user or replaces or deletes their photo (the route checks the admin role of the path's workspace, not that the user belongs to it); code reading: the answer is the victim's profile view with live session tokens and their workspaces with OAuth `clientSecret`, so with D-58 it is an account takeover by any signed-in user, severity higher than first rated | fixed on this branch (run 2026-11-23 on an image rebuilt from this branch's working tree: SEC-C19a and SEC-C19b pass and are in the default run) | SEC-C19a, C19b | +| D-7 | any workspace admin renames another workspace's folder and grants permissions on it; a plain member can escalate inside a workspace through folder grants copied onto later apps | fixed on this branch (run 2026-11-23 on an image rebuilt from this branch's working tree: SEC-C09, C11, C22e and R15c pass and are in the default run) | SEC-C09, C11, C22e, R15c | +| D-8 | any signed-in user reads the permission list of any folder | fixed on this branch (Java unit and Spring+Mongo tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); residual: a folder id or gid that names no folder still gets a different answer (NO_RESOURCE_FOUND, or FOLDER_NOT_EXIST for a gid) than a folder of another workspace (NOT_AUTHORIZED), as on the other folder routes | SEC-C10 | +| D-9 | an app editor sets the app's status (recycled, deleted) through the update route, which needs only edit rights | fixed on this branch (Java unit tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); a status change through the update route needs the owner right like recycle; an editor still updates name and DSL (SEC-R03a+); an owner can still set any status directly, DELETED without recycling first, as before | SEC-R03b, R03f+ | +| D-10 | viewers, and anonymous visitors of public apps, run unpublished (draft) queries | fixed on this branch (Java unit tests green 2026-11-23; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); in another app's editor a module's queries run its published version; residual: an app or module that was never published has its draft as its live version, so READ on it runs that draft | SEC-A09c, R19a+ to R19e | +| D-11 | a plain member creates apps or data sources in a workspace when it is a developer in its current workspace | fixed on this branch (Java unit tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); app, bundle (D-41) and data source creation now check the developer role in the TARGET workspace (the request's `orgId`), not the visitor's current one | SEC-R06c, R06e | +| D-12 | anonymous callers resolve names of apps, users, workspaces and more by id (`POST /api/meta/`) | fixed on this branch (Java unit test green 2026-11-23; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); residual: any signed-in user still resolves the names, and for users the e-mail addresses, of any id in any workspace (D-12) | SEC-A10a | | D-13 | anonymous callers list the workspaces of any e-mail address (`GET /api/organizations/byuser/{email}`) | open | SEC-A10b | -| D-14 | the workspace answer carries the auth configs' client secret | open | SEC-R07d | +| D-14 | the workspace answer carries the auth configs' client secret | fixed on this branch (Java unit tests green: `OrganizationJsonTest`, `OrganizationEndpointsContractTest`, `UserEndpointsContractTest`, `ApplicationEndpointsContractTest`, `AuthenticationEndpointsContractTest`; `Organization#getAuthConfigs` is `@JsonIgnore`, so no answer that holds an `Organization` writes the auth configs; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); residual: the workspace answer (`GET /api/organizations/{id}`) and the app home page (`GET /api/applications/home`) still give every member the workspace's full common settings, the npm registry credential and the password-reset template included (the profile drops those two) | SEC-R07d, SEC-R07e | | D-15 | API keys are signed with a published default secret; a forged token is refused only because it must equal a stored key | open, defended (pin) | SEC-A01a | -| D-16 | any signed-in user writes deployment-wide server config | fixed on branch (`24295707f`) | SEC-R08c (positive half SEC-R16b) | -| D-17 | library queries of other workspaces can be read and run | fixed on branch (`e84499a0b`) | SEC-C15 | -| D-18 | any signed-in user invites itself into any workspace | fixed on branch (`2ae399ef2`) | SEC-C17a, C17b, LC-PW14 (the invitation mail of another workspace) | -| D-19 | folder create with a client-chosen id replaces another workspace's folder | fixed on branch (`f3e4b2908`) | SEC-A07a | -| D-20 | a query naming its datasource by gid skips the use permission | fixed on branch (`a8e6531ec`) | SEC-R09c | -| D-21 | any signed-in user lists any app's versions | fixed on branch (`f698f98ef`) | SEC-C20 | -| D-22 | any signed-in user lists any workspace's users through a group id | fixed on branch (`3eb3c4a05`) | SEC-C18b | -| D-23 | a workspace admin grants `super_admin` or changes a super admin's role | fixed on branch (`bf53d64b9`) | SEC-A06b, R16c | -| D-24 | an admin removes a super admin or the last admin | fixed on branch (`928d02040`) | SEC-R08d, R16d | -| D-25 | app views, the anonymous view of a public app included, carry the workspace's password-reset mail template | fixed on branch (`7f2b48e4a`) | SEC-A09a | -| D-26 | an app's creator who left the workspace, and any user on a template app, open the editing view | fixed on branch (`c377186ad`) | SEC-R11b | -| D-27 | the session cookie is forwarded to JS datasource queries | fixed on branch (`f4fc9f3ec`) | SEC-X02b | -| D-28 | any signed-in user sets any workspace's slug and reads any workspace | fixed on branch (`22e4419b1`, `893e7ebd0`) | SEC-C16b, C16c | -| D-29 | any signed-in user reads any datasource's structure and makes it connect | fixed on branch (`fe745f3bd`) | SEC-C13 | -| D-30 | signing in with `?orgId=` joins that workspace without an invitation (may be intended for the per-workspace sign-in page; needs an owner decision) | suspected | SEC-C17c | -| D-31 | an editor of any app reads any history snapshot by id | open | SEC-C21 | -| D-32 | any workspace member reads the full live DSL of any of its apps | open | SEC-R01d | -| D-33 | credentialed CORS from any origin with CSRF protection off (default allowed origins `*`) | open | SEC-A12 (`@quarantine`), SEC-A13 (pin) | -| D-34 | sessions survive a password change | open | SEC-A04, LC-PW08 (a password reset), `@quarantine` | -| D-35 | anonymous callers use any app's workspace npm registry settings | open | SEC-X01b, X01c | -| D-36 | the collaboration server checks neither the user nor the room | open | SEC-A11 | -| D-37 | the app slug route has no permission check (latent while no slug is stored) | open | SEC-C16f | -| D-38 | a batched permission lookup takes the workspace and the admin role from the first id | suspected | SEC-R09d | -| D-39 | actuator metrics (`/api/status/**`) are anonymous | open | SEC-A10c | -| D-40 | in ENTERPRISE mode a workspace admin resets the instance super admin's password and receives it | open (measured on the 3.0.0 image: the reset answers 200 and the password) | SEC-E05 (`security/enterprise-takeover.spec.ts`, alone on its own enterprise stack) | -| D-41 | a plain member creates bundles in a workspace when it is a developer in its current workspace | suspected | SEC-R17b | -| D-42 | a bundle's element list carries the editing DSL of every app in it, with no check on the apps | open | SEC-R17c | -| D-43 | any signed-in user lists any bundle's elements, each app's editing DSL included | fixed on branch (`bd6308331`) | SEC-C23a | -| D-44 | an app's owner adds or moves it into any bundle of any workspace | fixed on branch (`a63df54ac`) | SEC-C23c | -| D-45 | deleting a user's last API key answers 200 but the key stays listed and keeps authenticating (measured on the image) | fixed on branch (`86fe43f9d`, not verified at runtime on the branch) | SEC-A02a, LC-AK04 and the helper test in `foundation/security-helpers.spec.ts` | -| D-46 | recycling a bundle sets the status and then answers 500 / 5005 (measured on the image) | suspected open on the branch (not verified at runtime) | SEC-R17f and the helper test; `recycleBundle` tolerates exactly this answer | -| D-47 | the instance super admin's requests hang (HTTP 504) once the stack holds more than about 420 workspaces (measured on the 3.0.0 image: 400 ok in about 100 ms, 450 and more 504 after about 120 s; cause not found) | open, cause not found, measured on 3.0.0, HEAD not measured | SEC-R16a to R16d, tagged `@superadmin` | -| D-48 | the server enforces no password rule on sign-up (the rule, at least 8 characters with a letter and a digit, is checked in the client only): a sign-up with the password `a` answers 200 and opens a session, and so does `PUT /api/users/password` with the new password `a` (measured on the image; the same code at HEAD, not run) | open (candidate L-3 of the lifecycle research) | LC-AU07, LC-PR14, `@quarantine` | -| D-49 | `POST /api/users/password?password=` sets a password with no old password for a user who already has one (the route of the "Set Password" card); any session, a stolen one included, replaces the password and takes the account (measured on the image; HEAD the same by code, not run) | open (candidate L-2) | LC-PR13, `@quarantine` | -| D-50 | the avatar size limit (`avatarMaxSizeInKb`, 300) is not enforced: a 6.7 MB PNG is accepted (measured on the image; HEAD not run) | open, not verified at HEAD | LC-PR06, `@quarantine` | -| D-51 | an API-key token is the user id and the second it was created in (no unique id): two keys of one user created in the same second are the same token, so deleting one of them does not revoke it (measured on the image: back-to-back keys collide) | fixed on branch (`0da2e7f76`, a random `jti` in every new key token; not verified at runtime) | LC-AK08, `@quarantine`; LC-AK03 creates its second key in a later second to avoid it | -| D-52 | `PUT /api/groups/{id}/update` renames the all-users group (measured on the image) and, by the same code, the developers group (not measured): the rename has no system-group check, the UI only hides the control (HEAD unchanged by the commit log) | open | LC-GR09, `@quarantine` | -| D-53 | deleting a group leaves its members the access the group granted: a member of a deleted group still views the app the group was granted on, 30 s after the delete (measured on the image; HEAD unchanged by the commit log) | open | LC-GR03, `@quarantine` | -| D-54 | the reset link of the mail has a double slash (`//user/auth/lost-password?token=...`, because the public URL, in the shipped default too, ends in a slash) and the client opens a blank page for it; the same link with one slash opens the reset form (measured on the image; the link is built in `EmailCommunicationServiceImpl`, HEAD unchanged by the commit log) | open | LC-PW12, `@quarantine` | -| D-55 | the invite dialog confirms with a raw translation key (`oups! membersSettings.inviteByEmailSuccess`): the client asks for keys that do not exist (`inviteDialog.tsx`, HEAD unchanged by the commit log) | open | LC-PW15, `@quarantine` | -| D-56 | the password-reset mail ignores the workspace's own template (the template is read with the wrong key; measured on the image: the marker of a stored template is absent) | fixed on branch (`adfe89327`; not run at HEAD) | LC-PW09, `@quarantine` | -| D-57 | an account in no workspace gets no reset mail while the forgot page still confirms (measured on the image: a member removed from its only workspace gets none) | fixed on branch (`49e759ed9`; not run at HEAD) | LC-PW10, `@quarantine` | -| D-58 | a reset request for a display name that is not an address mails that user's token to the typed text: whoever can rename a user sets the victim's name to an address of its own and receives the victim's token (measured on the image: the alias received a mail; the reset itself was not run; HEAD code read, `UserServiceImpl.java:437`) | open | LC-PW11, `@quarantine` | -| D-59 | a removed developer's data source grant is not deleted: 20 s after the removal the "Can Use" row of the data source was still there, while the group and app rows were gone within 40 ms (measured on the image; HEAD not run) | open, not verified at HEAD | LC-DL03, `@quarantine` | -| D-60 | a removed member's folder grant is not deleted and is live again after a rejoin: the removal listener has no folder step, and the row was still there after the removal and after the rejoin (measured on the image; HEAD listener read: no folder or bundle step) | open | LC-DL04, `@quarantine` | -| D-61 | a second sign-in configuration of a provider type that already has one is accepted: a second GitHub configuration with another client id answers 200 and the workspace lists two (the server code names the refusal 400 / 5621 `DUPLICATE_AUTH_CONFIG_ADDITION`; measured on the image, HEAD not run) | open, not verified at HEAD | LC-IP07, `@quarantine` | -| D-62 | a provider sign-in whose e-mail claim equals an existing account's address signs in AS that account: the server resolves the provider identity by address (`UserServiceImpl.findByAuthUserRawId` is `findByEmailDeep`, the claim is not verified), so whoever configures a provider for a workspace can make its user-info answer name any address and receive that user's session, including users of other workspaces; measured on the image with a mock provider: the session listed the form user's own workspace (HEAD code read: unchanged) | open | LC-IP14, `@quarantine` | -| D-63 | the "Info" card "Your Created Apps" of the profile page counts 0 although the user created two apps (`createBy` of the list equals the user's name and the app list shows them; the page filters the redux app list, `UserProfileLayout.tsx`; root cause NOT VERIFIED); measured on the image, HEAD not run | open, not verified at HEAD | LC-OT02, `@quarantine` | +| D-16 | any signed-in user writes deployment-wide server config | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | SEC-R08c (positive half SEC-R16b) | +| D-17 | library queries of other workspaces can be read and run | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | SEC-C15 | +| D-18 | any signed-in user invites itself into any workspace | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | SEC-C17a, C17b, LC-PW14 (the invitation mail of another workspace) | +| D-19 | folder create with a client-chosen id replaces another workspace's folder | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | SEC-A07a | +| D-20 | a query naming its datasource by gid skips the use permission | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run); partial: the gid case is fixed only on app update, app create stores the DSL without the use check and running a query checks only READ on the app (code read, not run; N-4) | SEC-R09c | +| D-21 | any signed-in user lists any app's versions | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run); fixed for other workspaces, inside a workspace the gate is membership only (severity low-medium) | SEC-C20 | +| D-22 | any signed-in user lists any workspace's users through a group id | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | SEC-C18b | +| D-23 | a workspace admin grants `super_admin` or changes a super admin's role | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | SEC-A06b, R16c | +| D-24 | an admin removes a super admin or the last admin | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | SEC-R08d, R16d | +| D-25 | app views, the anonymous view of a public app included, carry the workspace's password-reset mail template | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run); partial: fixed for the password-reset template only, `sanitized()` still leaves the workspace's `npmRegistries` setting with its credentials in the published view that an anonymous visitor of a public app receives (code read, N-1) | SEC-A09a | +| D-26 | an app's creator who left the workspace, and any user on a template app, open the editing view | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run); fixed for editing, a creator outside the workspace keeps READ through the creator-shortcut VIEWER row (`createdBy`), a separate, unrevoked mechanism from the member-leave clean-up's stored-row deletion (D-60 residual, LC-DL13 quarantined candidate, an open scope question for the owner) | SEC-R11b | +| D-27 | the session cookie is forwarded to JS datasource queries | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | SEC-X02b | +| D-28 | any signed-in user sets any workspace's slug and reads any workspace | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | SEC-C16b, C16c | +| D-29 | any signed-in user reads any datasource's structure and makes it connect | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run); fixed for the structure read, the sibling `GET /api/datasources/info` has no check (code read, N-2) | SEC-C13 | +| D-30 | signing in with `?orgId=` joins that workspace without an invitation (may be intended for the per-workspace sign-in page; needs an owner decision) | present, by design upstream (`tryAddUserToOrgAndSwitchOrg` has no condition and the admin page publishes the per-workspace sign-in URL; what is missing is an admin opt-in), severity medium | SEC-C17c | +| D-31 | an editor of any app reads any history snapshot by id | fixed on this branch (Java unit tests green: `ApplicationHistorySnapshotServiceImplTest`, `ApplicationHistorySnapshotEndpointsTest`, `ApplicationHistorySnapshotEndpointsContractTest`, `PayloadContractCompletenessTest`; both DSL routes now resolve the path key once with `findByIdWithoutDsl`, check EDIT on the resolved object id, and serve a snapshot only when its stored `applicationId` equals that object id and either it carries the `applicationIdResolved` marker the create route now writes, or, for a snapshot stored before this fix, the path's application was created strictly before the snapshot; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); residual: a snapshot's DSL may name modules of any workspace and both snapshot routes answer those modules' live DSL (code read, not run); residual: a snapshot saved before this fix through a slug set to exactly another app's id while a lookup still asked for the slug first (same workspace or a different one) is still served through that other app, if that other app was created strictly before the snapshot (code read, not run); residual: the creation-order check compares server wall-clock timestamps, not a monotonic order, so clock skew between nodes could still admit a colliding app's snapshot even outside the slug-first case above; changed: a new snapshot is stored under the app's id even when created through its gid or slug, and listed through that id; a snapshot saved before this fix under an app's gid or slug instead of its id (only a workspace admin can save one, through the API) is still listed through that key but no longer served; one saved before this fix under the app's id is served only when the app was created strictly before the snapshot (both creation times present) | SEC-C21 | +| D-32 | any workspace member reads the full live DSL of any of its apps | fixed on this branch (Java unit tests green: `ApplicationRecordApiServiceImplTest`; the app record route, live or a named version, now needs `EDIT_APPLICATIONS` on the record's own application, checked after the workspace match; an empty visitor id is refused; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); not changed: the version list still needs only workspace membership (D-21 residual) and the version delete only the developer role and the workspace | SEC-R01d, SEC-R01e, SEC-R01f+, SEC-R01g+ | +| D-33 | credentialed CORS from any origin with CSRF protection off (default allowed origins `*`) | CORS-credentials half fixed on this branch (run 2026-11-23: `SecurityConfig` grants credentials only to an origin listed in a non-wildcard `LOWCODER_CORS_DOMAINS` entry; SEC-A12 passes and is in the default run; four new Java tests cover the wildcard-only, single-listed-origin, wildcard-sub-pattern and mixed-configuration cases); CSRF and `SameSite=None` on HTTPS remain open, so a cross-site SIMPLE request (a plain HTML form submit, which needs no credential grant) still reaches a route shaped to accept one, e.g. `POST /api/users/password?password=...` | SEC-A12, SEC-A13 (pin) | +| D-34 | sessions survive a password change | fixed on this branch (Java unit tests green: `SessionUserServiceImplEndSessionsTest`, `UserApiServiceImplResetPasswordTest`, `UserApiServiceImplResetLostPasswordTest`, `InvitationAndUserApiServiceTest`, `UserEndpointsContractTest`, `UserServiceImplPasswordTest`, `EmailBackfillEndToEndTest`; a password change ends every other session of the user and keeps the caller's, a lost-password reset ends every session, an ENTERPRISE admin reset ends every session of the target and keeps the caller's only when the caller reset its own password; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); residuals: API keys are not revoked; a sign-in that checked the old password while the password changes can keep its session or write the old hash back, and a session whose token a concurrent whole-document save of the user dropped from the stored token list is not found (both need targeted token and password writes in the shared sign-in path); when a session cannot be ended the request answers PASSWORD_CHANGED_SESSIONS_NOT_ENDED 500 / 6202 although the password has changed | SEC-A04, LC-PW08 (a password reset), SEC-E07a, SEC-E07b (ENTERPRISE admin reset) | +| D-35 | anonymous callers use any app's workspace npm registry settings | fixed on this branch (Java unit tests green 2026-11-23; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); the proxy now needs READ on the app before resolving the workspace or forwarding anything; a module's npm component inside a host app uses the host app id, SEC-X01e+; by design, anyone who may read an app (anonymous visitors of a public app included) still uses its workspace's registry through the proxy | SEC-X01b, X01c, X01e+ | +| D-36 | the collaboration server checks neither the user nor the room | fixed on this branch (`hocuspocus-server.js` now checks the room's app permission; run 2026-11-23 on an image rebuilt from this branch's working tree with the hocuspocus websocket URL baked in: SEC-A11 passes and is in the default run, and a new two-viewer round-trip test, `components/chat.spec.ts` "two viewers in the same room: each one's share reaches the other", confirms real cross-client relay still works) | SEC-A11 | +| D-37 | the app slug route has no permission check (latent: the domain write is not reached while its slug-exists query completes empty, `ApplicationRepository.java:76-77`) | fixed on this branch (Java unit tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); the route needs EDIT on the app; an id that names no app answers NO_RESOURCE_FOUND; the slug write itself still stores nothing (functional, not security); a signed-in visitor tells an unknown app id (500/5005) from a refused one (401/5001), as on every app route that resolves the app's workspace in the check | SEC-C16f, C16g+, C16h | +| D-38 | a batched permission lookup takes the workspace and the admin role from the first id | fixed on this branch (Java unit and MongoDB integration tests green 2026-11-24: each id of a batch of two or more is now decided in its own workspace, including `datasourcesOfTwoWorkspaces_adminRoleElsewhereGrantsNothing`, the test that reproduces this defect's own repro against real MongoDB; the one-id contract is unchanged; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`): SEC-R09d confirmed passing in the default run, no longer intermittent) | SEC-R09d | +| D-39 | actuator metrics (`/api/status/**`) are anonymous | fixed on this branch (Java unit test green 2026-11-23; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); `/api/status/health` stays anonymous; residual: any signed-in user still reads the metrics, and a Prometheus scraper that read `/api/status/prometheus` anonymously now needs an API key (not yet measured whether that key works as a bearer token) (D-39) | SEC-A10c | +| D-40 | in ENTERPRISE mode a workspace admin resets the instance super admin's password and receives it | fixed on this branch (run 2026-11-23, `E2E_STACK_PROFILE=enterprise` on an image rebuilt from this branch's working tree: SEC-E05 passes, alone on its own enterprise stack; SEC-E05 left `OPEN_DEFECTS` and no longer needs `E2E_INCLUDE_QUARANTINE`, but still needs `E2E_INCLUDE_ENTERPRISE_TAKEOVER` (`@enterprise-takeover`, a separate opt-in from the quarantine maps)) | SEC-E05 (`security/enterprise-takeover.spec.ts`, alone on its own enterprise stack) | +| D-41 | a plain member creates bundles in a workspace when it is a developer in its current workspace | fixed on this branch (Java unit tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); see D-11, the same fix | SEC-R17b | +| D-42 | a bundle's element list carries the editing DSL of every app in it, with no check on the apps; adding an app to a bundle copies its editing DSL into the bundle's DSL, and publishing copies it into the published DSL | partly fixed on this branch (Java unit tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`): SEC-R17c and SEC-R17g confirmed passing in the default run). The element list carries an app's editing DSL only to a reader who may edit that app, and an app added to or moved into a bundle is stored without its editing DSL. Residual: bundle DSLs written before the fix keep each app's editing DSL as it was when the app was added; the bundle's views answer those copies to every reader of the bundle and, once the bundle is public to all, to any signed-in user of any workspace; re-adding the app or republishing the bundle does not remove them. By code an anonymous caller is refused (401) before any bundle code runs (`/api/**` requires authentication); confirmed by the combined run (2026-11-24, image `secfix-combined-e2e`) | SEC-R17c, SEC-R17g | +| D-43 | any signed-in user lists any bundle's elements, each app's editing DSL included | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | SEC-C23a | +| D-44 | an app's owner adds or moves it into any bundle of any workspace | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | SEC-C23c | +| D-45 | deleting a user's last API key answered 200 but the key stayed listed and kept authenticating (measured on the 3.0.0 image) | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run); LC-AK04 (UI delete) is intermittent and stays `@quarantine` | SEC-A02a, LC-AK04 and the helper test in `foundation/security-helpers.spec.ts` | +| D-46 | recycling a bundle sets the status and then answers 500 / 5005 (measured on the image) | present, functional bug, cause: `BusinessEventPublisher` overload (500 / 5005 after a successful recycle, still failing on 3.0.1-e2e; restore should fail the same way, not run); not a security finding | SEC-R17f and the helper test; `recycleBundle` tolerates exactly this answer | +| D-47 | the instance super admin's requests hang (HTTP 504) once the stack holds more than about 420 workspaces (measured on the 3.0.0 image: 400 ok in about 100 ms, 450 and more 504 after about 120 s; cause not found) | fixed in code, not re-measured (cause found: `getCurrentOrgMember` filtered a cached membership list whose condition collected the same list; reactor-core stalls above 448 memberships, a Java probe reproduces it; HEAD collects first; a 450-workspace run against the image was not done; the same pattern remains in the workspace data source list and the library query list); SEC-R16a to R16d pass | SEC-R16a to R16d, tagged `@superadmin` | +| D-48 | the server enforces no password rule on sign-up (the rule, at least 8 characters with a letter and a digit, is checked in the client only): a sign-up with the password `a` answers 200 and opens a session, and so does `PUT /api/users/password` with the new password `a` (measured on the image; the same code at HEAD, not run) | fixed on this branch (Java unit tests green: `PasswordRuleTest`, `FormAuthRequestTest`, `UserEndpointsContractTest`, `UserCreateInOrgPasswordRuleTest` against real MongoDB; a password a user chooses on sign-up, an admin's create-user route, a password change, a lost-password reset or a first password that breaks the client's rule is refused with `INVALID_PASSWORD` 403 / 5608 before anything is stored or a session opened; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); residual: existing weak passwords keep working (no forced rotation); the super admin password from the environment and server-generated passwords are exempt | LC-AU07, LC-PR14, LC-AU17, LC-PW16, LC-IP17 | +| D-49 | `POST /api/users/password?password=` sets a password with no old password for a user who already has one (the route of the "Set Password" card); any session, a stolen one included, replaces the password and takes the account (measured on the image; HEAD the same by code, not run) | fixed on this branch (Java unit tests green: `UserServiceImplPasswordTest`, `UserEndpointsContractTest`, the new `UserSetPasswordIfAbsentMongoTest` against real MongoDB; the route answers `INVALID_PASSWORD` 403 / 5608 for an account that already has a password, decided and written in one conditional MongoDB update that is race-proof under concurrent requests; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)); residual: the route still accepts a cross-site form post for an account WITHOUT a password (CSRF open, D-33 row) | LC-PR13 | +| D-50 | the avatar size limit (`avatarMaxSizeInKb`, 300) is not enforced: a 6.7 MB PNG is accepted (measured on the image; HEAD not run) | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | LC-PR06 (default run) | +| D-51 | an API-key token is the user id and the second it was created in (no unique id): two keys of one user created in the same second are the same token, so deleting one of them does not revoke it (measured on the image: back-to-back keys collide) | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | LC-AK08 (default run); LC-AK03 creates its second key in a later second to avoid it | +| D-52 | `PUT /api/groups/{id}/update` renames the all-users group (measured on the image) and, by the same code, the developers group (not measured): the rename has no system-group check, the UI only hides the control (HEAD unchanged by the commit log) | fixed on this branch: a non-null `groupName` on either built-in group (any of its three encodings) is refused with UNSUPPORTED_OPERATION (400 / 5003, message key BAD_REQUEST) and writes nothing; a `dynamicRule`-only update of a built-in group still works; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`): LC-GR09 confirmed passing in the default run; residual: groups renamed before the fix keep the stored name (never shown, `Group.getName(Locale)`), low | LC-GR09 (default run) | +| D-53 | deleting a group leaves its members the access the group granted: a member of a deleted group still views the app the group was granted on, 30 s after the delete (measured on the image; HEAD unchanged by the commit log) | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | LC-GR03 (default run) | +| D-54 | the reset link of the mail has a double slash (`//user/auth/lost-password?token=...`, because the public URL, in the shipped default too, ends in a slash) and the client opens a blank page for it; the same link with one slash opens the reset form (measured on the image; the link is built in `EmailCommunicationServiceImpl`, HEAD unchanged by the commit log) | fixed on this branch: `CommonConfig.withoutTrailingSlashes` strips the public URL's trailing run of slashes before both the reset link and the invitation link are built; a public URL ending in none, one or several slashes gives exactly one slash before the path; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`): LC-PW02 and LC-PW13 (which now open the mailed links as mailed) and LC-PW12 confirmed passing in the default run; not a security finding (the link goes to the account's own address) | LC-PW02, LC-PW12, LC-PW13 (default run) | +| D-55 | the invite dialog confirms with a raw translation key (`oups! membersSettings.inviteByEmailSuccess`): the client asks for keys that do not exist (`inviteDialog.tsx`, HEAD unchanged by the commit log) | fixed on this branch (`inviteDialog.tsx`: `membersSettings.inviteByEmailSuccess` -> `memberSettings.inviteByEmailSuccess`, matching every other key in the file); Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`): LC-PW15 confirmed passing in the default run; not a security finding (display typo); the sibling `membersSettings.inviteByEmailError` at the same line's error branch is unchanged (unreachable: `validateResponse` throws on failure before that branch runs, so no test observes it) | LC-PW15 | +| D-56 | the password-reset mail ignores the workspace's own template (the template is read with the wrong key; measured on the image: the marker of a stored template is absent) | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | LC-PW09 (default run) | +| D-57 | an account in no workspace gets no reset mail while the forgot page still confirms (measured on the image: a member removed from its only workspace gets none) | fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run) | LC-PW10 (default run) | +| D-58 | a reset request for a display name that is not an address mails that user's token to the typed text: whoever can rename a user sets the victim's name to an address of its own and receives the victim's token | fixed on this branch (run 2026-11-23 on an image rebuilt from this branch's working tree: LC-PW11 passes and is in the default run) | LC-PW11 | +| D-59 | a removed developer's data source grant is not deleted: 20 s after the removal the "Can Use" row of the data source was still there, while the group and app rows were gone within 40 ms (measured on the image; HEAD not run) | fixed on this branch: `removeUserDatasourcePermission` now deletes `ResourceType.DATASOURCE` rows instead of `ResourceType.APPLICATION` (copy-paste bug); Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`): LC-DL03 confirmed passing in the default run; low-medium | LC-DL03 | +| D-60 | a removed member's folder grant is not deleted and is live again after a rejoin: the removal listener has no folder step, and the row was still there after the removal and after the rejoin (measured on the image; HEAD listener read: no folder or bundle step) | fixed on this branch: the member-leave clean-up gained a folder and a bundle step (`OrgAndGroupEventListener.onUserLeaveOrg`); Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`): LC-DL04 and LC-DL12 confirmed passing in the default run. Residuals: rows left by removals before the fix stay stored (not a target of this fix; needs an operator audit or a migration); the creator (`createdBy`) access to apps, bundles and folders is a separate, unrevoked mechanism: a removed creator still reads its apps and bundles, and a rejoined creator manages its folders again (LC-DL13 to LC-DL15, quarantined candidates; D-26 residual; an open scope question for the owner) | LC-DL04, LC-DL12 | +| D-61 | a second sign-in configuration of a provider type that already has one is accepted: a second GitHub configuration with another client id answers 200 and the workspace lists two (the server code names the refusal 400 / 5621 `DUPLICATE_AUTH_CONFIG_ADDITION`; measured on the image, HEAD not run) | partly fixed on 3.0.1 (run 2026-11-22: the test passes on lowcoder-ce:3.0.1-e2e; the test is in the default run); the block applies only to a request without an `id`, a request with a made-up `id` should still add a second config (code only, not run); the e2e test sends no `id` | LC-IP07 (default run) | +| D-62 | a provider sign-in whose e-mail claim equals an existing account's address signs in AS that account: the server resolved the provider identity by address, so whoever configures a provider for a workspace could make its user-info answer name any address and receive that user's session, including users of other workspaces | fixed on this branch (run 2026-11-23 on an image rebuilt from this branch's working tree: LC-IP14 passes and is in the default run) | LC-IP14 | +| D-63 | the "Info" card "Your Created Apps" of the profile page counts 0 although the user created two apps (`createBy` of the list equals the user's name and the app list shows them; the page filters the redux app list, `UserProfileLayout.tsx`; root cause NOT VERIFIED); measured on the image, HEAD not run | fixed on this branch: `UserProfileLayout` now fetches the app list on mount and whenever the workspace changes (`dispatch(fetchAllApplications({}))`), instead of relying on another component's lazy fetch, which is never mounted on this page; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`): LC-OT02 confirmed passing in the default run; not a security finding (display bug); residual (an open scope question for the owner): the counts still compare the creator's display NAME (`createBy`), not user id, so same-name users are counted together and an app whose creator no longer exists counts as shared | LC-OT02 | Quarantine decision rule: a test that asserts the DESIRED behaviour and fails today is `@quarantine`. A characterisation or workaround test that passes while documenting a defect (CD-5, CD-7, CD-3 limits, D-3 handling) is not. diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts index ffc2417d61..f09ebcd1fe 100644 --- a/e2e/playwright.config.ts +++ b/e2e/playwright.config.ts @@ -46,6 +46,8 @@ export default defineConfig({ ["junit", { outputFile: "./test-results/junit.xml" }], // Fails the run when more than half of the tests of S1 or M3 needed a D-3 retry. ["./src/reporters/d3-threshold-reporter.ts"], + // One run's raw results, merged across runs (e.g. default and enterprise stacks) with `playwright merge-reports`. + ["blob", { outputDir: "./blob-report" }], ], use: { baseURL: BASE_URL, diff --git a/e2e/scripts/run-in-docker.sh b/e2e/scripts/run-in-docker.sh index 80f494078d..8a56049a21 100755 --- a/e2e/scripts/run-in-docker.sh +++ b/e2e/scripts/run-in-docker.sh @@ -22,8 +22,7 @@ ## E2E_INCLUDE_INSERT_ALL set to 1 to also run the @insert-all tests (S1, the insert-every-component smoke test, 112 ## tests); independent of E2E_INCLUDE_QUARANTINE. Nightly: E2E_INCLUDE_INSERT_ALL=1 $0 --grep @insert-all ## E2E_INCLUDE_SUPERADMIN set to 1 to also run the @superadmin tests (SEC-R16a to SEC-R16d, the instance super admin; -## independent of the other flags; SEC-R16c and SEC-R16d also carry @quarantine and then need -## E2E_INCLUDE_QUARANTINE=1 too). Run: E2E_INCLUDE_SUPERADMIN=1 $0 --grep @superadmin +## independent of the other flags). Run: E2E_INCLUDE_SUPERADMIN=1 $0 --grep @superadmin ## E2E_STACK_PROFILE which stack to start: `default` (the all-in-one image in its SAAS workspace mode; the default) or ## `enterprise` (the same image with LOWCODER_WORKSPACE_MODE=ENTERPRISE: one workspace shared by every ## user; it runs only the @enterprise tests, SEC-E01 to SEC-E04, E06a, E06b) or `signup-disabled` (the same diff --git a/e2e/src/api/client.ts b/e2e/src/api/client.ts index d59e6f3852..bacfd64f20 100644 --- a/e2e/src/api/client.ts +++ b/e2e/src/api/client.ts @@ -17,6 +17,8 @@ import { bundleElementsPath, bundlePath, bundlePermissionsPath, + bundlePublicToAllPath, + bundlePublishPath, bundleRecyclePath, bundleViewPath, datasourcePermissionPath, @@ -691,10 +693,13 @@ export async function logout(request: APIRequestContext): Promise { await unwrap("log out", await request.post(API_PATHS.AUTH_LOGOUT)); } -/** Runs an app query as `POST /api/query/execute` does; `viewMode: true` runs the published version. Raw answer. */ +/** + * Runs an app query as `POST /api/query/execute` does; `viewMode: true` runs the published version. `path` is the + * host chain of a module query (`[hostAppId]`); omit it for the app's own query. Raw answer. + */ export async function executeAppQueryRaw( request: APIRequestContext, - params: { applicationId: string; queryId: string; viewMode: boolean }, + params: { applicationId: string; queryId: string; viewMode: boolean; path?: string[] }, ): Promise { return apiRaw(request, "POST", API_PATHS.QUERY_EXECUTE, { data: { ...params, params: [] } }); } @@ -751,6 +756,17 @@ export async function bundleElementsRaw(request: APIRequestContext, bundleId: st return apiRaw(request, "GET", bundleElementsPath(bundleId)); } +export async function publishBundle(request: APIRequestContext, bundleId: string): Promise { + await unwrap(`publish bundle ${bundleId}`, await request.post(bundlePublishPath(bundleId))); +} + +export async function setBundlePublicToAll(request: APIRequestContext, bundleId: string, publicToAll: boolean): Promise { + await unwrap( + `set public-to-all of bundle ${bundleId}`, + await request.put(bundlePublicToAllPath(bundleId), { data: { publicToAll } }), + ); +} + export async function grantBundlePermission(request: APIRequestContext, bundleId: string, grant: PermissionGrant): Promise { await unwrap( `grant ${grant.role} on bundle ${bundleId}`, @@ -760,6 +776,10 @@ export async function grantBundlePermission(request: APIRequestContext, bundleId ); } +export async function listBundlePermissions(request: APIRequestContext, bundleId: string): Promise { + return unwrap(`list permissions of bundle ${bundleId}`, await request.get(bundlePermissionsPath(bundleId))); +} + /** * Recycles a bundle. The 3.0.0 server sets the status and THEN answers HTTP 500 / 5005 "Cannot find this application" * (measured: the bundle is recycled, `GET /api/bundles/{id}/view` answers 400 / 5003 afterwards, and the recycled bundle @@ -789,7 +809,7 @@ export async function deleteBundle(request: APIRequestContext, bundleId: string) /** * Stores a GitHub sign-in configuration with the given client secret in the workspace of the (admin) caller. GitHub - * configs are only stored; nothing contacts GitHub. Used to prove whether the secret leaks to other callers (SEC-R07d). + * configs are only stored; nothing contacts GitHub. Used to prove whether the secret leaks to other callers (SEC-R07d, SEC-R07e). */ export async function seedOAuthConfig(request: APIRequestContext, params: { clientSecret: string; clientId?: string }): Promise { await unwrap( @@ -807,7 +827,7 @@ export async function seedOAuthConfig(request: APIRequestContext, params: { clie /** * One sign-in configuration as `GET /api/auth/configs` lists it (admin only). The answer also carries the client secret in - * clear (D-14); the type leaves it out so no test reads it. + * clear (the admin list, `@JsonView(Internal)`, by design); the type leaves it out so no test reads it. */ export interface AuthConfigEntry { id: string; @@ -932,6 +952,7 @@ export async function getApp(request: APIRequestContext, appId: string): Promise /** One published version of an app as `GET /api/application-records/listByApplicationId` lists it (`ApplicationRecordMetaView`). */ export interface AppVersion { + id: string; tag: string; } diff --git a/e2e/src/constants.ts b/e2e/src/constants.ts index e1c9da91f3..a4a81f1a11 100644 --- a/e2e/src/constants.ts +++ b/e2e/src/constants.ts @@ -56,8 +56,11 @@ export const API_PATHS = { CONFIGS: "/api/configs", META: "/api/meta/", STATUS_PROMETHEUS: "/api/status/prometheus", + STATUS_METRICS: "/api/status/metrics", /** The registry proxy of the app: `//` (api/npm/PrivateNpmRegistryEndpoint.java). */ NPM_REGISTRY: "/api/npm/registry", + /** The package-asset proxy of the app: `//` (api/npm/PrivateNpmRegistryEndpoint.java). */ + NPM_PACKAGE: "/api/npm/package", } as const; /** `GET` path of the registry proxy for a package of the app; the proxy is open to anonymous callers (D-35). */ @@ -178,11 +181,11 @@ export const TAGS = { * The tests of the instance super admin (SEC-R16a to SEC-R16d): out of the default run and of the @security and @core * gate runs, in only with E2E_INCLUDE_SUPERADMIN (see src/run-selection.ts). On the 3.0.0 image the super admin is a * member of every workspace and its requests time out once the stack holds more than about 420 workspaces (defect - * D-47), a size that repeated security runs reach. SEC-R16c and SEC-R16d also carry @quarantine and need both flags. + * D-47), a size that repeated security runs reach. (SEC-R16c and SEC-R16d were quarantined until 3.0.1-e2e; they need only this flag now.) */ SUPERADMIN: "@superadmin", /** - * The tests of the second stack in ENTERPRISE workspace mode (SEC-E01 to SEC-E06b, tests/security/enterprise*.spec.ts): + * The tests of the second stack in ENTERPRISE workspace mode (SEC-E01 to SEC-E07b, tests/security/enterprise*.spec.ts): * out of every run on the default stack, the only ones of a run with E2E_STACK_PROFILE=enterprise (see * src/run-selection.ts). SEC-E05 also carries @quarantine (open defect D-40) and @superadmin. */ @@ -499,6 +502,10 @@ export function bundlePublishPath(bundleId: string): string { return `${bundlePath(bundleId)}/publish`; } +export function bundlePublicToAllPath(bundleId: string): string { + return `${bundlePath(bundleId)}/public-to-all`; +} + export function datasourcePath(datasourceId: string): string { return `${API_PATHS.DATASOURCES}/${datasourceId}`; } @@ -615,6 +622,11 @@ export function userPhotoPath(orgId: string, userId: string): string { return `${API_PATHS.USERS}/photo/${orgId}/${userId}`; } +/** `POST /api/users/new/{orgId}`: an admin of the organisation creates a user with an e-mail and a password and adds it as a member. */ +export function createUserInOrgPath(orgId: string): string { + return `${API_PATHS.USERS}/new/${orgId}`; +} + export function apiKeyPath(apiKeyId: string): string { return `${API_PATHS.API_KEYS}/${apiKeyId}`; } @@ -702,6 +714,9 @@ export const RESET_TOKEN_MESSAGES = { EXPIRED: "Token to reset the password has expired", } as const; +/** The message of the server's password-rule refusal (INVALID_PASSWORD 403 / 5608, key PASSWORD_TOO_WEAK in `locale_en.properties`; D-48). */ +export const PASSWORD_TOO_WEAK_MESSAGE = "The password must be at least 8 characters long, contain a letter and a digit, and contain no whitespace."; + /** * How long a test polls for the clean-up a removal, a leave or a workspace deletion starts (a listener on its own scheduler, * `OrganizationEventListener` [3.0.0]). Measured on the image: the rows of the user's groups and apps, and the memberships of a diff --git a/e2e/src/lifecycle/mail.ts b/e2e/src/lifecycle/mail.ts index 079bf6fb8f..56e0661514 100644 --- a/e2e/src/lifecycle/mail.ts +++ b/e2e/src/lifecycle/mail.ts @@ -210,21 +210,16 @@ export function resetLinkOf(mail: ParsedMail): string { return match[0]; } -/** A link with the repeated slashes of its path collapsed (`http://h//user/x` -> `http://h/user/x`): what a browser needs when the public URL ends in a slash. */ -export function withSingleSlashes(link: string): string { - const url = new URL(link); - url.pathname = url.pathname.replace(/\/{2,}/g, "/"); - return url.toString(); -} - -/** The invitation code of an invitation mail: the text after `/invite/` in its link. */ -export function inviteCodeOf(mail: ParsedMail): string { - const match = new RegExp(`${INVITE_LINK_PATH.replace(/\//g, "\\/")}([A-Za-z0-9]+)`).exec(textOf(mail)); - const code = match?.[1]; - if (code === undefined) { +/** + * The invitation link of an invitation mail exactly as mailed (the path starts with whatever slashes the server's + * public URL leaves, D-54). Use it to open a page, never put it into a matcher or a message. + */ +export function inviteLinkOf(mail: ParsedMail): string { + const match = new RegExp(`https?:\\/\\/[^\\s<"']*${INVITE_LINK_PATH.replace(/\//g, "\\/")}[A-Za-z0-9]+`).exec(textOf(mail)); + if (!match) { throw new MalformedMailError(`no ${INVITE_LINK_PATH} link with a code`); } - return code; + return match[0]; } /** Whether a parsed mail is a password-reset mail / an invitation (by subject). */ diff --git a/e2e/src/pages/SettingPage.ts b/e2e/src/pages/SettingPage.ts index 0d17d567a2..09f0ed1a04 100644 --- a/e2e/src/pages/SettingPage.ts +++ b/e2e/src/pages/SettingPage.ts @@ -1,6 +1,9 @@ import type { Locator, Page } from "@playwright/test"; import { SETTING_PATHS } from "../constants"; +/** The invite dialog's success notice (`en.ts` `memberSettings.inviteByEmailSuccess`; D-55). */ +export const INVITE_SUCCESS_TEXT = "Invitations sent successfully!"; + /** * The workspace settings at /setting (3.0.0 client). Everything here is measured: a plain member who opens any /setting URL * is sent to /apps, a developer reaches the pages, an admin also gets the provider list. diff --git a/e2e/src/run-selection.ts b/e2e/src/run-selection.ts index 02657e1c26..411a643530 100644 --- a/e2e/src/run-selection.ts +++ b/e2e/src/run-selection.ts @@ -55,7 +55,7 @@ export function runFlagsFromEnv(env: Record): RunFla * independent), and always `@enterprise`, `@enterprise-takeover` and `@signup-disabled`. Signup-disabled profile: `@quarantine` unless its flag is set. Enterprise profile: `@quarantine` unless its flag is set, * and `@enterprise-takeover` unless ITS flag is set; the other two flags do not apply there (`@insert-all` tests are outside * the `@enterprise` selection anyway, and the super admin of that stack is a member of ONE workspace, so the D-47 capacity - * limit behind `@superadmin` does not arise: SEC-E01 to E06a use it and carry the tag for the guard of + * limit behind `@superadmin` does not arise: SEC-E01 to E06a and SEC-E07a, E07b use it and carry the tag for the guard of * tests/foundation/run-selection.spec.ts). */ export function excludedTags(flags: RunFlags): string[] { @@ -83,8 +83,8 @@ export function excludedTags(flags: RunFlags): string[] { * out. Default profile, no flag: `/@quarantine|@insert-all|@superadmin|@enterprise|@enterprise-takeover/` (the default run); * in between, the alternation of the tags whose flag is not set, the two enterprise tags always last. Enterprise profile: * `/@quarantine|@enterprise-takeover/` by default, `/@quarantine/` with the takeover flag only, `/@enterprise-takeover/` - * with the quarantine flag only. A test tagged with several opt-in tags runs only when all their flags are set (SEC-R16c and - * SEC-R16d carry @quarantine and @superadmin; SEC-E05 carries @quarantine and @enterprise-takeover). Limit: it matches the + * with the quarantine flag only. A test tagged with several opt-in tags runs only when all their flags are set (SEC-E05 carries + * @quarantine and @enterprise-takeover; no other test carries two opt-in tags since SEC-R16c and SEC-R16d left the quarantine). Limit: it matches the * tags in the test title, so a title that contains the text of an excluded tag is excluded too (no test title does). */ export function grepInvertFor(flags: RunFlags): RegExp | undefined { diff --git a/e2e/src/security/quarantine.ts b/e2e/src/security/quarantine.ts index 84075e3439..040bb405ca 100644 --- a/e2e/src/security/quarantine.ts +++ b/e2e/src/security/quarantine.ts @@ -22,92 +22,83 @@ export const DEFECT_ID_PATTERN = /^D-\d+$/; export const DEFECT_ANNOTATION_TYPE = "defect"; /** - * Scenarios that fail on the 3.0.0 image but are fixed on this branch's server (fixed-on-branch defects), - * scenario id to defect id. They leave quarantine, without a rewrite of any spec, by deleting their id from this map - * once a run against an updated server passes them (`E2E_INCLUDE_QUARANTINE=1 ... --grep @quarantine`). + * Scenarios whose defect is fixed in the code of this branch but whose test is not (yet) in the default run, scenario id to + * defect id. Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` every other entry that used to be + * here has left the map (its test passed on 3.0.1 and runs by default); what is left needs a decision before it can leave: + * - LC-AK04 (D-45): the API defect is fixed (SEC-A02a passes), but the UI test that deletes the last API key is intermittent + * on 3.0.1 (passed 2 of 3 runs, failed 1 of 3; the cause, product or test, is not investigated). It stays quarantined until + * it passes repeatedly (`E2E_INCLUDE_QUARANTINE=1 ... --grep @quarantine`), then its id is deleted and this map is empty. * - * Limit: the map is the single source of the quarantine; a scenario missing here that fails on the image is NOT + * Limit: the maps are the single source of the quarantine; a scenario missing from both that fails on the image is NOT * quarantined and fails the default run, and a stale entry hides a test that passes. */ export const FIXED_ON_BRANCH: Readonly> = { - "SEC-C13": "D-29", - "SEC-C15": "D-17", - "SEC-C16b": "D-28", - "SEC-C16c": "D-28", - "SEC-C17a": "D-18", - "SEC-C17b": "D-18", - "SEC-C18b": "D-22", - "SEC-C20": "D-21", - "SEC-C23a": "D-43", - "SEC-C23c": "D-44", - "SEC-R08c": "D-16", - "SEC-R08d": "D-24", - "SEC-R09c": "D-20", - "SEC-R11b": "D-26", - "SEC-R16c": "D-23", - "SEC-R16d": "D-24", - "SEC-A02a": "D-45", "LC-AK04": "D-45", - "LC-AK08": "D-51", - "LC-PW09": "D-56", - "LC-PW10": "D-57", - "LC-PW14": "D-18", - "SEC-A06b": "D-23", - "SEC-A07a": "D-19", - "SEC-A09a": "D-25", - "SEC-X02b": "D-27", }; /** - * Scenarios that fail on this branch's server too (open defects, listed in the table "Security findings" of - * `e2e/README.md`), scenario id to defect id. SEC-E05 (ENTERPRISE stack, `tests/security/enterprise-takeover.spec.ts`) - * and SEC-X01b, SEC-X01c (npm registry proxy, `tests/security/outbound.spec.ts`) are built. LC-AU07, LC-AU15 (`tests/auth/signup-edge.spec.ts`), LC-PR06 (`tests/account/profile.spec.ts`), LC-PR13 and LC-PR14 (`tests/account/password.spec.ts`), LC-PW08, LC-PW11, LC-PW12 and LC-PW15 (`tests/auth/password-recovery.spec.ts`), LC-DL03 and LC-DL04 (`tests/workspace/leave-removal.spec.ts`), LC-IP07 (`tests/auth/providers-config.spec.ts`), LC-IP14 (`tests/auth/providers-login.spec.ts`) and LC-OT02 (`tests/account/other.spec.ts`) are lifecycle ids. + * Scenarios that still fail on this branch's server (open defects, listed in the table "Security findings" of + * `e2e/README.md`; each still failed on 3.0.1-e2e on 2026-11-22), scenario id to defect id. + * D-6, D-7, D-35, D-36, D-40 and D-58, D-62 left this map: the server fixes close them (SEC-C09, SEC-C11, SEC-C19a, + * SEC-C19b, SEC-C22e, SEC-R15c, SEC-A11, SEC-E05 and the lifecycle ids LC-PW11, LC-IP14 all now pass; SEC-E05 needs + * `E2E_STACK_PROFILE=enterprise`, confirmed separately). D-33's CORS-credentials half also left: `SecurityConfig` now + * grants credentials only to an origin listed in a non-wildcard `LOWCODER_CORS_DOMAINS` entry, so SEC-A12 passes on the + * default stack (`*`); D-33's CSRF and `SameSite` half stays open (the row names the residual). D-12 and D-39 left this + * map: `SecurityConfig` no longer lets anonymous callers reach `POST /api/meta/` or the actuator metrics and Prometheus + * routes (health stays open); SEC-A10a and SEC-A10c are therefore no longer quarantined (Docker/e2e confirmation + * pending the combined final run). SEC-X01b, SEC-X01c (D-35) left the same way: the npm registry proxy now needs + * READ on the path's app id before resolving the workspace or forwarding anything. D-10 left this map the same way: + * `POST /api/query/execute` in edit mode needs EDIT on the app (for a module run in another app's editor: EDIT on + * that app and READ on the module, whose published queries run), so SEC-A09c is no longer quarantined. D-49 left the + * map the same way: `POST /api/users/password` now needs a single conditional MongoDB update that refuses an account + * which already has a password, so LC-PR13 is no longer quarantined. D-34 left the map the same way: a password + * change, a lost-password reset and an ENTERPRISE admin reset now end the other sessions of the account (the + * caller's own survives a change or a self-reset), so SEC-A04 and LC-PW08 are no longer quarantined. D-48 left the map + * the same way: the server now enforces the client's password rule (sign-up, an admin's create-user route, a password + * change, a lost-password reset, a provider-only account's first password), so LC-AU07 and LC-PR14 are no longer + * quarantined. D-14 left this map: an organization's JSON no longer carries its auth configs, so neither the + * workspace answer nor the profile holds a sign-in client secret, so SEC-R07d is no longer quarantined (SEC-R07e is + * new and was never quarantined). D-32 left this map: the app record route (live or a named version's DSL) now needs + * EDIT_APPLICATIONS on the record's own application, so SEC-R01d is no longer quarantined (SEC-R01e, SEC-R01f+ and + * SEC-R01g+ pin the viewer, editor and workspace-admin answers; Docker/e2e confirmation deferred to the combined + * final run, NOT VERIFIED yet). D-31 left this map: a history snapshot is now served only through the app it was + * saved for, so SEC-C21 is no longer quarantined (Docker/e2e confirmation deferred to the combined final run, NOT + * VERIFIED yet). D-42 left this map only partly: a bundle's element list now carries an app's editing DSL only to a + * reader who may edit that app, and an app added to or moved into a bundle is stored without its editing DSL, so + * SEC-R17c is no longer quarantined (Docker/e2e confirmation deferred to the combined final run, NOT VERIFIED yet); + * copies stored in bundle DSLs before the fix remain unfiltered (the README row names the residual). D-38 left this + * map: each id of a batched permission lookup is now decided in its own workspace instead of the first id's, so + * SEC-R09d is no longer quarantined and no longer intermittent (Docker/e2e confirmation deferred to the combined + * final run, NOT VERIFIED yet). D-8 left this map: a folder's permission list now requires the caller to be a member + * of the folder's workspace, so SEC-C10 is no longer quarantined (Docker/e2e confirmation deferred to the combined + * final run, NOT VERIFIED yet). D-9 and D-37 left this map: a status change through the update route now needs + * MANAGE_APPLICATIONS, and the app slug route now needs EDIT_APPLICATIONS, so SEC-R03b and SEC-C16f are no longer + * quarantined (Docker/e2e confirmation deferred to the combined final run, NOT VERIFIED yet). D-11 and D-41 left + * this map: app, bundle and data source creation now check the developer role in the TARGET workspace, not the + * visitor's current one, so SEC-R06c and SEC-R17b are no longer quarantined (SEC-R06e is new and was never + * quarantined; Docker/e2e confirmation deferred to the combined final run, NOT VERIFIED yet). D-59 and D-60 left this + * map: the member-leave clean-up now deletes the data source row by the right resource type and gained a folder and a + * bundle step, so LC-DL03 and LC-DL04 are no longer quarantined (LC-DL12 is new and was never quarantined; Docker/e2e + * confirmation deferred to the combined final run, NOT VERIFIED yet); rows left by removals before the fix stay + * stored, and a creator's `createdBy` access is a separate, unrevoked mechanism (README D-26 and D-60 residuals, + * LC-DL13 to LC-DL15 candidates). D-52 left this map: `GroupApiServiceImpl.update` now refuses a non-null `groupName` + * on a system group (any of its three encodings) with UNSUPPORTED_OPERATION and writes nothing, so LC-GR09 is no + * longer quarantined (Docker/e2e confirmation deferred to the combined final run, NOT VERIFIED yet); groups renamed + * before the fix keep their stored name, never shown (`Group.getName`). D-54 left this map: the password-reset and + * invitation mail links now carry the configured public URL without its trailing slashes, so LC-PW12 is no longer + * quarantined (LC-PW02 and LC-PW13 now open those links as mailed instead of working around the double slash; + * Docker/e2e confirmation deferred to the combined final run, NOT VERIFIED yet). D-55 left this map: the invite + * dialog's success notice now uses the key readers of every other notice in the file use (`memberSettings.*`, not + * `membersSettings.*`), so LC-PW15 is no longer quarantined (Docker/e2e confirmation deferred to the combined final + * run, NOT VERIFIED yet). D-63 also left this map: the profile now fetches the app list it counts, so LC-OT02 passes + * (Docker/e2e confirmation deferred to the combined final run, NOT VERIFIED yet). LC-AU15 + * (`tests/auth/signup-edge.spec.ts`) is a lifecycle id. */ export const OPEN_DEFECTS: Readonly> = { - "SEC-C09": "D-7", - "SEC-C10": "D-8", - "SEC-C11": "D-7", - "SEC-C16f": "D-37", "SEC-C17c": "D-30", - "SEC-C19a": "D-6", - "SEC-C19b": "D-6", - "SEC-C21": "D-31", - "SEC-C22e": "D-7", - "SEC-R01d": "D-32", - "SEC-R03b": "D-9", - "SEC-R06c": "D-11", - "SEC-R07d": "D-14", - "SEC-R09d": "D-38", - "SEC-R15c": "D-7", - "SEC-R17b": "D-41", - "SEC-R17c": "D-42", "SEC-R17f": "D-46", - "SEC-A04": "D-34", - "SEC-A09c": "D-10", - "SEC-A10a": "D-12", "SEC-A10b": "D-13", - "SEC-A10c": "D-39", - "SEC-A11": "D-36", - "SEC-A12": "D-33", - "SEC-E05": "D-40", - "SEC-X01b": "D-35", - "SEC-X01c": "D-35", - "LC-AU07": "D-48", "LC-AU15": "D-30", - "LC-GR03": "D-53", - "LC-DL03": "D-59", - "LC-DL04": "D-60", - "LC-GR09": "D-52", - "LC-IP07": "D-61", - "LC-IP14": "D-62", - "LC-OT02": "D-63", - "LC-PR06": "D-50", - "LC-PR13": "D-49", - "LC-PR14": "D-48", - "LC-PW08": "D-34", - "LC-PW11": "D-58", - "LC-PW12": "D-54", - "LC-PW15": "D-55", }; /** What a security test passes to `test(title, details, body)`: the `tag` and, for a quarantined test, the annotation. */ @@ -144,7 +135,7 @@ export function securityTestDetails(id: string, extraTags: readonly string[] = [ } /** - * The details of a security test that failed on the 3.0.0 image for a real server behaviour nobody expected and that + * The details of a security test that failed on the image under test for a real server behaviour nobody expected and that * no defect-list entry names yet (`e2e/AGENTS.md` section 7: " candidate"). Quarantined like a listed id, the annotation * description names the scenario and what was measured. A candidate leaves this form by getting a D id in * `FIXED_ON_BRANCH` or `OPEN_DEFECTS` and `securityTestDetails`. Throws on an id that is not a scenario id or that is already diff --git a/e2e/tests/account/password.spec.ts b/e2e/tests/account/password.spec.ts index 9c009286c8..3f9e1fcdca 100644 --- a/e2e/tests/account/password.spec.ts +++ b/e2e/tests/account/password.spec.ts @@ -1,5 +1,5 @@ import { apiRaw, signInRaw } from "../../src/api/client"; -import { API_ERRORS, API_OK, API_PATHS, CHANGED_PASSWORD, TAGS, TEST_PASSWORD, UI_PATHS, USER_SET_PASSWORD_PARAM } from "../../src/constants"; +import { API_ERRORS, API_OK, API_PATHS, CHANGED_PASSWORD, PASSWORD_TOO_WEAK_MESSAGE, TAGS, TEST_PASSWORD, UI_PATHS, USER_SET_PASSWORD_PARAM } from "../../src/constants"; import { expect, test } from "../../src/fixtures"; import { PASSWORD_RULE_TEXT } from "../../src/pages/AuthPage"; import { ProfileModal } from "../../src/pages/ProfileModal"; @@ -82,16 +82,23 @@ test.describe("lifecycle: password change", () => { const answer = await apiRaw(user.request, "POST", API_PATHS.USER_PASSWORD, { params: { [USER_SET_PASSWORD_PARAM]: CHANGED_PASSWORD } }); - expect(answer.status, "the route that sets a password refuses a user who already has one").toBeGreaterThanOrEqual(400); + expectAnswer(answer, API_ERRORS.INVALID_PASSWORD, "the route that sets a password refuses a user who already has one"); expectAnswer(await signInRaw((await newUserSession()).page.request, user.email, TEST_PASSWORD), ALLOWED, "the old password still signs in"); + expectAnswer(await signInRaw((await newUserSession()).page.request, user.email, CHANGED_PASSWORD), API_ERRORS.INVALID_PASSWORD, "the attempted password does not sign in"); }); test("LC-PR14 the server refuses a new password the client rule refuses", lifecycleTestDetails("LC-PR14"), async ({ actor, newUserSession }) => { const user = await actor("weakpw"); + const second = (await newUserSession()).page.request; + expectAnswer(await signInRaw(second, user.email, TEST_PASSWORD), ALLOWED, "setup: a second session of the user"); const answer = await apiRaw(user.request, "PUT", API_PATHS.USER_PASSWORD, { data: { oldPassword: TEST_PASSWORD, newPassword: WEAK_PASSWORD } }); - expect(answer.status, "a one-character new password is refused").toBeGreaterThanOrEqual(400); + expectAnswer(answer, API_ERRORS.INVALID_PASSWORD, "a one-character new password is refused"); + expect(answer.body, "the refusal names the rule").toContain(PASSWORD_TOO_WEAK_MESSAGE); expectAnswer(await signInRaw((await newUserSession()).page.request, user.email, TEST_PASSWORD), ALLOWED, "the password is unchanged"); + expectAnswer(await signInRaw((await newUserSession()).page.request, user.email, WEAK_PASSWORD), API_ERRORS.INVALID_PASSWORD, "the weak password does not sign in"); + expectAnswer(await apiRaw(second, "GET", API_PATHS.USER_MY_ORG), ALLOWED, "the second session survives: the refused change ended nothing"); + expectAnswer(await apiRaw(user.request, "PUT", API_PATHS.USER_PASSWORD, { data: { oldPassword: TEST_PASSWORD, newPassword: CHANGED_PASSWORD } }), ALLOWED, "control: the route accepts a password that meets the rule"); }); }); diff --git a/e2e/tests/auth/password-recovery.spec.ts b/e2e/tests/auth/password-recovery.spec.ts index 721eae1845..a4449dee5f 100644 --- a/e2e/tests/auth/password-recovery.spec.ts +++ b/e2e/tests/auth/password-recovery.spec.ts @@ -15,8 +15,10 @@ import { API_OK, API_PATHS, CHANGED_PASSWORD, + INVITE_LINK_PATH, MAIL_SUBJECTS, PASSWORD_RESET_EMAIL_TEMPLATE_KEY, + PASSWORD_TOO_WEAK_MESSAGE, RESET_TOKEN_MESSAGES, SETTING_PATHS, TAGS, @@ -26,17 +28,17 @@ import { userProfilePath, } from "../../src/constants"; import { expect, test, uniqueEmail, type UserSession } from "../../src/fixtures"; -import { inviteCodeOf, resetLinkOf, resetTokenOf, textOf, withSingleSlashes, type Mailbox } from "../../src/lifecycle/mail"; +import { inviteLinkOf, resetLinkOf, resetTokenOf, textOf, type Mailbox } from "../../src/lifecycle/mail"; import { AuthPage } from "../../src/pages/AuthPage"; import { LoginPage } from "../../src/pages/LoginPage"; import { PasswordRecoveryPage } from "../../src/pages/PasswordRecoveryPage"; -import { SettingPage } from "../../src/pages/SettingPage"; +import { INVITE_SUCCESS_TEXT, SettingPage } from "../../src/pages/SettingPage"; import { joinWorkspace } from "../../src/security/actors"; import { expectAnswer } from "../../src/security/assertions"; import { lifecycleTestDetails } from "../../src/security/quarantine"; /** - * Password recovery and invitation mails (LC-PW01 to LC-PW15). The mails come from the run's mail sink. A reset token is a + * Password recovery and invitation mails (LC-PW01 to LC-PW16). The mails come from the run's mail sink. A reset token is a * credential: it is compared as a boolean or sent to the server, never given to a matcher or a message, and the trace is off * because it would record the pages and requests that carry it. A denial first proves its setup (a mail arrived, a token works). * Not covered: the 12-hour expiry (no clock control) and rate limiting (a per-URL limit of the whole server). @@ -46,9 +48,8 @@ test.use({ trace: "off" }); const ALLOWED = { status: 200, code: API_OK } as const; const OTHER_PASSWORD = "Passw0rd-e2e-other"; +const WEAK_PASSWORD = "a"; const MADE_UP_TOKEN = "madeUpTok1"; -/** What a notice shows when the client asks for a translation that does not exist: the framework's "oups!" marker, or a dotted key such as `membersSettings.inviteByEmailSuccess`. */ -const UNTRANSLATED_NOTICE = /oups!|\b[a-z]+Settings\.[A-Za-z]+/i; const TOKEN_REFUSED = API_ERRORS.INVALID_PARAMETER; /** A request context with no session of the test's browser (the page of a new session, never logged in). */ @@ -100,7 +101,7 @@ test.describe("lifecycle: password recovery", () => { const session = await newUserSession(); const recovery = new PasswordRecoveryPage(session.page); - await recovery.openLink(withSingleSlashes(link)); + await recovery.openLink(link); await recovery.submitReset(user.email, CHANGED_PASSWORD); await expect(recovery.resetSuccessMessage, "the page confirms the reset").toBeVisible(); @@ -271,8 +272,9 @@ test.describe("lifecycle: password recovery", () => { const mails = await mailbox.waitForMail(guest.email, MAIL_SUBJECTS.INVITATION); expect(mails.length, "exactly one invitation mail").toBe(1); - const code = inviteCodeOf(mails[0]!); - await guest.session.page.goto(`/invite/${code}`); + const link = inviteLinkOf(mails[0]!); + expect(new URL(link).pathname, "one slash before invite/ (D-54)").toMatch(new RegExp(`^${INVITE_LINK_PATH}[A-Za-z0-9]+$`)); + await guest.session.page.goto(link); await expect(guest.session.page, "the invitation leads to the app list").toHaveURL(UI_PATHS.APP_LIST); await expect .poll(async () => (await currentUser(guest.request)).orgAndRoles.map((entry) => ({ id: entry.org.id, role: entry.role })), "the guest joined the workspace as a member") @@ -305,7 +307,21 @@ test.describe("lifecycle: password recovery", () => { const notice = await settings.inviteNotice.innerText(); // read at once: the notice is transient await mailbox.waitForMail(invitee, MAIL_SUBJECTS.INVITATION); // control: the invitation was sent - expect(notice.trim().length > 0, "the notice has text").toBe(true); - expect(UNTRANSLATED_NOTICE.test(notice), "the notice is text, not a translation key").toBe(false); + expect(notice.trim(), "the notice is the localized success text").toBe(INVITE_SUCCESS_TEXT); + }); + + test("LC-PW16 a reset to a password the client rule refuses is refused and leaves the token usable", lifecycleTestDetails("LC-PW16"), async ({ actor, newUserSession, mailbox }) => { + const user = await actor("pwweak"); + const anon = await visitor(newUserSession); + const token = await tokenOfRequest(anon, mailbox, user.email); + + const weak = await resetLostPasswordRaw(anon, { address: user.email, token, password: WEAK_PASSWORD }); + + expectAnswer(weak, API_ERRORS.INVALID_PASSWORD, "a reset to a one-character password"); + expect(weak.body, "the refusal names the rule").toContain(PASSWORD_TOO_WEAK_MESSAGE); + expect(await canSignIn(newUserSession, user.email, TEST_PASSWORD), "the password is unchanged").toBe(true); + expect(await canSignIn(newUserSession, user.email, WEAK_PASSWORD), "the weak password does not sign in").toBe(false); + expectAnswer(await resetLostPasswordRaw(anon, { address: user.email, token, password: CHANGED_PASSWORD }), ALLOWED, "the same live token then resets to a password that meets the rule"); + expect(await canSignIn(newUserSession, user.email, CHANGED_PASSWORD), "the new password signs in").toBe(true); }); }); diff --git a/e2e/tests/auth/providers-login.spec.ts b/e2e/tests/auth/providers-login.spec.ts index b757682c45..6ef9edfba0 100644 --- a/e2e/tests/auth/providers-login.spec.ts +++ b/e2e/tests/auth/providers-login.spec.ts @@ -3,6 +3,7 @@ import { API_ERRORS, API_OK, API_PATHS, + PASSWORD_TOO_WEAK_MESSAGE, SESSION_COOKIE_NAME, SET_COOKIE_HEADER, TEST_PASSWORD, @@ -27,7 +28,7 @@ import { expectAnswer } from "../../src/security/assertions"; import { lifecycleTestDetails } from "../../src/security/quarantine"; /** - * Sign-in through a provider (LC-IP10 to LC-IP15) against a mock Generic OAuth provider on the test's own target of the echo + * Sign-in through a provider (LC-IP10 to LC-IP17) against a mock Generic OAuth provider on the test's own target of the echo * sidecar. The server calls the token and user-info endpoints itself; the browser never visits the provider, so a test makes * the call the client makes after the redirect (`POST /api/auth/tp/login`) with a made-up code. Every test configures its own * workspace's provider and user, so parallel tests share nothing. The tokens and the secret are fakes of the mock. @@ -35,6 +36,7 @@ import { lifecycleTestDetails } from "../../src/security/quarantine"; const OK = { status: 200, code: API_OK } as const; const PROVIDER_USER_NAME = "Mock User"; +const WEAK_PASSWORD = "a"; function setsSessionCookie(headers: Record): boolean { return (headers[SET_COOKIE_HEADER] ?? "").includes(SESSION_COOKIE_NAME); @@ -169,4 +171,20 @@ test.describe("lifecycle: sign-in through a provider (mock)", () => { expectAnswer(await signInRaw(emailSession.page.request, bound, TEST_PASSWORD), OK, "the bound address signs in"); expect(await currentUserId(emailSession.page.request), "as the same account").toBe(userId); }); + + test("LC-IP17 a provider-only user cannot set a first password the client rule refuses", lifecycleTestDetails("LC-IP17"), async ({ actor, newUserSession, echo, baseURL }, testInfo) => { + const admin = await actor("idpadmin"); + const address = uniqueEmail("idpweak", testInfo.workerIndex); + await answerToken(echo); + await answerUser(echo, { sub: `sub-${address}`, email: address, name: "Mock Weak" }); + const provider = await saveMockProvider(admin.request, echo, { enableRegister: true }); + const session = await newUserSession(); + expectAnswer(await providerLogin(session.page.request, { provider, orgId: admin.orgId, baseURL: baseURL! }), OK, "setup: the provider sign-in creates a user without a password"); + + const weak = await apiRaw(session.page.request, "POST", API_PATHS.USER_PASSWORD, { params: { [USER_SET_PASSWORD_PARAM]: WEAK_PASSWORD } }); + + expectAnswer(weak, API_ERRORS.INVALID_PASSWORD, "a one-character first password is refused"); + expect(weak.body, "the refusal names the rule").toContain(PASSWORD_TOO_WEAK_MESSAGE); + expectAnswer(await apiRaw(session.page.request, "POST", API_PATHS.USER_PASSWORD, { params: { [USER_SET_PASSWORD_PARAM]: TEST_PASSWORD } }), OK, "TEST_PASSWORD is then set: the refused password stored nothing (an account with a password is refused, D-49)"); + }); }); diff --git a/e2e/tests/auth/signup-edge.spec.ts b/e2e/tests/auth/signup-edge.spec.ts index 985ae6f470..e8621339e4 100644 --- a/e2e/tests/auth/signup-edge.spec.ts +++ b/e2e/tests/auth/signup-edge.spec.ts @@ -7,16 +7,16 @@ import { signIn, signInRaw, } from "../../src/api/client"; -import { API_ERRORS, API_OK, API_PATHS, TAGS, TEST_PASSWORD, UI_PATHS } from "../../src/constants"; +import { API_ERRORS, API_OK, API_PATHS, createUserInOrgPath, PASSWORD_TOO_WEAK_MESSAGE, TAGS, TEST_PASSWORD, UI_PATHS } from "../../src/constants"; import { expect, test, uniqueEmail } from "../../src/fixtures"; import { AuthPage, PASSWORD_RULE_TEXT } from "../../src/pages/AuthPage"; import { expectAnswer } from "../../src/security/assertions"; import { lifecycleTestDetails } from "../../src/security/quarantine"; /** - * Edge cases of the sign-up (LC-AU01 to LC-AU08, LC-AU15, LC-AU16): a registered address in any casing, a malformed one, - * the password rules of the form, the invitation link and the workspace sign-up page. A denial first proves its setup (the - * account the refusal protects exists and works). + * Edge cases of the sign-up (LC-AU01 to LC-AU08, LC-AU15 to LC-AU17): a registered address in any casing, a malformed one, + * the password rules of the form, the invitation link, the workspace sign-up page and an admin's create-user route. A + * denial first proves its setup (the account the refusal protects exists and works). */ const ALLOWED = { status: 200, code: API_OK } as const; @@ -113,16 +113,31 @@ test.describe("lifecycle: sign-up edge cases", () => { lifecycleTestDetails("LC-AU07"), async ({ newUserSession }, testInfo) => { const visitor = (await newUserSession()).page.request; - const control = await registerRaw((await newUserSession()).page.request, uniqueEmail("ctl", testInfo.workerIndex), TEST_PASSWORD); - expectAnswer(control, ALLOWED, "control: a sign-up with a password that meets the rules works"); + const weakAddress = uniqueEmail("weak", testInfo.workerIndex); - const answer = await registerRaw(visitor, uniqueEmail("weak", testInfo.workerIndex), WEAK_PASSWORD); + const answer = await registerRaw(visitor, weakAddress, WEAK_PASSWORD); - expect(answer.status, "the server refuses a one-character password").toBeGreaterThanOrEqual(400); + expectAnswer(answer, API_ERRORS.INVALID_PASSWORD, "the server refuses a one-character password"); + expect(answer.body, "the refusal names the rule").toContain(PASSWORD_TOO_WEAK_MESSAGE); expectAnswer(await apiRaw(visitor, "GET", API_PATHS.USER_MY_ORG), API_ERRORS.UNAUTHENTICATED, "no session was opened"); + expectAnswer(await registerRaw((await newUserSession()).page.request, weakAddress, TEST_PASSWORD), ALLOWED, "no account was created: the address still signs up"); }, ); + test("LC-AU17 an admin cannot create a user with a password the client rule refuses", lifecycleTestDetails("LC-AU17"), async ({ actor, newUserSession }, testInfo) => { + const admin = await actor("creator"); + const weakAddress = uniqueEmail("created-weak", testInfo.workerIndex); + const strongAddress = uniqueEmail("created-ok", testInfo.workerIndex); + + const answer = await apiRaw(admin.request, "POST", createUserInOrgPath(admin.orgId), { data: { email: weakAddress, password: WEAK_PASSWORD } }); + + expectAnswer(answer, API_ERRORS.INVALID_PASSWORD, "the admin route refuses a one-character password"); + expect(answer.body, "the refusal names the rule").toContain(PASSWORD_TOO_WEAK_MESSAGE); + expectAnswer(await registerRaw((await newUserSession()).page.request, weakAddress, TEST_PASSWORD), ALLOWED, "no account was created: the address still signs up"); + expectAnswer(await apiRaw(admin.request, "POST", createUserInOrgPath(admin.orgId), { data: { email: strongAddress, password: TEST_PASSWORD } }), ALLOWED, "control: the route creates a user with a password that meets the rule"); + expectAnswer(await signInRaw((await newUserSession()).page.request, strongAddress, TEST_PASSWORD), ALLOWED, "control: the created user signs in"); + }); + test("LC-AU08 an invited visitor signs up through the invitation link and joins only that workspace", lifecycleTestDetails("LC-AU08", [TAGS.CORE]), async ({ actor, newUserSession }, testInfo) => { const inviter = await actor("inviter"); const code = await createInvitation(inviter.request, inviter.orgId); diff --git a/e2e/tests/foundation/lifecycle-mail.spec.ts b/e2e/tests/foundation/lifecycle-mail.spec.ts index 19952114c7..d395052e77 100644 --- a/e2e/tests/foundation/lifecycle-mail.spec.ts +++ b/e2e/tests/foundation/lifecycle-mail.spec.ts @@ -5,13 +5,12 @@ import { MAIL_SUBJECTS } from "../../src/constants"; import { MalformedMailError, UnsupportedMailEncodingError, - inviteCodeOf, + inviteLinkOf, isInvitation, isPasswordReset, parseMail, resetLinkOf, resetTokenOf, - withSingleSlashes, textOf, type SinkMail, } from "../../src/lifecycle/mail"; @@ -45,12 +44,12 @@ test.describe("mail parser", () => { expect(resetTokenOf(mail), "TOKEN%3CPLACEHOLDER%24 decoded").toBe("TOKEN { + test("the recorded invitation mail: subject and link", () => { const mail = parseMail(fixture("invitation.eml")); expect(mail.subject).toBe(MAIL_SUBJECTS.INVITATION); expect(isInvitation(mail)).toBe(true); - expect(inviteCodeOf(mail)).toBe("INVITECODEPLACEHOLDER000"); + expect(inviteLinkOf(mail), "the link as mailed, double slash kept").toBe("http://lowcoder-e2e-app:3000//invite/INVITECODEPLACEHOLDER000"); expect(() => resetTokenOf(mail), "an invitation holds no reset link").toThrow(MalformedMailError); }); @@ -137,13 +136,11 @@ test.describe("mail parser", () => { expect(mail.parts.map((part) => part.text)).toEqual(["see --B1 inside and x--B1 too"]); }); - test("resetLinkOf returns the link as mailed and withSingleSlashes collapses only the slashes of its path", () => { + test("resetLinkOf returns the link as mailed", () => { const mail = parseMail(fixture("password-reset.eml")); const link = resetLinkOf(mail); expect(link.replace(/token=.*/, "token="), "the link keeps the double slash of the public URL").toBe("http://lowcoder-e2e-app:3000//user/auth/lost-password?token="); - expect(withSingleSlashes(link).replace(/token=.*/, "token=")).toBe("http://lowcoder-e2e-app:3000/user/auth/lost-password?token="); - expect(withSingleSlashes("http://h:1/a/b?x=//y"), "a link with single slashes and slashes in the query is unchanged").toBe("http://h:1/a/b?x=//y"); expect(() => resetLinkOf(parseMail(fixture("invitation.eml"))), "an invitation holds no reset link").toThrow(MalformedMailError); }); @@ -160,6 +157,6 @@ test.describe("mail parser", () => { expect(() => resetTokenOf(none)).toThrow(MalformedMailError); expect(() => resetTokenOf(bad)).toThrow(/not valid percent-encoding/); - expect(() => inviteCodeOf(none)).toThrow(MalformedMailError); + expect(() => inviteLinkOf(none)).toThrow(MalformedMailError); }); }); diff --git a/e2e/tests/foundation/lifecycle-recovery-helpers.spec.ts b/e2e/tests/foundation/lifecycle-recovery-helpers.spec.ts index abd0ea4d6a..f76b6ac33b 100644 --- a/e2e/tests/foundation/lifecycle-recovery-helpers.spec.ts +++ b/e2e/tests/foundation/lifecycle-recovery-helpers.spec.ts @@ -1,4 +1,4 @@ -import { requestPasswordReset, resetLostPasswordRaw, sendInvitationEmails } from "../../src/api/client"; +import { requestPasswordReset, resetLostPasswordRaw, sendInvitationEmails, signIn } from "../../src/api/client"; import { API_ERRORS, API_OK, MAIL_SUBJECTS, CHANGED_PASSWORD } from "../../src/constants"; import { expect, test, uniqueEmail } from "../../src/fixtures"; import { resetTokenOf } from "../../src/lifecycle/mail"; @@ -18,6 +18,9 @@ test.describe("lifecycle recovery helpers", () => { const token = resetTokenOf((await mailbox.waitForMail(user.email, MAIL_SUBJECTS.PASSWORD_RESET))[0]!); const first = await resetLostPasswordRaw(anon, { address: user.email, token, password: CHANGED_PASSWORD }); const second = await resetLostPasswordRaw(anon, { address: user.email, token, password: CHANGED_PASSWORD }); + // D-34: a successful reset ends every other session of the user, so `user.request`'s own sign-in from `actor()` is + // gone; sign it back in with the new password before using it, as a real user would. + await signIn(user.request, user.email, CHANGED_PASSWORD); const invitee = uniqueEmail("rawinvitee", testInfo.workerIndex); const sent = await sendInvitationEmails(user.request, user.orgId, [invitee]); diff --git a/e2e/tests/foundation/run-selection.spec.ts b/e2e/tests/foundation/run-selection.spec.ts index 20e62315ae..e1885b697a 100644 --- a/e2e/tests/foundation/run-selection.spec.ts +++ b/e2e/tests/foundation/run-selection.spec.ts @@ -193,7 +193,7 @@ test.describe("run selection: grep and grepInvert from the opt-in flags and the test("a super admin test that is also quarantined runs only when both of its flags are set", () => { const runsIn = everyFlagCombination(DEFAULT_STACK).filter((flags) => keptTitles(flags).includes(TITLE_SUPERADMIN_QUARANTINE)); - expect(runsIn.every((flags) => flags.includeQuarantine && flags.includeSuperAdmin), "SEC-R16c and SEC-R16d need both flags").toBe(true); + expect(runsIn.every((flags) => flags.includeQuarantine && flags.includeSuperAdmin), "a test with both tags needs both flags").toBe(true); expect(runsIn.length, "combinations that keep them (insert-all and takeover free to vary)").toBe(4); }); diff --git a/e2e/tests/foundation/security-api-raw.spec.ts b/e2e/tests/foundation/security-api-raw.spec.ts index f5896eaa01..54c6221511 100644 --- a/e2e/tests/foundation/security-api-raw.spec.ts +++ b/e2e/tests/foundation/security-api-raw.spec.ts @@ -1,7 +1,8 @@ import { createServer, type IncomingMessage, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import { expect, test as base, type APIRequestContext } from "@playwright/test"; -import { apiRaw } from "../../src/api/client"; +import { apiRaw, executeAppQueryRaw } from "../../src/api/client"; +import { API_PATHS } from "../../src/constants"; /** Paths of the local server that stands in for the app: no stack is needed to test how `apiRaw` reads an answer. */ const PATHS = { @@ -56,6 +57,17 @@ function startServer(): Promise<{ server: Server; baseURL: string }> { case PATHS.HEADERS: response.writeHead(200, { "x-e2e-single": "one", "set-cookie": ["a=1; HttpOnly", "b=2"] }).end(); return; + case API_PATHS.QUERY_EXECUTE: { + const echo: Echo = { + method: request.method ?? "", + url: request.url ?? "", + contentType: request.headers["content-type"], + probeHeader: request.headers[PROBE_HEADER] as string | undefined, + body: await readBody(request), + }; + response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ code: 1, data: echo })); + return; + } case PATHS.ECHO: { const echo: Echo = { method: request.method ?? "", @@ -159,4 +171,14 @@ test.describe("apiRaw", () => { expect((answer.json as { data: Echo }).data.body).toBe("new-slug"); }); + + test("executeAppQueryRaw sends the path when given and no path otherwise", async ({ localApi: context }) => { + const withPath = await executeAppQueryRaw(context, { applicationId: "app-1", queryId: "q1", viewMode: false, path: ["h1"] }); + const withPathBody = JSON.parse((withPath.json as { data: Echo }).data.body); + expect(withPathBody.path).toEqual(["h1"]); + + const withoutPath = await executeAppQueryRaw(context, { applicationId: "app-1", queryId: "q1", viewMode: false }); + const withoutPathBody = JSON.parse((withoutPath.json as { data: Echo }).data.body); + expect(withoutPathBody).not.toHaveProperty("path"); + }); }); diff --git a/e2e/tests/foundation/security-constants.spec.ts b/e2e/tests/foundation/security-constants.spec.ts index fc554e1bb4..84c761c987 100644 --- a/e2e/tests/foundation/security-constants.spec.ts +++ b/e2e/tests/foundation/security-constants.spec.ts @@ -23,6 +23,7 @@ import { bundleReorderPath, bundleViewPath, configPath, + createUserInOrgPath, datasourcePath, datasourcePermissionPath, datasourcePermissionsPath, @@ -126,6 +127,7 @@ test.describe("security constants", () => { apiKeyPath: apiKeyPath(ID), libraryQueryPath: libraryQueryPath(ID), configPath: configPath("k"), + createUserInOrgPath: createUserInOrgPath(ID), }; expect(built).toEqual({ @@ -169,6 +171,7 @@ test.describe("security constants", () => { apiKeyPath: "/api/auth/api-key/i1", libraryQueryPath: "/api/library-queries/i1", configPath: "/api/configs/k", + createUserInOrgPath: "/api/users/new/i1", }); }); diff --git a/e2e/tests/foundation/security-helpers.spec.ts b/e2e/tests/foundation/security-helpers.spec.ts index cc8f4e430d..8426feae28 100644 --- a/e2e/tests/foundation/security-helpers.spec.ts +++ b/e2e/tests/foundation/security-helpers.spec.ts @@ -27,6 +27,7 @@ import { grantFolderPermission, listAppPermissions, listAppVersions, + listBundlePermissions, listDatasourcePermissions, listFolderPermissions, listGroupMembers, @@ -36,7 +37,9 @@ import { logout, moveToFolder, publishApp, + publishBundle, recycleBundle, + setBundlePublicToAll, removeAppPermission, removeDatasourcePermission, removeFolderPermission, @@ -486,7 +489,7 @@ test.describe("security helpers: credentials and content", () => { expect(snapshots[0]?.snapshotId, "with an id").toBeTruthy(); }); - test("bundle helpers: createBundle, addAppToBundle, bundleElementsRaw, grantBundlePermission, recycleBundle, deleteBundle", async ({ + test("bundle helpers: createBundle, addAppToBundle, bundleElementsRaw, grantBundlePermission, listBundlePermissions, recycleBundle, deleteBundle", async ({ actor, }) => { const owner = await actor("owner"); @@ -502,8 +505,16 @@ test.describe("security helpers: credentials and content", () => { expect(elements.status).toBe(200); expect(elements.body, "after: the app is in the bundle").toContain(appId); expect((await apiRaw(guest.request, "GET", bundleViewPath(bundleId))).code, "before the grant: a member without one").not.toBe(API_OK); + expect( + (await listBundlePermissions(owner.request, bundleId)).userPermissions.some((item) => item.id === guest.userId), + "before the grant: no bundle permission row", + ).toBe(false); await grantBundlePermission(owner.request, bundleId, { role: APP_ROLES.VIEWER, userIds: [guest.userId] }); expect((await apiRaw(guest.request, "GET", bundleViewPath(bundleId))).code, "after the grant: viewer views").toBe(API_OK); + expect( + (await listBundlePermissions(owner.request, bundleId)).userPermissions.find((item) => item.id === guest.userId)?.role, + "after the grant: a bundle permission row listing the role", + ).toBe(APP_ROLES.VIEWER); expect((await apiRaw(owner.request, "GET", RECYCLED_BUNDLES_PATH)).body, "before recycling: not in the trash").not.toContain(bundleId); await recycleBundle(owner.request, bundleId); expect((await apiRaw(owner.request, "GET", bundleViewPath(bundleId))).code, "recycled: the view is refused").not.toBe(API_OK); @@ -514,6 +525,28 @@ test.describe("security helpers: credentials and content", () => { expect((await apiRaw(owner.request, "GET", RECYCLED_BUNDLES_PATH)).body, "deleted: out of the trash").not.toContain(bundleId); }); + test("bundle helpers: publishBundle, setBundlePublicToAll", async ({ actor }) => { + const owner = await actor("owner"); + const outsider = await actor("outsider"); + // A bundle with no app ever added keeps `editingBundleDSL` null (Bundle.java:39 has no builder default), so publishing + // it would copy null into `publishedBundleDSL` (BundleServiceImpl.java:90-97) and never satisfy the "after publishing" + // assertion below. Add one app first, as every other bundle helpers test does, so there is editing DSL to publish. + const bundleId = await createBundle(owner.request, { orgId: owner.orgId, name: BUNDLE_NAME }); + const { appId } = await createApp(owner.request, { orgId: owner.orgId, name: SCENARIO_APP }); + await addAppToBundle(owner.request, appId, bundleId); + const view = async () => (await apiRaw(owner.request, "GET", bundleViewPath(bundleId))).json as { data: { publishedBundleDSL?: unknown } }; + expect((await view()).data.publishedBundleDSL, "before publishing: no published DSL yet").toBeFalsy(); + expect((await apiRaw(outsider.request, "GET", bundleViewPath(bundleId))).code, "before: an outsider has no grant").not.toBe(API_OK); + + await publishBundle(owner.request, bundleId); + + expect((await view()).data.publishedBundleDSL, "after publishing: a published DSL exists").toBeTruthy(); + + await setBundlePublicToAll(owner.request, bundleId, true); + + expect((await apiRaw(outsider.request, "GET", bundleViewPath(bundleId))).code, "after public-to-all: an outsider views").toBe(API_OK); + }); + // D-46 (SF-41): the 3.0.0 server recycles a bundle and then answers 500 / 5005. test("a bundle recycle answers success (bundle recycle candidate)", { tag: TAGS.QUARANTINE, @@ -544,7 +577,10 @@ test.describe("security helpers: credentials and content", () => { await publishApp(owner.request, appId); - expect(await listAppVersions(owner.request, appId), "after: one version").toHaveLength(1); + const versions = await listAppVersions(owner.request, appId); + expect(versions, "after: one version").toHaveLength(1); + expect(typeof versions[0]?.id, "the version carries a non-empty id").toBe("string"); + expect(versions[0]?.id, "the version's id is not empty").not.toBe(""); }); test("uploadProfilePhoto stores a photo that readProfilePhoto returns a different one afterwards", async ({ actor }) => { diff --git a/e2e/tests/foundation/security-quarantine.spec.ts b/e2e/tests/foundation/security-quarantine.spec.ts index e2c45359a4..f109baa085 100644 --- a/e2e/tests/foundation/security-quarantine.spec.ts +++ b/e2e/tests/foundation/security-quarantine.spec.ts @@ -16,10 +16,31 @@ import { securityTestDetails, } from "../../src/security/quarantine"; -/** Sizes of the two maps: 26 fixed-on-branch scenarios (21 security ids plus LC-AK04, LC-AK08, LC-PW09, LC-PW10 and LC-PW14), and 44 open ones (28 security ids plus the lifecycle ids LC-GR03, LC-GR09, LC-AU07, LC-AU15, LC-PR06, LC-PR13, LC-PR14, LC-PW08, LC-PW11, LC-PW12, LC-PW15, LC-DL03, LC-DL04, LC-IP07, LC-IP14 and LC-OT02). */ -const FIXED_ON_BRANCH_COUNT = 26; -const OPEN_DEFECTS_COUNT = 44; -/** Lifecycle ids: LC-AU07 and LC-AU15 are in a map so far; the listed-id branches are also tested through an injected lookup. */ +/** Sizes of the two maps: 1 fixed-on-branch scenario (the lifecycle id LC-AK04, an intermittent UI test), and 4 open ones + * (3 security ids plus the lifecycle id LC-AU15). D-6, D-7, D-33 (CORS-credentials half), D-34, D-36, D-40, D-48, D-49, D-58 and D-62 left the map: their server fixes + * closed SEC-C09, SEC-C11, SEC-C19a, SEC-C19b, SEC-C22e, SEC-R15c, SEC-A04, SEC-A11, SEC-A12, SEC-E05, LC-PW08, LC-PW11, + * LC-IP14, LC-PR13, LC-AU07 and LC-PR14. D-12 and D-39 also left the map: the fix closed SEC-A10a and SEC-A10c. D-35 also left the map: + * the fix closed SEC-X01b and SEC-X01c. D-10 also left the map: the fix closed SEC-A09c. D-14 also left the map: the + * fix closed SEC-R07d and SEC-R07e. D-32 also left the map: the fix closed SEC-R01d (SEC-R01e, SEC-R01f+ and + * SEC-R01g+ are new and were never quarantined). D-31 also left the map: the fix closed SEC-C21. D-42 also left the + * map, only partly: the fix closed SEC-R17c (SEC-R17g is new and was never quarantined); copies stored in bundle + * DSLs before the fix remain unfiltered. D-38 also left the map: each id of a batched permission lookup is now + * decided in its own workspace, so SEC-R09d is no longer quarantined and no longer intermittent. D-8 also left the + * map: a folder's permission list now requires the caller to be a member of the folder's workspace, so SEC-C10 is no + * longer quarantined. D-9 and D-37 also left the map: a status change now needs MANAGE_APPLICATIONS and the app slug + * route now needs EDIT_APPLICATIONS, so SEC-R03b and SEC-C16f are no longer quarantined. D-11 and D-41 also left the + * map: app, bundle and data source creation now check the developer role of the TARGET workspace, so SEC-R06c and + * SEC-R17b are no longer quarantined (SEC-R06e is new and was never quarantined). D-59 and D-60 also left the map: + * the member-leave clean-up now deletes the right data source rows and gained a folder and a bundle step, so + * LC-DL03 and LC-DL04 are no longer quarantined (LC-DL12 is new and was never quarantined). D-52 also left the map: + * a system group's rename is now refused with UNSUPPORTED_OPERATION, so LC-GR09 is no longer quarantined. D-54 also + * left the map: the mail links now carry the public URL without its trailing slashes, so LC-PW12 is no longer + * quarantined. D-55 also left the map: the invite dialog's success notice now uses the right translation key, so + * LC-PW15 is no longer quarantined. D-63 also left the map: the profile now fetches the app list it counts, so + * LC-OT02 is no longer quarantined. */ +const FIXED_ON_BRANCH_COUNT = 1; +const OPEN_DEFECTS_COUNT = 4; +/** Lifecycle ids: LC-AU15 is in a map so far; the listed-id branches are also tested through an injected lookup. */ const LC_UNLISTED_ID = "LC-AU01"; const LC_INJECTED_ID = "LC-AK98"; const INJECTED_DEFECTS: Readonly> = { [LC_INJECTED_ID]: "D-45" }; @@ -27,8 +48,12 @@ const LC_AREAS = ["AU", "PR", "AK", "WM", "GR", "SH", "PW", "DL", "IP", "OT"]; const injected = lifecycleDetailsFor((id) => INJECTED_DEFECTS[id]); /** A scenario id that is in neither map (a scenario that passes on the image). */ const PASSING_ID = "SEC-C01a"; -const FIXED_ID = "SEC-C13"; -const OPEN_ID = "SEC-C09"; +/** The one id of `FIXED_ON_BRANCH` is a lifecycle id, so the security functions are exercised with open-defect ids. */ +const FIXED_LC_ID = "LC-AK04"; +/** A scenario that left the quarantine on 3.0.1 (its test passes, so it is in neither map). */ +const LEFT_QUARANTINE_ID = "SEC-C13"; +const OPEN_ID = "SEC-C17c"; +const OTHER_OPEN_ID = "SEC-R17f"; /** The title as Playwright matches `grep` / `grepInvert` against: the title followed by the tags of the test. */ function titleWithTags(id: string, tags: string[]): string { @@ -37,9 +62,9 @@ function titleWithTags(id: string, tags: string[]): string { test.describe("security quarantine list", () => { test("a listed id gets the security and quarantine tags and the defect annotation", () => { - expect(securityTestDetails(FIXED_ID), "a fixed-on-branch id").toEqual({ - tag: [TAGS.SECURITY, TAGS.QUARANTINE], - annotation: { type: DEFECT_ANNOTATION_TYPE, description: FIXED_ON_BRANCH[FIXED_ID] }, + expect(lifecycleTestDetails(FIXED_LC_ID), "a fixed-on-branch id").toEqual({ + tag: [TAGS.LIFECYCLE, TAGS.QUARANTINE], + annotation: { type: DEFECT_ANNOTATION_TYPE, description: FIXED_ON_BRANCH[FIXED_LC_ID] }, }); expect(securityTestDetails(OPEN_ID), "an open-defect id").toEqual({ tag: [TAGS.SECURITY, TAGS.QUARANTINE], @@ -52,11 +77,12 @@ test.describe("security quarantine list", () => { expect(details.tag).toEqual([TAGS.SECURITY]); expect(details, "no annotation key at all").not.toHaveProperty("annotation"); + expect(securityTestDetails(LEFT_QUARANTINE_ID), "an id that left the quarantine on 3.0.1").toEqual({ tag: [TAGS.SECURITY] }); }); test("extra tags are appended after the quarantine tags; the P0 set passes TAGS.CORE", () => { expect(securityTestDetails(PASSING_ID, [TAGS.CORE]).tag).toEqual([TAGS.SECURITY, TAGS.CORE]); - expect(securityTestDetails(FIXED_ID, [TAGS.CORE]).tag).toEqual([TAGS.SECURITY, TAGS.QUARANTINE, TAGS.CORE]); + expect(securityTestDetails(OPEN_ID, [TAGS.CORE]).tag).toEqual([TAGS.SECURITY, TAGS.QUARANTINE, TAGS.CORE]); }); test("an id that is not a scenario id is refused, so a typo cannot leave a test unquarantined", () => { @@ -83,13 +109,13 @@ test.describe("security quarantine list", () => { }); test("quarantinedDefect names the defect of a listed id and nothing for an unlisted one", () => { - expect(quarantinedDefect(FIXED_ID)).toBe(FIXED_ON_BRANCH[FIXED_ID]); + expect(quarantinedDefect(FIXED_LC_ID)).toBe(FIXED_ON_BRANCH[FIXED_LC_ID]); expect(quarantinedDefect(OPEN_ID)).toBe(OPEN_DEFECTS[OPEN_ID]); expect(quarantinedDefect(PASSING_ID)).toBeUndefined(); }); test("the default run leaves a quarantined security test out and E2E_INCLUDE_QUARANTINE brings it back", () => { - const quarantined = titleWithTags(FIXED_ID, securityTestDetails(FIXED_ID).tag); + const quarantined = titleWithTags(OTHER_OPEN_ID, securityTestDetails(OTHER_OPEN_ID).tag); const passing = titleWithTags(PASSING_ID, securityTestDetails(PASSING_ID).tag); const defaultRun = grepInvertFor(runFlagsFromEnv({})); const withQuarantine = grepInvertFor(runFlagsFromEnv({ [RUN_FLAGS.INCLUDE_QUARANTINE]: "1" })); @@ -107,7 +133,7 @@ test.describe("security quarantine list", () => { expect(securityCandidateDetails("SEC-A98a", "x", [TAGS.CORE]).tag, "extra tags last").toEqual([TAGS.SECURITY, TAGS.QUARANTINE, TAGS.CORE]); expect(() => securityCandidateDetails("SEC-A02", "x"), "pattern needs two digits").not.toThrow(); expect(() => securityCandidateDetails("bad", "x")).toThrow(/is not a security scenario id/); - expect(() => securityCandidateDetails(FIXED_ID, "x"), "an id of a map").toThrow(/quarantine map/); + expect(() => securityCandidateDetails(OTHER_OPEN_ID, "x"), "an id of a map").toThrow(/quarantine map/); expect(() => securityCandidateDetails("SEC-A98a", " "), "no measurement").toThrow(/names what was measured/); }); diff --git a/e2e/tests/security/bundles.spec.ts b/e2e/tests/security/bundles.spec.ts index 2e88d7700b..e14efaa86a 100644 --- a/e2e/tests/security/bundles.spec.ts +++ b/e2e/tests/security/bundles.spec.ts @@ -8,7 +8,9 @@ import { createBundle, currentUser, grantBundlePermission, + publishBundle, recycleBundle, + setBundlePublicToAll, switchOrganization, } from "../../src/api/client"; import { @@ -211,7 +213,7 @@ test.describe("security: bundles inside one workspace", () => { const answer = await apiRaw(m.request, "POST", API_PATHS.BUNDLES, { data: { orgId: a.orgId, name: BUNDLE_OF_MEMBER } }); - // Desired: the refusal of a plain member (R06a). The dev check reads the CURRENT workspace, where M is admin (SF-36, open on HEAD). + // The refusal of a plain member (R06a); the dev check now reads the TARGET workspace, where M is only a plain member (D-11, D-41). expectAnswer(answer, API_ERRORS.NEED_DEV_TO_CREATE_RESOURCE, "the member's bundle create with its own workspace current"); expect((await apiRaw(a.request, "GET", API_PATHS.BUNDLE_LIST)).body, "after: no bundle of M in OA").not.toContain(BUNDLE_OF_MEMBER); }); @@ -236,6 +238,44 @@ test.describe("security: bundles inside one workspace", () => { expect(answer.body, "and no test id of its button").not.toContain(SEEDED_BUTTON_TEST_ID); }); + test("SEC-R17g a public bundle's published view carries no editing DSL of the apps added to it", securityTestDetails("SEC-R17g"), async ({ + page, + apiUser, + actor, + newUserSession, + }) => { + const { a, seeded } = await sceneOf(page, apiUser); + const o = await actor("outsider"); + const anonymous = (await newUserSession()).page.request; + const bundleId = await createBundle(a.request, { orgId: a.orgId, name: BUNDLE_NAME }); + await addAppToBundle(a.request, seeded.appId, bundleId); + + const own = await bundleElementsRaw(a.request, bundleId); + expect(own.body, "before: A's elements carry the app's draft").toContain(SEEDED_BUTTON_TEXT); + expect(own.body, "before: and its button test id").toContain(SEEDED_BUTTON_TEST_ID); + expect(own.body, "before: and its data source id").toContain(seeded.datasourceId); + expectAnswer(await apiRaw(o.request, "GET", bundleViewPath(bundleId)), API_ERRORS.NO_PERMISSION_TO_REQUEST_APP, "before: the bundle is not public yet"); + + await publishBundle(a.request, bundleId); + await setBundlePublicToAll(a.request, bundleId, true); + + const view = await apiRaw(o.request, "GET", bundleViewPath(bundleId)); + expectAnswer(view, OK, "the outsider's view of the published, public bundle"); + expect(view.body, "the published DSL still holds the app element").toContain(seeded.appId); + expect(view.body, "no button text of the app's draft").not.toContain(SEEDED_BUTTON_TEXT); + expect(view.body, "no button test id of the app's draft").not.toContain(SEEDED_BUTTON_TEST_ID); + expect(view.body, "no data source id of the app's query").not.toContain(seeded.datasourceId); + + // Pins the boundary of the defect (README, D-42): by code, /api/** requires authentication and answers 401 before any + // bundle code runs, so this passes on the unfixed image too and does NOT by itself prove the fix (the checks above do). + const anon = await apiRaw(anonymous, "GET", bundleViewPath(bundleId)); + expectAnswer(anon, API_ERRORS.UNAUTHENTICATED, "an anonymous caller's view of the public bundle"); + expect(anon.body, "no body on the 401").toBe(""); + expect(anon.body, "no button text leaks to an anonymous caller either").not.toContain(SEEDED_BUTTON_TEXT); + expect(anon.body, "no button test id leaks to an anonymous caller either").not.toContain(SEEDED_BUTTON_TEST_ID); + expect(anon.body, "no data source id leaks to an anonymous caller either").not.toContain(seeded.datasourceId); + }); + test("SEC-R17d a bundle viewer can neither recycle nor delete the bundle", securityTestDetails("SEC-R17d"), async ({ page, apiUser, actor }) => { const { a, d, bundleId } = await developerBundle(page, apiUser, actor); const m = await memberOf(a, actor, "member"); diff --git a/e2e/tests/security/credentials.spec.ts b/e2e/tests/security/credentials.spec.ts index 148f8b337f..dad6b34abd 100644 --- a/e2e/tests/security/credentials.spec.ts +++ b/e2e/tests/security/credentials.spec.ts @@ -179,8 +179,9 @@ test.describe("security: forged and revoked credentials (further rows)", () => { const fresh = await newUserSession(); await signIn(fresh.page.request, first.email, CHANGED_PASSWORD); expect(await currentUserId(fresh.page.request), "setup: the new password works, so the password really changed").toBe(first.userId); - // Desired: the second session, opened with the old password, is dead. It is not on 3.0.0 or on HEAD (SF-29). + // D-34: the second session, opened with the old password, is dead; the session that made the change is kept. expectAnswer(await apiRaw(secondSession.page.request, "GET", API_PATHS.USER_MY_ORG), API_ERRORS.UNAUTHENTICATED, "after: the other session"); + expectAnswer(await apiRaw(first.request, "GET", API_PATHS.USER_MY_ORG), ALLOWED, "after: the session that changed the password still works"); }); test("SEC-A05 forwarding headers do not open the node-service route", securityTestDetails("SEC-A05"), async ({ page, apiUser, actor }) => { diff --git a/e2e/tests/security/cross-org.spec.ts b/e2e/tests/security/cross-org.spec.ts index e68724e019..3abd7b8892 100644 --- a/e2e/tests/security/cross-org.spec.ts +++ b/e2e/tests/security/cross-org.spec.ts @@ -127,6 +127,8 @@ const PLAIN_TEXT = { "content-type": "text/plain" }; const FOLDER_DENIALS = [API_ERRORS.FOLDER_OPERATE_NO_PERMISSION, API_ERRORS.NOT_AUTHORIZED]; /** The answer of an allowed call. */ const OK = { status: 200, code: API_OK } as const; +/** HTTP status of an allowed call, for an assertion that checks only the status, not the envelope code. */ +const HTTP_OK = 200; /** The profile photo A has before the outsider's delete: the 8x8 PNG of src/media.ts, as bytes. */ const PHOTO = { name: "photo.png", mimeType: "image/png", buffer: Buffer.from(PNG_RED.split(",")[1] ?? "", "base64") }; @@ -544,9 +546,37 @@ test.describe("security: another workspace's resources (further rows)", () => { const answer = await apiRaw(b.request, "PUT", appSlugPath(seeded.appId), { data: OUTSIDER_SLUG, headers: PLAIN_TEXT }); expectAnswer(answer, API_ERRORS.NOT_AUTHORIZED, "the outsider's app slug change"); + // Limit: no app view carries the slug and the slug write is not reached today (D-37), so this read cannot show a stored slug; the denial above is the proof. expect((await apiRaw(a.request, "GET", applicationPath(seeded.appId))).body, "after: the slug was not stored").not.toContain(OUTSIDER_SLUG); }); + /** A well-formed object id that names no application; no hyphen, so the lookup tries it as an object id, then as a slug. */ + const UNKNOWN_APP_ID = "000000000000000000000000"; + /** The slug an editor is allowed to set, as the positive control of SEC-C16f. */ + const EDITOR_SLUG = "e2e-sec-slug-by-editor"; + + test("SEC-C16g+ the app's editor is not refused by the slug route", securityTestDetails("SEC-C16g+"), async ({ page, apiUser, actor }) => { + const { a, b, seeded } = await sceneOf(page, apiUser, actor); + await joinWorkspace(a, b); + await grantApp(a, seeded.appId, b, APP_ROLES.EDITOR); + expectAnswer(await apiRaw(b.request, "GET", applicationPath(seeded.appId)), OK, "precondition: B edits the app"); + + const answer = await apiRaw(b.request, "PUT", appSlugPath(seeded.appId), { data: EDITOR_SLUG, headers: PLAIN_TEXT }); + + // The body is not asserted: it is empty today because the write is not reached (D-37, the slug-exists query + // completes empty for a fresh slug) and would carry the app once that query is repaired. + expect(answer.status, "the editor's slug change is not refused").toBe(HTTP_OK); + expect(answer.code, "not the denial").not.toBe(API_ERRORS.NOT_AUTHORIZED.code); + }); + + test("SEC-C16h the app slug route answers NO_RESOURCE_FOUND for an id that names no app", securityTestDetails("SEC-C16h"), async ({ page, apiUser, actor }) => { + const { b } = await sceneOf(page, apiUser, actor); + + const answer = await apiRaw(b.request, "PUT", appSlugPath(UNKNOWN_APP_ID), { data: OUTSIDER_SLUG, headers: PLAIN_TEXT }); + + expectAnswer(answer, API_ERRORS.NO_RESOURCE_FOUND, "the slug change of an unknown app"); + }); + test("SEC-C17a an outsider cannot create an invitation to another workspace", securityTestDetails("SEC-C17a"), async ({ page, apiUser, actor }) => { const { a, b } = await sceneOf(page, apiUser, actor); @@ -683,13 +713,15 @@ test.describe("security: another workspace's resources (further rows)", () => { await createSnapshot(a.request, seeded.appId, (await getApp(a.request, seeded.appId)).dsl as object); const snapshotId = (await listSnapshots(a.request, seeded.appId))[0]?.snapshotId; expect(snapshotId, "setup: A has a snapshot").toBeTruthy(); + const ownRead = await apiRaw(a.request, "GET", snapshotPath(seeded.appId, snapshotId ?? "")); + expectAnswer(ownRead, OK, "before: the owner reads the snapshot through its own app"); + expect(ownRead.body, "before: the owner's answer carries A's DSL").toContain(SEEDED_BUTTON_TEST_ID); const appOfB = await appOfOutsider(b); const answer = await apiRaw(b.request, "GET", snapshotPath(appOfB, snapshotId ?? "")); - // Not narrowable on any available image: the 3.0.0 server lets the call through, so the desired code was never observed. - // The first run against an updated server should replace this list with the one answer it gives. - expectDeniedAs(answer, [API_ERRORS.INVALID_HISTORY_SNAPSHOT, API_ERRORS.NOT_AUTHORIZED], "the outsider reads A's snapshot through B's app"); + // D-31: the snapshot of another app gets the answer of an unknown snapshot id (same status, code and message). + expectAnswer(answer, API_ERRORS.INVALID_HISTORY_SNAPSHOT, "the outsider reads A's snapshot through B's app"); expect(answer.body, "A's DSL is not in the answer").not.toContain(SEEDED_BUTTON_TEST_ID); }); diff --git a/e2e/tests/security/draft-queries.spec.ts b/e2e/tests/security/draft-queries.spec.ts new file mode 100644 index 0000000000..ebc71a2bff --- /dev/null +++ b/e2e/tests/security/draft-queries.spec.ts @@ -0,0 +1,161 @@ +import { apiRaw, createApp, createModule, executeAppQueryRaw, publishApp, updateApp } from "../../src/api/client"; +import { API_ERRORS, API_OK, APP_ROLES, PRODUCTS, applicationPath } from "../../src/constants"; +import { appDsl, button, moduleApp, moduleInstance, postgresQuery } from "../../src/dsl/builders"; +import { expect, test } from "../../src/fixtures"; +import { expectAnswer } from "../../src/security/assertions"; +import { securityTestDetails } from "../../src/security/quarantine"; +import { grantApp } from "../../src/security/actors"; +import { memberOf, sceneOf } from "../../src/security/scene"; + +/** + * Draft and module queries by role (D-10): `POST /api/query/execute` in edit mode needs EDIT on the app; a module run + * in another app's (the host's) editor needs EDIT on the host, membership, and READ on the module itself, and runs + * the module's published queries, never its draft (a never-published module's draft IS its only version, accepted + * behaviour). A = `apiUser` (admin of OA, owner of everything); E = a plain member with grants as stated; V = a plain + * member with VIEWER only. + */ + +const ALLOWED = { status: 200, code: API_OK } as const; + +function moduleWithQueries(queries: object[]): object { + return { ...moduleApp({}), queries }; +} + +function hostOf(moduleId: string): object { + return appDsl([moduleInstance({ id: "m1", name: "module1", moduleId })]); +} + +test.describe("security: draft and module queries by role (D-10)", () => { + test("SEC-R19a+ an app editor runs the app's draft-only query", securityTestDetails("SEC-R19a"), async ({ page, apiUser, actor }) => { + const { a, seeded } = await sceneOf(page, apiUser); + const draftOnly = postgresQuery({ id: "q2", name: "draftOnly", datasourceId: seeded.datasourceId, sql: "SELECT 'e2e-sec-r19-draft' AS marker" }); + const dsl = appDsl([button({ id: "b1", name: "button1", text: "x", testId: "e2e-sec-r19a" })], { + queries: [postgresQuery({ id: seeded.queryId, name: seeded.queryName, datasourceId: seeded.datasourceId, sql: "SELECT * FROM products ORDER BY id" }), draftOnly], + }); + await updateApp(a.request, seeded.appId, { dsl }); + const e = await memberOf(a, actor, "editor"); + await grantApp(a, seeded.appId, e, APP_ROLES.EDITOR); + + const viewModeRun = await executeAppQueryRaw(e.request, { applicationId: seeded.appId, queryId: "q2", viewMode: true }); + expectAnswer(viewModeRun, API_ERRORS.QUERY_NOT_FOUND, "before: view mode cannot find the draft-only query"); + + const draftRun = await executeAppQueryRaw(e.request, { applicationId: seeded.appId, queryId: "q2", viewMode: false }); + expectAnswer(draftRun, ALLOWED, "E's edit-mode run of the draft-only query"); + expect(draftRun.body, "with its marker").toContain("e2e-sec-r19-draft"); + + const q1Run = await executeAppQueryRaw(e.request, { applicationId: seeded.appId, queryId: seeded.queryId, viewMode: false }); + expectAnswer(q1Run, ALLOWED, "E's edit-mode run of q1"); + expect(q1Run.body, "with product rows").toContain(PRODUCTS.FIRST_NAME); + }); + + test("SEC-R19b an app viewer cannot run the app's draft queries", securityTestDetails("SEC-R19b"), async ({ page, apiUser, actor }) => { + const { a, seeded } = await sceneOf(page, apiUser); + const draftOnly = postgresQuery({ id: "q2", name: "draftOnly", datasourceId: seeded.datasourceId, sql: "SELECT 'e2e-sec-r19-draft' AS marker" }); + const q1Draft = postgresQuery({ id: seeded.queryId, name: seeded.queryName, datasourceId: seeded.datasourceId, sql: "SELECT 'e2e-sec-r19-q1-draft' AS marker" }); + const dsl = appDsl([button({ id: "b1", name: "button1", text: "x", testId: "e2e-sec-r19b" })], { queries: [q1Draft, draftOnly] }); + await updateApp(a.request, seeded.appId, { dsl }); + const v = await memberOf(a, actor, "viewer"); + await grantApp(a, seeded.appId, v, APP_ROLES.VIEWER); + + const vViewRun = await executeAppQueryRaw(v.request, { applicationId: seeded.appId, queryId: seeded.queryId, viewMode: true }); + expectAnswer(vViewRun, ALLOWED, "before: V's view-mode run of q1 (the grant works)"); + expect(vViewRun.body, "the live (published) version, with product rows").toContain(PRODUCTS.FIRST_NAME); + const aDraftRun = await executeAppQueryRaw(a.request, { applicationId: seeded.appId, queryId: "q2", viewMode: false }); + expectAnswer(aDraftRun, ALLOWED, "before: A's edit-mode run of q2"); + expect(aDraftRun.body, "with its marker (the grant and the query both work)").toContain("e2e-sec-r19-draft"); + + const vDraftOnlyRun = await executeAppQueryRaw(v.request, { applicationId: seeded.appId, queryId: "q2", viewMode: false }); + expectAnswer(vDraftOnlyRun, API_ERRORS.NOT_AUTHORIZED, "V's edit-mode run of the draft-only query"); + expect(vDraftOnlyRun.body, "no draft marker").not.toContain("e2e-sec-r19-draft"); + + const vQ1DraftRun = await executeAppQueryRaw(v.request, { applicationId: seeded.appId, queryId: seeded.queryId, viewMode: false }); + expectAnswer(vQ1DraftRun, API_ERRORS.NOT_AUTHORIZED, "V's edit-mode run of q1's draft"); + expect(vQ1DraftRun.body, "no draft marker, no rows").not.toContain("e2e-sec-r19-q1-draft"); + expect(vQ1DraftRun.body, "and no published product rows either (the request was denied outright)").not.toContain(PRODUCTS.FIRST_NAME); + }); + + test("SEC-R19c a host editor runs a module's published query, never its draft", securityTestDetails("SEC-R19c"), async ({ page, apiUser, actor }) => { + const { a, seeded } = await sceneOf(page, apiUser); + const mq1Live = postgresQuery({ id: "mq1", name: "mq1", datasourceId: seeded.datasourceId, sql: "SELECT 'e2e-sec-r19-live' AS marker" }); + const module = await createModule(a.request, { orgId: a.orgId, name: "e2e-sec-r19c-module", dsl: moduleWithQueries([mq1Live]) }); + await publishApp(a.request, module.appId); + const mq1Draft = postgresQuery({ id: "mq1", name: "mq1", datasourceId: seeded.datasourceId, sql: "SELECT 'e2e-sec-r19-draft-mq1' AS marker" }); + const mq2DraftOnly = postgresQuery({ id: "mq2", name: "mq2", datasourceId: seeded.datasourceId, sql: "SELECT 'e2e-sec-r19-draft-only-mq2' AS marker" }); + await updateApp(a.request, module.appId, { dsl: moduleWithQueries([mq1Draft, mq2DraftOnly]) }); + + const host = await createApp(a.request, { orgId: a.orgId, name: "e2e-sec-r19c-host", dsl: appDsl([moduleInstance({ id: "m1", name: "module1", moduleId: module.appId })]) }); + const e = await memberOf(a, actor, "editor"); + await grantApp(a, host.appId, e, APP_ROLES.EDITOR); + await grantApp(a, module.appId, e, APP_ROLES.VIEWER); + + const aViewMq1 = await executeAppQueryRaw(a.request, { applicationId: module.appId, queryId: "mq1", viewMode: true }); + expectAnswer(aViewMq1, ALLOWED, "before: A's view-mode run of mq1 on M (live)"); + expect(aViewMq1.body, "the live marker").toContain("e2e-sec-r19-live"); + const aEditMq2 = await executeAppQueryRaw(a.request, { applicationId: module.appId, queryId: "mq2", viewMode: false }); + expectAnswer(aEditMq2, ALLOWED, "before: A's edit-mode run of mq2 on M (draft-only)"); + expect(aEditMq2.body, "the draft-only marker").toContain("e2e-sec-r19-draft-only-mq2"); + + const eMq1ThroughHost = await executeAppQueryRaw(e.request, { applicationId: module.appId, queryId: "mq1", viewMode: false, path: [host.appId] }); + expectAnswer(eMq1ThroughHost, ALLOWED, "E's edit-mode run of mq1 through the host"); + expect(eMq1ThroughHost.body, "the live marker, never the draft").toContain("e2e-sec-r19-live"); + expect(eMq1ThroughHost.body, "never the draft marker").not.toContain("e2e-sec-r19-draft-mq1"); + + const eMq2ThroughHost = await executeAppQueryRaw(e.request, { applicationId: module.appId, queryId: "mq2", viewMode: false, path: [host.appId] }); + expectAnswer(eMq2ThroughHost, API_ERRORS.QUERY_NOT_FOUND, "E's edit-mode run of mq2 (draft-only) through the host"); + expect(eMq2ThroughHost.body, "no draft-only marker").not.toContain("e2e-sec-r19-draft-only-mq2"); + + const eMq1OwnEditor = await executeAppQueryRaw(e.request, { applicationId: module.appId, queryId: "mq1", viewMode: false }); + expectAnswer(eMq1OwnEditor, API_ERRORS.NOT_AUTHORIZED, "E's edit-mode run of mq1 in M's own editor (E does not edit M)"); + expect(eMq1OwnEditor.body, "no marker at all").not.toContain("e2e-sec-r19"); + }); + + test( + "SEC-R19d a host editor cannot run, through its host, a module it may not read", + securityTestDetails("SEC-R19d"), + async ({ page, apiUser, actor }) => { + const { a, seeded } = await sceneOf(page, apiUser); + const mq1Live = postgresQuery({ id: "mq1", name: "mq1", datasourceId: seeded.datasourceId, sql: "SELECT 'e2e-sec-r19d-live' AS marker" }); + const module = await createModule(a.request, { orgId: a.orgId, name: "e2e-sec-r19d-module", dsl: moduleWithQueries([mq1Live]) }); + await publishApp(a.request, module.appId); + const host = await createApp(a.request, { orgId: a.orgId, name: "e2e-sec-r19d-host", dsl: appDsl([]) }); + const e = await memberOf(a, actor, "editor"); + await grantApp(a, host.appId, e, APP_ROLES.EDITOR); + + const save = await apiRaw(e.request, "PUT", applicationPath(host.appId), { data: { editingApplicationDSL: hostOf(module.appId) } }); + expectAnswer(save, ALLOWED, "before: E's save injecting the module into the host (the save checks no module right)"); + const aRun = await executeAppQueryRaw(a.request, { applicationId: module.appId, queryId: "mq1", viewMode: false, path: [host.appId] }); + expectAnswer(aRun, ALLOWED, "before: A's edit-mode run of mq1 with a valid path and membership"); + expect(aRun.body, "the live marker").toContain("e2e-sec-r19d-live"); + + const eRun = await executeAppQueryRaw(e.request, { applicationId: module.appId, queryId: "mq1", viewMode: false, path: [host.appId] }); + expectAnswer(eRun, API_ERRORS.NOT_AUTHORIZED, "E's edit-mode run of mq1 through the host E injected but may not read"); + expect(eRun.body, "no marker").not.toContain("e2e-sec-r19d-live"); + }, + ); + + test( + "SEC-R19e a never-published module runs its draft for a host editor who may read it, but not in its own editor", + securityTestDetails("SEC-R19e"), + async ({ page, apiUser, actor }) => { + const { a, seeded } = await sceneOf(page, apiUser); + const nq1 = postgresQuery({ id: "nq1", name: "nq1", datasourceId: seeded.datasourceId, sql: "SELECT 'e2e-sec-r19-unpublished' AS marker" }); + const module2 = await createModule(a.request, { orgId: a.orgId, name: "e2e-sec-r19e-module", dsl: moduleWithQueries([nq1]) }); + const host = await createApp(a.request, { orgId: a.orgId, name: "e2e-sec-r19e-host", dsl: appDsl([moduleInstance({ id: "m1", name: "module1", moduleId: module2.appId })]) }); + const e = await memberOf(a, actor, "editor"); + await grantApp(a, host.appId, e, APP_ROLES.EDITOR); + await grantApp(a, module2.appId, e, APP_ROLES.VIEWER); + + const eViewRun = await executeAppQueryRaw(e.request, { applicationId: module2.appId, queryId: "nq1", viewMode: true }); + expectAnswer(eViewRun, ALLOWED, "before: E's view-mode run of nq1 on M2 (READ already runs the only version)"); + expect(eViewRun.body, "with the marker").toContain("e2e-sec-r19-unpublished"); + + const eThroughHost = await executeAppQueryRaw(e.request, { applicationId: module2.appId, queryId: "nq1", viewMode: false, path: [host.appId] }); + expectAnswer(eThroughHost, ALLOWED, "E's edit-mode run of nq1 through the host (accepted, 3.3 b)"); + expect(eThroughHost.body, "with the marker").toContain("e2e-sec-r19-unpublished"); + + const eOwnEditor = await executeAppQueryRaw(e.request, { applicationId: module2.appId, queryId: "nq1", viewMode: false }); + expectAnswer(eOwnEditor, API_ERRORS.NOT_AUTHORIZED, "E's edit-mode run of nq1 in M2's own editor (E does not edit M2)"); + expect(eOwnEditor.body, "no marker").not.toContain("e2e-sec-r19-unpublished"); + }, + ); +}); diff --git a/e2e/tests/security/enterprise.spec.ts b/e2e/tests/security/enterprise.spec.ts index 1bc258e805..d33281c9c1 100644 --- a/e2e/tests/security/enterprise.spec.ts +++ b/e2e/tests/security/enterprise.spec.ts @@ -44,6 +44,13 @@ const MEMBER_TAG = "user"; const ADMIN_TAG = "admin"; const UNKNOWN_ADDRESS_TAG = "nobody"; +/** + * File-wide (trace/screenshot/video cannot be set in a describe group: Playwright forces a new worker and refuses). + * SEC-E07a/b reset a password and must keep it out of every artifact; applying this to the whole file costs nothing, + * since it only removes debugging artifacts and changes no assertion. + */ +test.use({ trace: "off", screenshot: "off", video: "off" }); + function bearer(token: string): Record { return { [AUTHORIZATION_HEADER]: `${BEARER_PREFIX}${token}` }; } @@ -170,3 +177,40 @@ test.describe("security: the ENTERPRISE stack", () => { }, ); }); + +/** SEC-E07a, SEC-E07b: an admin password reset and the sessions of the reset user (D-34). The reset answer carries a new + * password, so no artifact of these tests keeps a response body and no assertion receives one. */ +test.describe("security: the ENTERPRISE stack, sessions after a password reset", () => { + test( + "SEC-E07a an admin's reset of a member's password ends the member's sessions", + securityTestDetails("SEC-E07a", [TAGS.ENTERPRISE, TAGS.SUPERADMIN]), + async ({ actor, superAdmin }) => { + const a = await enterpriseAdmin(superAdmin, actor, ADMIN_TAG); + const u = await actor(MEMBER_TAG); + expectAnswer(await apiRaw(u.request, "GET", API_PATHS.USER_MY_ORG), ALLOWED, "before: U's session works"); + + const reset = await apiRaw(a.request, "POST", API_PATHS.USER_RESET_PASSWORD, { data: { userId: u.userId } }); + + expectAnswer(reset, ALLOWED, "A's reset of U's password"); + expectAnswer(await apiRaw(u.request, "GET", API_PATHS.USER_MY_ORG), API_ERRORS.UNAUTHENTICATED, "after: U's session from before the reset"); + expectAnswer(await apiRaw(a.request, "GET", API_PATHS.USER_MY_ORG), ALLOWED, "control: a reset of someone else leaves A's own session alone"); + }, + ); + + test( + "SEC-E07b an admin who resets its own password keeps the session that asked and loses its other one", + securityTestDetails("SEC-E07b", [TAGS.ENTERPRISE, TAGS.SUPERADMIN]), + async ({ actor, superAdmin, newUserSession }) => { + const a = await enterpriseAdmin(superAdmin, actor, ADMIN_TAG); + const other = (await newUserSession()).page.request; + await signIn(other, a.email); + expectAnswer(await apiRaw(other, "GET", API_PATHS.USER_MY_ORG), ALLOWED, "before: A's second session works"); + + const reset = await apiRaw(a.request, "POST", API_PATHS.USER_RESET_PASSWORD, { data: { userId: a.userId } }); + + expectAnswer(reset, ALLOWED, "A's reset of its own password"); + expectAnswer(await apiRaw(a.request, "GET", API_PATHS.USER_MY_ORG), ALLOWED, "after: the session that asked for the reset still works"); + expectAnswer(await apiRaw(other, "GET", API_PATHS.USER_MY_ORG), API_ERRORS.UNAUTHENTICATED, "after: A's other session"); + }, + ); +}); diff --git a/e2e/tests/security/membership-changes.spec.ts b/e2e/tests/security/membership-changes.spec.ts index b64c5f1640..48198062fb 100644 --- a/e2e/tests/security/membership-changes.spec.ts +++ b/e2e/tests/security/membership-changes.spec.ts @@ -82,7 +82,7 @@ test.describe("security: rights that change while a session is open", () => { await expect(view.buttonByTestId(SEEDED_BUTTON_TEST_ID), "and no app").toHaveCount(0); }); - test("SEC-R11b a developer removed from the workspace cannot open the editing view of the app it created", securityTestDetails("SEC-R11b"), async ({ page, apiUser, actor }) => { + test("SEC-R11b a developer removed from the workspace cannot open the editing view of the app it created", securityTestDetails("SEC-R11b"), async ({ page, apiUser, actor }, testInfo) => { const { a } = await sceneOf(page, apiUser); const d = await memberOf(a, actor, "developer"); await makeDeveloper(a, d); @@ -91,8 +91,17 @@ test.describe("security: rights that change while a session is open", () => { await removeOrgMember(a.request, a.orgId, d.userId); - // READ of the app stays allowed by design (commit c377186ad); the editing view is EDIT and must not be. - expectAnswer(await apiRaw(d.request, "GET", appViewPath(appId)), ALLOWED, "the removed creator's published view (by design)"); + // READ of the app stays allowed by the creator-shortcut (commit c377186ad), an unrevoked mechanism separate from + // the member-leave clean-up's stored-row deletion (README D-26 and D-60 residuals); the editing view + // is EDIT and must not be. LC-DL13 (quarantined candidate) asserts the denial this leaves open. + const removedView = await apiRaw(d.request, "GET", appViewPath(appId)); + expectAnswer(removedView, ALLOWED, "the removed creator's published view (creator-shortcut VIEWER row)"); + if (removedView.status === ALLOWED.status && removedView.code === ALLOWED.code) { + testInfo.annotations.push({ + type: "defect", + description: "D-26 residual, LC-DL13 candidate: the removed creator's published view stays allowed through the creator-shortcut VIEWER row", + }); + } expectAnswer(await apiRaw(d.request, "GET", applicationPath(appId)), API_ERRORS.NO_PERMISSION_TO_REQUEST_APP, "the removed creator's editing view"); }); diff --git a/e2e/tests/security/outbound.spec.ts b/e2e/tests/security/outbound.spec.ts index cd76803a76..608855d84d 100644 --- a/e2e/tests/security/outbound.spec.ts +++ b/e2e/tests/security/outbound.spec.ts @@ -1,9 +1,14 @@ -import { apiRaw, setNpmRegistry, setPublicToAll, type RawAnswer } from "../../src/api/client"; -import { npmRegistryPath } from "../../src/constants"; +import { apiRaw, createApp, createModule, publishApp, setNpmRegistry, setPublicToAll, type RawAnswer } from "../../src/api/client"; +import { API_ERRORS, API_OK, API_PATHS, APP_ROLES, appViewPath, npmRegistryPath } from "../../src/constants"; +import { appDsl, moduleApp, moduleInstance, type DslItem } from "../../src/dsl/builders"; import { expect, test } from "../../src/fixtures"; +import { AppViewPage } from "../../src/pages/AppViewPage"; +import { expectAnswer } from "../../src/security/assertions"; import type { EchoRecord, EchoTarget } from "../../src/security/echo"; +import { recordsContain } from "../../src/security/echo"; import { securityTestDetails } from "../../src/security/quarantine"; -import { sceneOf, type Scene } from "../../src/security/scene"; +import { memberOf, sceneOf, type Scene } from "../../src/security/scene"; +import { grantApp } from "../../src/security/actors"; /** * Requests the SERVER makes inside the app container, proven at the HTTP echo sidecar (scripts/echo-server.js, `echo` fixture): @@ -15,14 +20,40 @@ import { sceneOf, type Scene } from "../../src/security/scene"; */ const STATUS_OK = 200; -const CLIENT_ERROR_MIN = 400; -const CLIENT_ERROR_MAX_EXCLUSIVE = 500; /** The package the signed-in admin asks for (the positive control) and the one an actor under test asks for, so their records tell apart. */ const CONTROL_PACKAGE = "e2e-pkg"; const PROBE_PACKAGE = "e2e-pkg-probe"; /** The echo answers every request with an empty JSON object; the proxy hands it on. */ const ECHO_ANSWER_BODY = "{}"; +/** SEC-X01e+: the package name of the npm component embedded in the module, and a second, distinct package for the + * direct-module-call contrast (neither is a substring of the other, so their echo records cannot mix). */ +const MODULE_PROBE_PACKAGE = "e2e-pkg-module-probe"; +const DIRECT_PROBE_PACKAGE = "e2e-pkg-direct"; +const PROBE_VERSION = "1.0.0"; +const PROBE_COMP_NAME = "probe"; +const NPM_PROBE_ITEM_ID = "npm1"; +const NPM_PROBE_NAME = "npmProbe1"; +const NPM_PROBE_SIZE = { w: 12, h: 6 }; + +/** The format of `getRemoteCompType` (client/src/comps/utils/remote.ts:5-12): `remote#npm#@#`. */ +function npmProbeCompType(packageName: string): string { + return `remote#npm#${packageName}@${PROBE_VERSION}#${PROBE_COMP_NAME}`; +} + +/** + * A DSL item for an npm-remote component (`gridItemComp.tsx` turns any `remote#...` compType into a `remoteComp`, + * whose loader starts on mount regardless of `comp`'s contents). Not built with `component(...)`: that starts from a + * recording (`fixtures/dsl/.json`), and no recording exists for a `remote#npm#...` type. + */ +function npmProbeItem(packageName: string): DslItem { + return { + id: NPM_PROBE_ITEM_ID, + layout: { x: 0, y: 0, ...NPM_PROBE_SIZE }, + item: { compType: npmProbeCompType(packageName), name: NPM_PROBE_NAME, comp: {} }, + }; +} + interface RegistryScene extends Scene { /** The dummy registry credential of this test; not a secret, a marker that shows which request carried it. */ token: string; @@ -75,11 +106,8 @@ test.describe("security: the npm registry proxy and the echo sidecar", () => { const answer = await registryCall(anonymous, scene, PROBE_PACKAGE); // read the echo BEFORE asserting, so a failure reports both properties: the answer class and what was forwarded const forwarded = recordOf(await echo.received(), echo, PROBE_PACKAGE); - expect.soft( - answer.status >= CLIENT_ERROR_MIN && answer.status < CLIENT_ERROR_MAX_EXCLUSIVE, - `the anonymous call on the private app is answered 4xx (got ${answer.status})`, - ).toBe(true); expect.soft(forwarded, "nothing of the anonymous call reached the echo").toEqual([]); + expectAnswer(answer, API_ERRORS.NOT_AUTHORIZED, "the anonymous call on the private app"); }); test("SEC-X01c a signed-in outsider's call on a private app is refused before anything is forwarded", securityTestDetails("SEC-X01c"), async ({ page, apiUser, actor, echo }) => { @@ -89,11 +117,8 @@ test.describe("security: the npm registry proxy and the echo sidecar", () => { const answer = await registryCall(outsider.request, scene, PROBE_PACKAGE); // read the echo BEFORE asserting, so a failure reports both properties: the answer class and what was forwarded const forwarded = recordOf(await echo.received(), echo, PROBE_PACKAGE); - expect.soft( - answer.status >= CLIENT_ERROR_MIN && answer.status < CLIENT_ERROR_MAX_EXCLUSIVE, - `the outsider's call on the private app is answered 4xx (got ${answer.status})`, - ).toBe(true); expect.soft(forwarded, "nothing of the outsider's call reached the echo").toEqual([]); + expectAnswer(answer, API_ERRORS.NOT_AUTHORIZED, "the outsider's call on the private app"); }); test("SEC-X01d+ an anonymous call on a public app still reaches the echo (intended use)", securityTestDetails("SEC-X01d"), async ({ page, apiUser, newUserSession, echo }) => { @@ -107,4 +132,58 @@ test.describe("security: the npm registry proxy and the echo sidecar", () => { expect(records, "the echo received the anonymous call").toHaveLength(1); expect(records[0]?.headers.authorization, "the registry credential rides on it").toBe(`Bearer ${scene.token}`); }); + + test( + "SEC-X01e+ a viewer of the host app loads a module's npm component through the host app id", + securityTestDetails("SEC-X01e"), + async ({ page, apiUser, actor, echo }) => { + const scene = await registryScene(page, apiUser, echo); + + const module = await createModule(scene.a.request, { + orgId: scene.a.orgId, + name: "e2e-sec-x01e-module", + dsl: moduleApp({ items: [npmProbeItem(MODULE_PROBE_PACKAGE)] }), + }); + await publishApp(scene.a.request, module.appId); + const host = await createApp(scene.a.request, { + orgId: scene.a.orgId, + name: "e2e-sec-x01e-host", + dsl: appDsl([moduleInstance({ id: "m1", name: "module1", moduleId: module.appId })]), + }); + await publishApp(scene.a.request, host.appId); + + const b = await memberOf(scene.a, actor, "host-viewer"); + await grantApp(scene.a, host.appId, b, APP_ROLES.VIEWER); + expectAnswer( + await apiRaw(b.request, "GET", appViewPath(host.appId)), + { status: STATUS_OK, code: API_OK }, + "precondition: B reads the host", + ); + const moduleAnswer = await apiRaw(b.request, "GET", appViewPath(module.appId)); + expect(moduleAnswer.status, "precondition: B cannot read the module itself").not.toBe(STATUS_OK); + + const requestWait = b.session.page.waitForRequest( + (request) => request.url().includes(API_PATHS.NPM_PACKAGE) && request.url().includes(`/${MODULE_PROBE_PACKAGE}@`), + ); + const responseWait = b.session.page.waitForResponse( + (response) => response.url().includes(API_PATHS.NPM_PACKAGE) && response.url().includes(`/${MODULE_PROBE_PACKAGE}@`), + ); + await new AppViewPage(b.session.page).open(host.appId); + const [request, response] = await Promise.all([requestWait, responseWait]); + + expect(new URL(request.url()).pathname, "the request path's app id segment is the HOST app id, not the module's").toContain( + `${API_PATHS.NPM_PACKAGE}/${host.appId}/`, + ); + expect(response.status(), "the response is not a permission denial").not.toBe(API_ERRORS.NOT_AUTHORIZED.status); + const afterLoad = await echo.received(); + expect(recordsContain(afterLoad, MODULE_PROBE_PACKAGE), "the proxy forwarded this load to the echo").toBe(true); + + // Contrast: B's DIRECT call on the module (not through the host) is still refused. + await expectControlReachesEcho(scene, echo); + const directAnswer = await registryCall(b.request, { ...scene, seeded: { ...scene.seeded, appId: module.appId } }, DIRECT_PROBE_PACKAGE); + const forwarded = recordOf(await echo.received(), echo, DIRECT_PROBE_PACKAGE); + expect.soft(forwarded, "nothing of B's direct module call reached the echo").toEqual([]); + expectAnswer(directAnswer, API_ERRORS.NOT_AUTHORIZED, "B's direct call on the module"); + }, + ); }); diff --git a/e2e/tests/security/public-leakage.spec.ts b/e2e/tests/security/public-leakage.spec.ts index 42ad6f259d..883d569f85 100644 --- a/e2e/tests/security/public-leakage.spec.ts +++ b/e2e/tests/security/public-leakage.spec.ts @@ -96,6 +96,9 @@ test.describe("security: what a public app shows an anonymous visitor", () => { ); await updateApp(a.request, seeded.appId, { dsl }); expect(JSON.stringify((await getApp(a.request, seeded.appId)).dsl), "setup: the draft holds the new query").toContain(DRAFT_QUERY_ID); + const ownerDraftRun = await executeAppQueryRaw(a.request, { applicationId: seeded.appId, queryId: DRAFT_QUERY_ID, viewMode: false }); + expectAnswer(ownerDraftRun, ALLOWED, "before: the owner runs the draft-only query in edit mode"); + expect(ownerDraftRun.body, "with its marker").toContain("e2e-sec-draft-only"); const published = await apiRaw(anonymous, "GET", appViewPath(seeded.appId)); expect(published.body, "before: the published version does not have it").not.toContain(DRAFT_QUERY_NAME); const run = await executeAppQueryRaw(anonymous, { applicationId: seeded.appId, queryId: seeded.queryId, viewMode: true }); @@ -104,7 +107,7 @@ test.describe("security: what a public app shows an anonymous visitor", () => { const answer = await executeAppQueryRaw(anonymous, { applicationId: seeded.appId, queryId: DRAFT_QUERY_ID, viewMode: false }); - // Desired: a draft query needs EDIT, like the editing view (401 / 5001). 3.0.0 and HEAD check READ only (SF-5). + // A draft query needs EDIT on the app, like the editing view (401 / 5001) (D-10). expectAnswer(answer, API_ERRORS.NOT_AUTHORIZED, "the anonymous run of the draft-only query"); expect(answer.body, "no draft result in the answer").not.toContain("e2e-sec-draft-only"); }); @@ -170,12 +173,22 @@ test.describe("security: routes that need no session", () => { expect(answer.body, "no workspace id of A in the answer").not.toContain(a.orgId); }); - test("SEC-A10c the metrics endpoint is not open to an anonymous caller", securityTestDetails("SEC-A10c"), async ({ newUserSession }) => { + test("SEC-A10c the metrics endpoint is not open to an anonymous caller", securityTestDetails("SEC-A10c"), async ({ page, apiUser, newUserSession }) => { + const { a } = await sceneOf(page, apiUser); + const signedIn = await apiRaw(a.request, "GET", API_PATHS.STATUS_PROMETHEUS); + // Prometheus text format, not JSON: apiRaw's `code` is only ever set from a JSON body's `code` field, so a + // plain-text 200 answer has code: undefined; assert the HTTP status directly instead of expectAnswer/ALLOWED. + expect(signedIn.status, "before: a signed-in caller reads the Prometheus metrics").toBe(200); + expect(signedIn.body, "Prometheus text format").toContain("# HELP"); + const anonymous = (await newUserSession()).page.request; const answer = await apiRaw(anonymous, "GET", API_PATHS.STATUS_PROMETHEUS); - expectAnswer(answer, API_ERRORS.UNAUTHENTICATED, "the anonymous metrics request"); expect(answer.body, "with no body (no metrics text)").toBe(""); + + const byName = await apiRaw(anonymous, "GET", `${API_PATHS.STATUS_METRICS}/jvm.memory.used`); + expectAnswer(byName, API_ERRORS.UNAUTHENTICATED, "the anonymous named-metric request"); + expect(byName.body, "with no body (no metric value)").toBe(""); }); }); diff --git a/e2e/tests/security/roles.spec.ts b/e2e/tests/security/roles.spec.ts index 99b13c8363..67ac1ccf21 100644 --- a/e2e/tests/security/roles.spec.ts +++ b/e2e/tests/security/roles.spec.ts @@ -10,6 +10,7 @@ import { grantDatasourcePermission, listAppNames, listAppPermissions, + listAppVersions, listDatasourcePermissions, listGroups, listOrgMembers, @@ -73,6 +74,7 @@ import { SEEDED_APP_NAME, grantApp, joinWorkspace, + makeAdmin, makeDeveloper, seedPrivateApp, type Actor, @@ -337,6 +339,11 @@ const SERVER_CONFIG_VALUE = "e2e-sec-config-value"; /** The anonymous user the server answers `GET /api/users/me` with (measured: `anonymous: true`, no id, no workspaces). */ const ANONYMOUS_USER = { anonymous: true, id: null, orgAndRoles: null } as const; +/** Reads the live or a named record of an app's DSL (`GET /api/application-records`), one spec only (D-32 rows). */ +function readRecord(request: Actor["request"], appId: string, recordId: string) { + return apiRaw(request, "GET", API_PATHS.APPLICATION_RECORDS, { params: { applicationId: appId, applicationRecordId: recordId } }); +} + /** The DSL of the seeded app with a different button text and, optionally, queries: what an edit sends. */ function editedDsl(text: string, queries: object[] = []): object { return appDsl([button({ id: SEEDED_BUTTON_ID, name: SEEDED_BUTTON_NAME, text, testId: SEEDED_BUTTON_TEST_ID })], { queries }); @@ -398,19 +405,87 @@ test.describe("security: roles inside one workspace (further rows)", () => { test("SEC-R01d a member without a grant cannot read the live record of the app", securityTestDetails("SEC-R01d"), async ({ page, apiUser, actor }) => { const { a, seeded } = await sceneOf(page, apiUser); const m = await memberOf(a, actor, "member"); - const liveRecord = (request: Actor["request"]) => - apiRaw(request, "GET", API_PATHS.APPLICATION_RECORDS, { params: { applicationId: seeded.appId, applicationRecordId: LIVE_RECORD_ID } }); - const own = await liveRecord(a.request); + const own = await readRecord(a.request, seeded.appId, LIVE_RECORD_ID); expectAnswer(own, ALLOWED, "before: the owner reads the live record"); expect(own.body, "and it holds the app's DSL").toContain(SEEDED_BUTTON_TEST_ID); - const answer = await liveRecord(m.request); + const answer = await readRecord(m.request, seeded.appId, LIVE_RECORD_ID); - // The desired answer is the denial of any other app route (401 / 5001); no available image gives it (SF-27 is open on HEAD). + // D-32: the route needs EDIT on the app since the fix. expectAnswer(answer, API_ERRORS.NOT_AUTHORIZED, "the member's read of the live record"); expect(answer.body, "no DSL in the answer").not.toContain(SEEDED_BUTTON_TEST_ID); }); + test("SEC-R01e a viewer opens the published app but cannot read its live or a named record", securityTestDetails("SEC-R01e"), async ({ page, apiUser, actor }) => { + const { a, seeded } = await sceneOf(page, apiUser); + const v = await memberOf(a, actor, "viewer"); + await grantApp(a, seeded.appId, v, APP_ROLES.VIEWER); + const versionId = (await listAppVersions(a.request, seeded.appId))[0]?.id; + expect(versionId, "setup: the seeded app has a published version").toBeTruthy(); + + const ownLive = await readRecord(a.request, seeded.appId, LIVE_RECORD_ID); + expectAnswer(ownLive, ALLOWED, "before: the owner reads the live record"); + expect(ownLive.body, "and it holds the app's DSL").toContain(SEEDED_BUTTON_TEST_ID); + const ownNamed = await readRecord(a.request, seeded.appId, versionId as string); + expectAnswer(ownNamed, ALLOWED, "before: the owner reads the named record"); + expect(ownNamed.body, "and it holds the app's DSL").toContain(SEEDED_BUTTON_TEST_ID); + + const viewAnswer = await apiRaw(v.request, "GET", appViewPath(seeded.appId)); + expectAnswer(viewAnswer, ALLOWED, "the viewer's published view (the legitimate view, unaffected by D-32)"); + expect(viewAnswer.body, "and it holds the app's DSL").toContain(SEEDED_BUTTON_TEST_ID); + await new AppViewPage(v.session.page).open(seeded.appId); + await expect( + new AppViewPage(v.session.page).buttonByTestId(SEEDED_BUTTON_TEST_ID), + "the viewer's published view shows the app", + ).toHaveText(SEEDED_BUTTON_TEXT); + + const liveAnswer = await readRecord(v.request, seeded.appId, LIVE_RECORD_ID); + expectAnswer(liveAnswer, API_ERRORS.NOT_AUTHORIZED, "the viewer's read of the live record"); + expect(liveAnswer.body, "no DSL in the live-record denial").not.toContain(SEEDED_BUTTON_TEST_ID); + const namedAnswer = await readRecord(v.request, seeded.appId, versionId as string); + expectAnswer(namedAnswer, API_ERRORS.NOT_AUTHORIZED, "the viewer's read of the named record"); + expect(namedAnswer.body, "no DSL in the named-record denial").not.toContain(SEEDED_BUTTON_TEST_ID); + + const afterView = await apiRaw(v.request, "GET", appViewPath(seeded.appId)); + expectAnswer(afterView, ALLOWED, "after: the viewer's published view still works"); + }); + + test("SEC-R01f+ an editor reads the live and a named record", securityTestDetails("SEC-R01f+"), async ({ page, apiUser, actor }) => { + const { a, seeded } = await sceneOf(page, apiUser); + const e = await memberOf(a, actor, "editor"); + await grantApp(a, seeded.appId, e, APP_ROLES.EDITOR); + const versionId = (await listAppVersions(a.request, seeded.appId))[0]?.id; + expect(versionId, "setup: the seeded app has a published version").toBeTruthy(); + expectAnswer(await apiRaw(e.request, "GET", applicationPath(seeded.appId)), ALLOWED, "before: E holds the editor right"); + + const liveAnswer = await readRecord(e.request, seeded.appId, LIVE_RECORD_ID); + expectAnswer(liveAnswer, ALLOWED, "the editor's read of the live record"); + expect(liveAnswer.body, "and it holds the app's DSL").toContain(SEEDED_BUTTON_TEST_ID); + const namedAnswer = await readRecord(e.request, seeded.appId, versionId as string); + expectAnswer(namedAnswer, ALLOWED, "the editor's read of the named record"); + expect(namedAnswer.body, "and it holds the app's DSL").toContain(SEEDED_BUTTON_TEST_ID); + }); + + test("SEC-R01g+ a workspace admin without an app grant reads the live and a named record", securityTestDetails("SEC-R01g+"), async ({ page, apiUser, actor }) => { + const { a, seeded } = await sceneOf(page, apiUser); + const admin = await memberOf(a, actor, "admin"); + await makeAdmin(a, admin); + const versionId = (await listAppVersions(a.request, seeded.appId))[0]?.id; + expect(versionId, "setup: the seeded app has a published version").toBeTruthy(); + expect(await roleOf(a, admin.userId), "before: the guest is an admin of the workspace").toBe(ORG_ROLES.ADMIN); + // Whether the permission list shows an admin implicitly is NOT VERIFIED here (deferred to the combined final e2e run); + // if it does, this assertion needs dropping. + const appPermissionRow = (await listAppPermissions(a.request, seeded.appId)).userPermissions.find((row) => row.id === admin.userId); + expect(appPermissionRow, "before: the admin has no explicit permission row on the app (the access is implicit OWNER)").toBeUndefined(); + + const liveAnswer = await readRecord(admin.request, seeded.appId, LIVE_RECORD_ID); + expectAnswer(liveAnswer, ALLOWED, "the workspace admin's read of the live record (implicit OWNER)"); + expect(liveAnswer.body, "and it holds the app's DSL").toContain(SEEDED_BUTTON_TEST_ID); + const namedAnswer = await readRecord(admin.request, seeded.appId, versionId as string); + expectAnswer(namedAnswer, ALLOWED, "the workspace admin's read of the named record (implicit OWNER)"); + expect(namedAnswer.body, "and it holds the app's DSL").toContain(SEEDED_BUTTON_TEST_ID); + }); + test("SEC-R02d+ a viewer may list who has access to the app", securityTestDetails("SEC-R02d+"), async ({ page, apiUser, actor }) => { const { a, seeded } = await sceneOf(page, apiUser); const v = await memberOf(a, actor, "viewer"); @@ -480,12 +555,29 @@ test.describe("security: roles inside one workspace (further rows)", () => { data: { applicationStatus: APP_STATUS.RECYCLED }, }); - // Desired: the status needs MANAGE like `recycle` (401 / 5001, R03d). The code takes it from EDIT on HEAD too (SF-4). + // The status needs MANAGE like recycle (401 / 5001, R03d); the editor right is not enough (D-9). expectAnswer(answer, API_ERRORS.NOT_AUTHORIZED, "the editor's status update"); expect((await getApp(a.request, seeded.appId)).applicationStatus, "after: the app is still normal").toBe(APP_STATUS.NORMAL); expect(await listAppNames(a.request), "and still listed").toContain(before.name); }); + test("SEC-R03f+ an owner of the app may change its status through the update route", securityTestDetails("SEC-R03f+"), async ({ page, apiUser, actor }) => { + const { a, seeded } = await sceneOf(page, apiUser); + const o = await memberOf(a, actor, "app-owner"); + await grantApp(a, seeded.appId, o, APP_ROLES.OWNER); + const before = await getApp(a.request, seeded.appId); + expect(before.applicationStatus, "before: the app is normal").toBe(APP_STATUS.NORMAL); + + const answer = await apiRaw(o.request, "PUT", applicationPath(seeded.appId), { + params: { updateStatus: true }, + data: { applicationStatus: APP_STATUS.RECYCLED }, + }); + + expectAnswer(answer, ALLOWED, "the owner's status update"); + const recycled = await listRecycledApps(a.request); + expect(recycled.find((app) => app.applicationId === seeded.appId)?.applicationStatus, "after: the app is in the trash, recycled").toBe(APP_STATUS.RECYCLED); + }); + test("SEC-R03c an editor cannot grant the owner role", securityTestDetails("SEC-R03c"), async ({ page, apiUser, actor }) => { const { a, seeded } = await sceneOf(page, apiUser); const e = await memberOf(a, actor, "editor"); @@ -577,11 +669,34 @@ test.describe("security: roles inside one workspace (further rows)", () => { data: { orgId: a.orgId, name: NEW_APP_BY_MEMBER, applicationType: APP_TYPE_APPLICATION, editingApplicationDSL: {} }, }); - // Desired: the same refusal as R06a. The dev check reads the CURRENT workspace, where M is admin (SF-6, open on HEAD). + // The same refusal as R06a; the dev check now reads the TARGET workspace, where M is only a plain member (D-11). expectAnswer(answer, API_ERRORS.NEED_DEV_TO_CREATE_RESOURCE, "the member's create with its own workspace current"); expect(await listAppNames(a.request), "after: nothing was created in OA").not.toContain(NEW_APP_BY_MEMBER); }); + test("SEC-R06e a member whose own workspace is current cannot create a data source in another workspace", securityTestDetails("SEC-R06e"), async ({ page, apiUser, actor }) => { + const { a } = await sceneOf(page, apiUser); + const m = await memberOf(a, actor, "member"); + await switchOrganization(m.request, m.orgId); + expect((await currentUser(m.request)).currentOrgId, "setup: M's own workspace is current").toBe(m.orgId); + const datasourcesBefore = (await apiRaw(a.request, "GET", datasourcesByOrgPath(), { params: { orgId: a.orgId } })).body; + + const answer = await apiRaw(m.request, "POST", API_PATHS.DATASOURCES, { + data: { + name: `${FOREIGN_DATASOURCE}-r06e`, + type: "postgres", + organizationId: a.orgId, + datasourceConfig: { ...postgresConnection(), usingSsl: false, extParams: {} }, + }, + }); + + // The same refusal as R06b; the dev check now reads the TARGET workspace, where M is only a plain member (D-11, D-41). + expectAnswer(answer, API_ERRORS.NEED_DEV_TO_CREATE_RESOURCE, "the member's data source create with its own workspace current"); + const datasourcesAfter = (await apiRaw(a.request, "GET", datasourcesByOrgPath(), { params: { orgId: a.orgId } })).body; + expect(datasourcesAfter, "after: the data sources are as they were").toBe(datasourcesBefore); + expect(datasourcesAfter, "and no foreign one").not.toContain(`${FOREIGN_DATASOURCE}-r06e`); + }); + test("SEC-R06d+ a developer can create apps, data sources, folders and library queries", securityTestDetails("SEC-R06d+"), async ({ page, apiUser, actor }) => { const { a } = await sceneOf(page, apiUser); const d = await memberOf(a, actor, "developer"); @@ -650,6 +765,21 @@ test.describe("security: roles inside one workspace (further rows)", () => { expect(answer.body, "the secret is nowhere in the body").not.toContain(secret); }); + test("SEC-R07e a member's profile carries no sign-in secret", securityTestDetails("SEC-R07e"), async ({ page, apiUser, actor }) => { + const { a } = await sceneOf(page, apiUser); + const m = await memberOf(a, actor, "member"); + const secret = `${OAUTH_SECRET_PREFIX}${randomUUID()}`; + await seedOAuthConfig(a.request, { clientSecret: secret }); + expect((await apiRaw(a.request, "GET", API_PATHS.AUTH_CONFIGS)).body, "before: the admin's config list holds the secret").toContain(secret); + + const answer = await apiRaw(m.request, "GET", API_PATHS.CURRENT_USER); + + expectAnswer(answer, ALLOWED, "the member's profile read (the read itself works)"); + const orgIds = (answer.json as { data: { orgAndRoles: { org: { id: string } }[] } }).data.orgAndRoles.map((entry) => entry.org.id); + expect(orgIds, "the profile lists the admin's workspace, so the secret's absence is not a missing workspace").toContain(a.orgId); + expect(answer.body, "the secret is nowhere in the body").not.toContain(secret); + }); + test("SEC-R08a+ an admin changes a member's role and removes a member", securityTestDetails("SEC-R08a+"), async ({ page, apiUser, actor }) => { const { a } = await sceneOf(page, apiUser); const m = await memberOf(a, actor, "member"); @@ -814,7 +944,7 @@ test.describe("security: data source use inside one workspace", () => { data: { editingApplicationDSL: editedDsl(EDITED_BUTTON_TEXT, queries) }, }); - // Suspected (SF-33, D-38): the batched check takes the workspace from the first data source, where E is an admin. + // D-38: each data source is decided in its own workspace, so E's admin role in its own workspace grants no use of A's data source. expectAnswer(answer, API_ERRORS.NOT_AUTHORIZED, "the editor's save with a query on a data source it may not use"); expect(JSON.stringify((await getApp(a.request, seeded.appId)).dsl), "after: the query is not stored").not.toContain(QUERY_ON_FOREIGN_DATASOURCE); }); diff --git a/e2e/tests/workspace/groups-gui.spec.ts b/e2e/tests/workspace/groups-gui.spec.ts index d98fd997cc..e50e52670b 100644 --- a/e2e/tests/workspace/groups-gui.spec.ts +++ b/e2e/tests/workspace/groups-gui.spec.ts @@ -168,13 +168,17 @@ test.describe("lifecycle: user groups", () => { test("LC-GR09 a built-in group cannot be renamed through the API", lifecycleTestDetails("LC-GR09"), async ({ actor }) => { const admin = await actor("grapirename"); - const allUsers = (await listGroups(admin.request)).find((group) => group.allUsersGroup); - expect(allUsers, "the workspace has an all-users group").toBeDefined(); - const answer = await apiRaw(admin.request, "PUT", groupUpdatePath(allUsers!.groupId), { data: { groupName: "renamed-all" } }); + // D-52: both built-in groups (as LC-GR08 finds them), not only the all-users group. + const builtInGroups = (await listGroups(admin.request)).filter((entry) => entry.allUsersGroup || entry.devGroup); + expect(builtInGroups, "setup: both built-in groups are found").toHaveLength(2); + for (const group of builtInGroups) { + const answer = await apiRaw(admin.request, "PUT", groupUpdatePath(group.groupId), { data: { groupName: "renamed-built-in" } }); - expect(answer.status, "the rename of a built-in group is refused").toBeGreaterThanOrEqual(400); - expect((await listGroups(admin.request)).find((group) => group.groupId === allUsers!.groupId)?.groupName, "the name is unchanged").toBe(allUsers!.groupName); + expectAnswer(answer, API_ERRORS.UNSUPPORTED_OPERATION, `rename of ${group.groupName}`); + // The shown name is unchanged; this does not prove the stored name is (GroupView.java always shows the system name). + expect((await listGroups(admin.request)).find((entry) => entry.groupId === group.groupId)?.groupName, `shown name of ${group.groupName}`).toBe(group.groupName); + } }); test("LC-GR10 adding a member to the developers group in the UI makes them a developer", lifecycleTestDetails("LC-GR10"), async ({ actor }) => { diff --git a/e2e/tests/workspace/leave-removal.spec.ts b/e2e/tests/workspace/leave-removal.spec.ts index 6d87e6f7cf..062b309832 100644 --- a/e2e/tests/workspace/leave-removal.spec.ts +++ b/e2e/tests/workspace/leave-removal.spec.ts @@ -3,7 +3,9 @@ import { acceptInvitation, addGroupMember, apiRaw, + bundleElementsRaw, createApp, + createBundle, createFolder, createGroup, createInvitation, @@ -12,11 +14,13 @@ import { deleteOrganizationRaw, editAppRaw, grantAppPermission, + grantBundlePermission, grantDatasourcePermission, grantFolderPermission, leaveOrganization, listAppNames, listAppPermissions, + listBundlePermissions, listDatasourcePermissions, listFolderPermissions, listGroupMembers, @@ -40,14 +44,15 @@ import { AuthPage } from "../../src/pages/AuthPage"; import { LoginPage } from "../../src/pages/LoginPage"; import { joinWorkspace, makeDeveloper, seedPrivateApp, type Actor } from "../../src/security/actors"; import { expectAnswer } from "../../src/security/assertions"; -import { lifecycleTestDetails } from "../../src/security/quarantine"; +import { lifecycleCandidateDetails, lifecycleTestDetails } from "../../src/security/quarantine"; /** - * What a removal, a leave and a workspace deletion do to a user's data (LC-DL01 to LC-DL11). 3.0.0 has no account deletion + * What a removal, a leave and a workspace deletion do to a user's data (LC-DL01 to LC-DL15). 3.0.0 has no account deletion * in SAAS mode, so there is none to test: a removal deletes the membership only. Every "row gone" check polls (the clean-up * is a listener on its own scheduler) and first asserts the row was there. Covered elsewhere: API keys of a removed member * (SEC-A02b), the removed member's open session (SEC-R11a), a removed creator's editing view (SEC-R11b), ENTERPRISE - * deactivation (SEC-E02 to E04). + * deactivation (SEC-E02 to E04). LC-DL13 to LC-DL15 are quarantined candidates for the creator (`createdBy`) shortcut + * that mechanism 1's cleanup does not revoke (README D-26 and D-60 residuals). */ const OK = { status: 200, code: API_OK } as const; @@ -281,6 +286,103 @@ test.describe("lifecycle: leaving, removal and deletion", () => { expectAnswer(answer, API_ERRORS.UNABLE_TO_FIND_VALID_ORG, "the invitation of the deleted workspace"); expect((await currentUser(outsider.request)).orgAndRoles.map((entry) => entry.org.id), "the outsider did not join").not.toContain(doomed); }); + + test("LC-DL12 a removed member's bundle grant does not survive a rejoin", lifecycleTestDetails("LC-DL12"), async ({ actor }) => { + const admin = await actor("dlowner"); + const member = await actor("dlmember"); + await joinWorkspace(admin, member); + const bundleId = await createBundle(admin.request, { orgId: admin.orgId, name: "dl-bundle" }); + await grantBundlePermission(admin.request, bundleId, { role: "viewer", userIds: [member.userId] }); + const hasRow = async (): Promise => (await listBundlePermissions(admin.request, bundleId)).userPermissions.some((row) => row.id === member.userId); + expect(await hasRow(), "setup: the member holds a bundle row").toBe(true); + expect((await bundleElementsRaw(member.request, bundleId)).status, "setup: the member reads the bundle's elements").toBe(200); + const groupId = await createGroup(admin.request, "dl-bundle-group"); + await addGroupMember(admin.request, groupId, member.userId, "member"); + + await removeOrgMember(admin.request, admin.orgId, member.userId); + await expect.poll(() => isInGroup(admin, groupId, member.userId), { message: "control: the clean-up ran (the member left its group)", ...POLL }).toBe(false); + await rejoin(admin, member); + + await expect.poll(hasRow, { message: "the rejoined member holds no bundle row", ...POLL }).toBe(false); + const elements = await bundleElementsRaw(member.request, bundleId); + expect({ status: elements.status, code: elements.code }, "the rejoined member's bundle elements read").toEqual(API_ERRORS.NO_PERMISSION_TO_REQUEST_APP); + }); + + test("LC-DL13 an app created by a removed developer is not readable by it, neither while removed nor after a rejoin (creator-shortcut candidate)", lifecycleCandidateDetails( + "LC-DL13", + "the removed creator's published view answers 200 (SEC-R11b, membership-changes.spec.ts:95, the creator-shortcut VIEWER row)", + ), async ({ actor }) => { + const admin = await actor("dlowner"); + const developer = await actor("dldeveloper"); + await joinWorkspace(admin, developer); + await makeDeveloper(admin, developer); + const name = `dl-dev-app-lc13-${Date.now()}`; + const { appId } = await createApp(developer.request, { orgId: admin.orgId, name }); + expect(await hasAppRow(admin, appId, developer.userId), "setup: the developer owns the app").toBe(true); + expect(await viewAppRaw(developer.request, appId), "setup: the creator views the app").toEqual(OK); + + await removeOrgMember(admin.request, admin.orgId, developer.userId); + await expect.poll(() => hasAppRow(admin, appId, developer.userId), { message: "control: the creator's owner row is deleted", ...POLL }).toBe(false); + + const removedView = await viewAppRaw(developer.request, appId); + expect({ status: removedView.status, code: removedView.code }, "the removed creator's view (desired: denied like any other removed member, SEC-R11a)").toEqual(API_ERRORS.NO_PERMISSION_TO_REQUEST_APP); + await rejoin(admin, developer); + const rejoinedView = await viewAppRaw(developer.request, appId); + expect({ status: rejoinedView.status, code: rejoinedView.code }, "the rejoined creator's view (desired: denied like a rejoined member, LC-DL02)").toEqual(API_ERRORS.NO_PERMISSION_TO_REQUEST_APP); + }); + + test("LC-DL14 a folder created by a removed developer is not manageable by it after a rejoin (creator-shortcut candidate)", lifecycleCandidateDetails( + "LC-DL14", + "the rejoined creator's rename answers 200 again (checkManagePermissionInCurrentOrg matches createdBy against the current org member once more)", + ), async ({ actor }) => { + const admin = await actor("dlowner"); + const developer = await actor("dldeveloper"); + await joinWorkspace(admin, developer); + await makeDeveloper(admin, developer); + const originalName = "dl-folder-lc14"; + const folderId = await createFolder(developer.request, originalName); + const probeName = "dl-folder-lc14-probe-9f3c"; + const renameAs = (actor: Actor, name: string) => apiRaw(actor.request, "PUT", API_PATHS.FOLDERS, { data: { id: folderId, name } }); + const rootListing = async (): Promise => (await apiRaw(admin.request, "GET", API_PATHS.FOLDER_ELEMENTS)).body; + expectAnswer(await renameAs(developer, probeName), OK, "setup: the creator renames its own folder"); + expectAnswer(await renameAs(developer, originalName), OK, "setup: rename back to the original name, so the control below has something to detect"); + expect(await rootListing(), "setup: the root listing holds the original name").toContain(originalName); + const groupId = await createGroup(admin.request, "dl-folder-lc14-group"); + await addGroupMember(admin.request, groupId, developer.userId, "member"); + + await removeOrgMember(admin.request, admin.orgId, developer.userId); + await expect.poll(() => isInGroup(admin, groupId, developer.userId), { message: "control: the clean-up ran (the creator left its group)", ...POLL }).toBe(false); + await rejoin(admin, developer); + + const rejoinedRename = await renameAs(developer, probeName); + expect({ status: rejoinedRename.status, code: rejoinedRename.code }, "the rejoined creator's rename (desired: refused, like any other non-creator developer, SEC-R15b)").toEqual(API_ERRORS.FOLDER_OPERATE_NO_PERMISSION); + const after = await rootListing(); + expect(after, "the admin's folder listing still shows the old name").toContain(originalName); + expect(after, "and not the rejoined creator's attempted rename").not.toContain(probeName); + }); + + test("LC-DL15 a bundle created by a removed developer is not readable by it, neither while removed nor after a rejoin (creator-shortcut candidate)", lifecycleCandidateDetails( + "LC-DL15", + "the removed/rejoined creator's bundleElementsRaw answers 200 through the creator-shortcut VIEWER row, same mechanism as LC-DL13's app case and SEC-R11b; expected to deny with NO_PERMISSION_TO_REQUEST_APP by the same code path LC-DL12 measures for a non-creator bundle grant (SEC-C23a, tests/security/bundles.spec.ts:86), not yet run against the fixed image, deferred to the combined final run", + ), async ({ actor }) => { + const admin = await actor("dlowner"); + const developer = await actor("dldeveloper"); + await joinWorkspace(admin, developer); + await makeDeveloper(admin, developer); + const bundleId = await createBundle(developer.request, { orgId: admin.orgId, name: `dl-dev-bundle-lc15-${Date.now()}` }); + const hasRow = async (): Promise => (await listBundlePermissions(admin.request, bundleId)).userPermissions.some((row) => row.id === developer.userId); + expect(await hasRow(), "setup: the developer owns the bundle").toBe(true); + expect((await bundleElementsRaw(developer.request, bundleId)).status, "setup: the creator reads the bundle's elements").toBe(200); + + await removeOrgMember(admin.request, admin.orgId, developer.userId); + await expect.poll(hasRow, { message: "control: the creator's owner row is deleted", ...POLL }).toBe(false); + + const removedElements = await bundleElementsRaw(developer.request, bundleId); + expect({ status: removedElements.status, code: removedElements.code }, "the removed creator's bundle elements (desired: denied)").toEqual(API_ERRORS.NO_PERMISSION_TO_REQUEST_APP); + await rejoin(admin, developer); + const rejoinedElements = await bundleElementsRaw(developer.request, bundleId); + expect({ status: rejoinedElements.status, code: rejoinedElements.code }, "the rejoined creator's bundle elements (desired: denied)").toEqual(API_ERRORS.NO_PERMISSION_TO_REQUEST_APP); + }); }); /** Whether the developer is still in the developers group of the workspace its (former) admin owns. */ diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/model/ApplicationHistorySnapshot.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/model/ApplicationHistorySnapshot.java index 0338d14d19..4b81d6bcf5 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/model/ApplicationHistorySnapshot.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/model/ApplicationHistorySnapshot.java @@ -18,6 +18,11 @@ public class ApplicationHistorySnapshot extends HasIdAndAuditing { private String applicationId; + /** + * TRUE when {@link #applicationId} was written as the object id the create route resolved the request's key to and + * checked EDIT on (D-31); null on a snapshot stored before, whose applicationId is whatever key its caller sent. + */ + private Boolean applicationIdResolved; private Map dsl; private Map context; diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/model/ApplicationHistorySnapshotTS.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/model/ApplicationHistorySnapshotTS.java index 1b6d865021..cdf01590e1 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/model/ApplicationHistorySnapshotTS.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/model/ApplicationHistorySnapshotTS.java @@ -17,6 +17,11 @@ public class ApplicationHistorySnapshotTS extends HasIdAndAuditing { private String applicationId; + /** + * TRUE when {@link #applicationId} was written as the object id the create route resolved the request's key to and + * checked EDIT on (D-31); null on a snapshot stored before, whose applicationId is whatever key its caller sent. + */ + private Boolean applicationIdResolved; private Map dsl; private Map context; diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/service/ApplicationHistorySnapshotService.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/service/ApplicationHistorySnapshotService.java index f4e5b3fcf6..cb70939b73 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/service/ApplicationHistorySnapshotService.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/service/ApplicationHistorySnapshotService.java @@ -11,6 +11,11 @@ public interface ApplicationHistorySnapshotService { + /** + * Stores a snapshot of the application whose object id is {@code applicationId} and marks it as stored under that + * object id (D-31). The caller resolves the key it was given to the object id and checks EDIT on it first: a gid or a + * slug passed here would be marked as an object id. + */ Mono createHistorySnapshot(String applicationId, Map dsl, Map context, String userId); Mono> listAllHistorySnapshotBriefInfo(String applicationId, String compName, String theme, Instant from, Instant to, PageRequest pageRequest); diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/service/impl/ApplicationHistorySnapshotServiceImpl.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/service/impl/ApplicationHistorySnapshotServiceImpl.java index 2d4aba44a4..ce6775e710 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/service/impl/ApplicationHistorySnapshotServiceImpl.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/application/service/impl/ApplicationHistorySnapshotServiceImpl.java @@ -31,6 +31,7 @@ public class ApplicationHistorySnapshotServiceImpl implements ApplicationHistory public Mono createHistorySnapshot(String applicationId, Map dsl, Map context, String userId) { ApplicationHistorySnapshot applicationHistorySnapshot = new ApplicationHistorySnapshot(); applicationHistorySnapshot.setApplicationId(applicationId); + applicationHistorySnapshot.setApplicationIdResolved(true); applicationHistorySnapshot.setDsl(dsl); applicationHistorySnapshot.setContext(context); return repository.save(applicationHistorySnapshot) diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/repository/BundleRepository.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/repository/BundleRepository.java index a65dd05f99..9020d269d1 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/repository/BundleRepository.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/repository/BundleRepository.java @@ -35,4 +35,6 @@ public interface BundleRepository extends ReactiveMongoRepository findByPublicToAllIsTrueAndPublicToMarketplaceIsTrue(); Flux findByPublicToAllIsTrueAndAgencyProfileIsTrue(); + + Flux findByOrganizationId(String organizationId); } diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/service/BundleService.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/service/BundleService.java index 4b4e99fc08..f279e4bb5d 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/service/BundleService.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/service/BundleService.java @@ -55,4 +55,6 @@ public interface BundleService { Flux findAllMarketplaceBundles(); Flux findAllAgencyProfileBundles(); + + Flux findByOrganizationId(String organizationId); } diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/service/BundleServiceImpl.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/service/BundleServiceImpl.java index c0616a1b59..1b27aa6090 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/service/BundleServiceImpl.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/bundle/service/BundleServiceImpl.java @@ -201,6 +201,11 @@ public Flux findAllAgencyProfileBundles() { return repository.findByPublicToAllIsTrueAndAgencyProfileIsTrue(); } + @Override + public Flux findByOrganizationId(String organizationId) { + return repository.findByOrganizationId(organizationId); + } + @Override public Mono setBundlePublicToAll(String bundleId, boolean publicToAll) { Bundle bundle = Bundle.builder() diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/Organization.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/Organization.java index 1a2f98b5c4..256127fa85 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/Organization.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/Organization.java @@ -137,6 +137,12 @@ public long getCreateTime() { return createdAt != null ? createdAt.toEpochMilli() : 0; } + /** + * The sign-in configurations of the organization, for server code. Never part of the organization's JSON: the + * configurations hold OAuth client secrets, and admins read them through {@code GET /api/auth/configs} (D-14). + * Limits: storage is not affected ({@code OrganizationDomain} stores them through its MongoDB hooks). + */ + @JsonIgnore public List getAuthConfigs() { return Optional.ofNullable(organizationDomain) .map(OrganizationDomain::getConfigs) diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/BundlePermissionHandler.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/BundlePermissionHandler.java index 3dd69017af..22bc60fc94 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/BundlePermissionHandler.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/BundlePermissionHandler.java @@ -113,4 +113,10 @@ protected Mono getOrgId(String resourceId) { return bundleService.findById(resourceId) .map(Bundle::getOrganizationId); } + + @Override + protected Mono> getOrgIds(Set resourceIds) { + return orgIdsByKey(bundleService.findByIdIn(resourceIds), resourceIds, Bundle::getId, Bundle::getGid, + Bundle::getOrganizationId); + } } diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/DatasourcePermissionHandler.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/DatasourcePermissionHandler.java index ea3f95611d..87069f312c 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/DatasourcePermissionHandler.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/DatasourcePermissionHandler.java @@ -18,6 +18,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; @@ -69,6 +70,14 @@ protected Mono getOrgId(String resourceId) { .map(Datasource::getOrganizationId); } + /** One {@code getByIds} call (one query per key kind present, D-38); the same per-document conversion as + * {@link #getOrgId} (it may fetch a JS plugin definition). */ + @Override + protected Mono> getOrgIds(Set resourceIds) { + return orgIdsByKey(datasourceService.getByIds(resourceIds), resourceIds, Datasource::getId, Datasource::getGid, + Datasource::getOrganizationId); + } + @Override public Mono>> getAllMatchingPermissions(String userId, Collection resourceIds, ResourceAction resourceAction) { diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionHandler.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionHandler.java index 05ab238c0f..eed073319a 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionHandler.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionHandler.java @@ -5,25 +5,40 @@ import jakarta.annotation.Nonnull; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.ListUtils; +import org.apache.commons.lang3.StringUtils; import org.lowcoder.domain.application.model.ApplicationRequestType; import org.lowcoder.domain.bundle.model.BundleRequestType; import org.lowcoder.domain.group.service.GroupMemberService; import org.lowcoder.domain.organization.service.OrgMemberService; import org.lowcoder.domain.permission.model.*; import org.lowcoder.sdk.config.CommonConfig; +import org.lowcoder.sdk.constants.FieldName; +import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.*; +import java.util.function.Function; import static java.util.Collections.*; import static java.util.function.Function.identity; +import static java.util.stream.Collectors.toCollection; import static java.util.stream.Collectors.toMap; import static org.lowcoder.sdk.constants.Authentication.isAnonymousUser; abstract class ResourcePermissionHandler implements ResourcePermissionHandlerService { + /** + * Upper bound of the lookups one batch runs at the same time: the per-id workspace lookups of a handler without a batch + * lookup (applications) and the per-workspace membership decisions. The MongoDB driver's default pool is 100 + * connections and no pool size is configured in this repository, so one large batch cannot take the pool from other + * requests. + */ + static final int ORG_LOOKUP_CONCURRENCY = 16; + @Lazy @Autowired private ResourcePermissionService resourcePermissionService; @@ -37,6 +52,19 @@ abstract class ResourcePermissionHandler implements ResourcePermissionHandlerSer @Autowired protected CommonConfig config; + /** + * Matching permissions of the user on each id. One id is decided as the one-resource checks decide it, its lookup + * errors included. Two or more ids are each decided in their own workspace (D-38: the workspace and admin role of + * the first id were applied to all ids): blank ids and ids that name nothing get no entry, a failed lookup fails the + * answer. Cost: the workspace lookup of the handler ({@link #getOrgIds}: for data sources and bundles one batch call, + * which runs one query per key kind present, object ids and gids; for applications one read per id, at most + * {@link #ORG_LOOKUP_CONCURRENCY} at once) plus one membership read per workspace, and for a member one group read + * and one permission read per workspace. Limits: a resource stored without a workspace id fails the answer; a gid + * stored twice is answered with the first match the lookup returns; a data source or bundle key is answered only as + * the kind {@link FieldName#isGID} gives it, so a gid stored without a hyphen gets no entry when asked by that gid; + * an application slug several applications share gets no entry, like an id that names nothing (the lookup answers + * both alike). + */ @Override public Mono>> getAllMatchingPermissions(String userId, Collection resourceIds, @@ -52,14 +80,18 @@ public Mono>> getAllMatchingPermissions(Str return getAnonymousUserPermissions(resourceIds, resourceAction); } - return getOrgId(resourceIds.iterator().next()) - .flatMap(orgId -> orgMemberService.getOrgMember(orgId, userId)) - .flatMap(orgMember -> { - if (orgMember.isAdmin() || orgMember.isSuperAdmin()) { - return Mono.just(buildAdminPermissions(resourceType, resourceIds, userId)); - } - return getAllMatchingPermissions0(userId, orgMember.getOrgId(), resourceType, resourceIds, resourceAction); - }) + Set distinctIds = new LinkedHashSet<>(resourceIds); + Mono>> orgPermissionsMono; + if (distinctIds.size() == 1) { + orgPermissionsMono = getOrgId(distinctIds.iterator().next()) + .flatMap(orgId -> getPermissionsInOrg(userId, orgId, resourceType, distinctIds, resourceAction)); + } else { + Set lookupIds = distinctIds.stream().filter(StringUtils::isNotBlank) + .collect(toCollection(LinkedHashSet::new)); + orgPermissionsMono = (lookupIds.isEmpty() ? Mono.just(Map. of()) : getOrgIds(lookupIds)) + .flatMap(orgIdById -> getPermissionsPerOrg(userId, resourceType, lookupIds, orgIdById, resourceAction)); + } + return orgPermissionsMono .switchIfEmpty(Mono.just(Maps.newHashMap())) .zipWith(getAnonymousUserPermissions(resourceIds, resourceAction)) .flatMap(tuple2 -> { @@ -70,6 +102,82 @@ public Mono>> getAllMatchingPermissions(Str }); } + /** Today's decision for ids of ONE workspace; empty when the user is not a member there. */ + private Mono>> getPermissionsInOrg(String userId, String orgId, + ResourceType resourceType, Collection resourceIds, ResourceAction resourceAction) { + return orgMemberService.getOrgMember(orgId, userId) + .flatMap(orgMember -> { + if (orgMember.isAdmin() || orgMember.isSuperAdmin()) { + return Mono.just(buildAdminPermissions(resourceType, resourceIds, userId)); + } + return getAllMatchingPermissions0(userId, orgMember.getOrgId(), resourceType, resourceIds, resourceAction); + }); + } + + private Mono>> getPermissionsPerOrg(String userId, ResourceType resourceType, + Set lookupIds, Map orgIdById, ResourceAction resourceAction) { + Map> idsByOrgId = new LinkedHashMap<>(); + lookupIds.forEach(id -> { + String orgId = orgIdById.get(id); + if (orgId != null) { + idsByOrgId.computeIfAbsent(orgId, key -> new ArrayList<>()).add(id); + } + }); + return Flux.fromIterable(idsByOrgId.entrySet()) + .flatMap(entry -> getPermissionsInOrg(userId, entry.getKey(), resourceType, entry.getValue(), resourceAction), + ORG_LOOKUP_CONCURRENCY) + .>> collect(HashMap::new, Map::putAll); + } + + /** + * The workspace of each given id that names a resource, looked up one id at a time with {@link #getOrgId}, at most + * {@link #ORG_LOOKUP_CONCURRENCY} at once. An id that names nothing (NO_RESOURCE_FOUND) is left out; any other error is + * a failed lookup and fails the answer. Limit: the application lookup raises the same NO_RESOURCE_FOUND for a slug + * several applications share, so such a key is left out too, like an unknown id (D-38). A handler with a batch lookup + * overrides this. Called with non-blank ids only. + */ + protected Mono> getOrgIds(Set resourceIds) { + return Flux.fromIterable(resourceIds) + .flatMap(resourceId -> getOrgId(resourceId) + .onErrorResume(ResourcePermissionHandler::isNoResourceFound, error -> Mono.empty()) + .map(orgId -> Map.entry(resourceId, orgId)), + ORG_LOOKUP_CONCURRENCY) + .collectMap(Map.Entry::getKey, Map.Entry::getValue); + } + + /** + * The workspace of each asked key among {@code found}, the answer of a batch lookup by object id or gid + * ({@code IdOrGidLookup}). Each key is told an object id or a gid by {@link FieldName#isGID} (a hyphen: gid), the rule + * the lookup splits its queries by, and is matched only against the field of its kind: an object-id key against + * {@code idOf}, a gid key against {@code gidOf}. A key equal to the other field of a found resource (a gid stored + * without a hyphen, an object id with one) gets no entry from it: the lookup did not find that resource by that key, + * and the one-id lookup of that key does not find it either. The lookup's queries are exact matches, so a + * resource whose field of a key's kind equals the key was found by that key's own query: matching by kind gives the + * pairs the lookup found, without tracking which query returned a resource. The first resource found for a key wins + * (a gid stored twice). A found resource without a workspace id fails the answer, as the one-id {@link #getOrgId} + * does. + */ + protected static Mono> orgIdsByKey(Flux found, Set keys, Function idOf, + Function gidOf, Function orgIdOf) { + return found.> collect(HashMap::new, (orgIdByKey, resource) -> { + String orgId = Objects.requireNonNull(orgIdOf.apply(resource), "organizationId"); + putIfAskedAsKind(orgIdByKey, keys, idOf.apply(resource), false, orgId); + putIfAskedAsKind(orgIdByKey, keys, gidOf.apply(resource), true, orgId); + }); + } + + /** Maps {@code key} to {@code orgId} when it is asked and {@link FieldName#isGID} tells it the given kind. */ + private static void putIfAskedAsKind(Map orgIdByKey, Set keys, String key, boolean gidKind, + String orgId) { + if (key != null && keys.contains(key) && FieldName.isGID(key) == gidKind) { + orgIdByKey.putIfAbsent(key, orgId); + } + } + + private static boolean isNoResourceFound(Throwable error) { + return error instanceof BizException bizException && bizException.getError() == BizError.NO_RESOURCE_FOUND; + } + @Override public Mono checkUserPermissionStatusOnResource(String userId, String resourceId, ResourceAction resourceAction) { diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionService.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionService.java index 3e97a42172..f7ae10a0f5 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionService.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionService.java @@ -75,7 +75,11 @@ Mono> getMaxMatchingPermission(String userId, Mono removeUserApplicationPermission(String appId, String userId); - Mono removeUserDatasourcePermission(String appId, String userId); + Mono removeUserDatasourcePermission(String datasourceId, String userId); + + Mono removeUserFolderPermission(String folderId, String userId); + + Mono removeUserBundlePermission(String bundleId, String userId); Mono getUserAssignedPermissionForApplication(String applicationId, String userId); } diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionServiceImpl.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionServiceImpl.java index 91e0ad468f..775dfd2e93 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionServiceImpl.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/service/ResourcePermissionServiceImpl.java @@ -260,8 +260,18 @@ public Mono removeUserApplicationPermission(String appId, String userId } @Override - public Mono removeUserDatasourcePermission(String appId, String userId) { - return repository.removePermissionBy(ResourceType.APPLICATION, appId, ResourceHolder.USER, userId); + public Mono removeUserDatasourcePermission(String datasourceId, String userId) { + return repository.removePermissionBy(ResourceType.DATASOURCE, datasourceId, ResourceHolder.USER, userId); + } + + @Override + public Mono removeUserFolderPermission(String folderId, String userId) { + return repository.removePermissionBy(ResourceType.FOLDER, folderId, ResourceHolder.USER, userId); + } + + @Override + public Mono removeUserBundlePermission(String bundleId, String userId) { + return repository.removePermissionBy(ResourceType.BUNDLE, bundleId, ResourceHolder.USER, userId); } @Override diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/CustomUserRepository.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/CustomUserRepository.java new file mode 100644 index 0000000000..b17698916d --- /dev/null +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/CustomUserRepository.java @@ -0,0 +1,10 @@ +package org.lowcoder.domain.user.repository; + +import com.mongodb.client.result.UpdateResult; + +import reactor.core.publisher.Mono; + +public interface CustomUserRepository { + + Mono setPasswordIfAbsent(String userId, String encryptedPassword); +} diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/CustomUserRepositoryImpl.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/CustomUserRepositoryImpl.java new file mode 100644 index 0000000000..7a9dd34953 --- /dev/null +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/CustomUserRepositoryImpl.java @@ -0,0 +1,42 @@ +package org.lowcoder.domain.user.repository; + +import static org.lowcoder.domain.util.QueryDslUtils.fieldName; + +import lombok.RequiredArgsConstructor; +import org.lowcoder.domain.user.model.QUser; +import org.lowcoder.domain.user.model.User; +import org.lowcoder.sdk.constants.FieldName; +import org.springframework.data.mongodb.core.ReactiveMongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Repository; + +import com.mongodb.client.result.UpdateResult; + +import reactor.core.publisher.Mono; + +@Repository +@RequiredArgsConstructor +public class CustomUserRepositoryImpl implements CustomUserRepository { + + /** A stored password counts as absent when the field is missing, null, or only whitespace. */ + static final String BLANK_PATTERN = "^\\s*$"; + + private final ReactiveMongoTemplate mongoTemplate; + + /** + * One atomic single-document update (D-49): the filter (absent password) and the {@code $set} of the new hash + * are evaluated together by MongoDB, so a concurrent call can never pass the filter after another call has + * already written a password; exactly one of two concurrent calls on the same account matches. Limits: like + * {@link org.lowcoder.infra.mongo.MongoUpsertHelper#updatePurely}, this bypasses {@code User.beforeMongodbWrite} + * (only re-encrypts API keys) and does not touch {@code updatedAt} or {@code modifiedBy}. + */ + @Override + public Mono setPasswordIfAbsent(String userId, String encryptedPassword) { + String password = fieldName(QUser.user.password); + Query query = Query.query(Criteria.where(FieldName.ID).is(userId) + .orOperator(Criteria.where(password).is(null), Criteria.where(password).regex(BLANK_PATTERN))); + return mongoTemplate.updateFirst(query, new Update().set(password, encryptedPassword), User.class); + } +} diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/UserRepository.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/UserRepository.java index 896c278cd7..63951675ce 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/UserRepository.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/repository/UserRepository.java @@ -13,7 +13,7 @@ import org.springframework.data.mongodb.repository.Query; @Repository -public interface UserRepository extends ReactiveMongoRepository { +public interface UserRepository extends ReactiveMongoRepository, CustomUserRepository { Flux findByIdIn(Collection ids); Mono findBySuperAdminIsTrue(); diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/EmailCommunicationServiceImpl.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/EmailCommunicationServiceImpl.java index 20f9b5d6aa..af03c193d3 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/EmailCommunicationServiceImpl.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/EmailCommunicationServiceImpl.java @@ -38,7 +38,8 @@ public boolean sendPasswordResetEmail(String to, String token, String message) { mimeMessageHelper.setSubject(subject); // Construct the message with the token link - String resetLink = config.getLowcoderPublicUrl() + "/user/auth/lost-password?token=" + URLEncoder.encode(token, StandardCharsets.UTF_8); + // D-54 + String resetLink = CommonConfig.withoutTrailingSlashes(config.getLowcoderPublicUrl()) + "/user/auth/lost-password?token=" + URLEncoder.encode(token, StandardCharsets.UTF_8); String formattedMessage = fillTemplate(message, to, resetLink); mimeMessageHelper.setText(formattedMessage, true); // Set HTML to true to allow links diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserService.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserService.java index e5057ab51a..3ab4e19b77 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserService.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserService.java @@ -51,9 +51,20 @@ public interface UserService { Mono lostPassword(String userEmail); - Mono resetLostPassword(String userEmail, String token, String newPassword); + /** Resets a lost password by its mailed token; answers the id of the account whose password was reset, so the caller can end its sessions (D-34). */ + Mono resetLostPassword(String userEmail, String token, String newPassword); Mono setPassword(String userId, String password); + + /** + * Sets the password of an account that has none (missing, null or blank), in one conditional MongoDB update, so the + * check cannot race another write of the password (D-49). Fails with INVALID_PASSWORD / PASSWORD_ALREADY_SET when the + * account has a password, USER_NOT_EXIST when there is no such account. {@link #setPassword} stays the unconditional + * write for the super admin job. Limit: a whole-document save of the same user that read it before this update (for + * example a login's token save) can write the old, absent password back. + */ + Mono setPasswordIfAbsent(String userId, String password); + Mono markAsSuperAdmin(String userId); Mono buildUserDetail(User user, boolean withoutDynamicGroups); diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserServiceImpl.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserServiceImpl.java index 4066e3441e..aa34a8ef83 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserServiceImpl.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/service/UserServiceImpl.java @@ -514,7 +514,7 @@ private static String passwordResetEmailTemplate(OrganizationCommonSettings sett } @Override - public Mono resetLostPassword(String userEmail, String token, String newPassword) { + public Mono resetLostPassword(String userEmail, String token, String newPassword) { return findByEmailDeep(userEmail) .switchIfEmpty(Mono.defer(() -> findByName(userEmail))) .filter(UserServiceImpl::canRecoverPassword) @@ -535,7 +535,7 @@ public Mono resetLostPassword(String userEmail, String token, String ne user.setPasswordResetToken(StringUtils.EMPTY); user.setPasswordResetTokenExpiry(Instant.now()); return repository.save(user) - .thenReturn(true); + .thenReturn(user.getId()); }); } @@ -559,6 +559,15 @@ public Mono setPassword(String userId, String password) { .thenReturn(true); } + @Override + public Mono setPasswordIfAbsent(String userId, String password) { + return Mono.fromSupplier(() -> encryptionService.encryptPassword(password)) + .flatMap(hash -> repository.setPasswordIfAbsent(userId, hash)) + .flatMap(result -> result.getMatchedCount() > 0 + ? Mono.just(true) + : findExistingById(userId).then(ofError(BizError.INVALID_PASSWORD, "PASSWORD_ALREADY_SET"))); + } + @Override public Mono markAsSuperAdmin(String userId) { return findExistingById(userId) diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/application/service/impl/ApplicationHistorySnapshotServiceImplTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/application/service/impl/ApplicationHistorySnapshotServiceImplTest.java new file mode 100644 index 0000000000..c339af3d3f --- /dev/null +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/application/service/impl/ApplicationHistorySnapshotServiceImplTest.java @@ -0,0 +1,51 @@ +package org.lowcoder.domain.application.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Duration; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.lowcoder.domain.application.model.ApplicationHistorySnapshot; +import org.lowcoder.domain.application.repository.ApplicationHistoryArchivedSnapshotRepository; +import org.lowcoder.domain.application.repository.ApplicationHistorySnapshotRepository; +import org.mockito.ArgumentCaptor; + +import reactor.core.publisher.Mono; + +/** + * D-31: {@code createHistorySnapshot} stores the given id as the object id it is, and marks the stored row with + * {@code applicationIdResolved = true} so the DSL routes can later tell it apart from a snapshot stored before this + * fix. The caller (the controller's {@code editableApplication}) is the one that resolved the key and checked EDIT on + * it; this service only writes what it is given. + */ +class ApplicationHistorySnapshotServiceImplTest { + + @Test + void createHistorySnapshotStoresTheGivenObjectIdAndMarksIt() { + ApplicationHistorySnapshotRepository repository = mock(ApplicationHistorySnapshotRepository.class); + ApplicationHistoryArchivedSnapshotRepository repositoryArchived = mock(ApplicationHistoryArchivedSnapshotRepository.class); + ApplicationHistorySnapshotServiceImpl service = new ApplicationHistorySnapshotServiceImpl(repository, repositoryArchived); + when(repository.save(any(ApplicationHistorySnapshot.class))).thenAnswer(invocation -> Mono.just(invocation.getArgument(0))); + Map dsl = Map.of("dsl", "d"); + Map context = Map.of("context", "c"); + + Boolean result = service.createHistorySnapshot("app-object-id", dsl, context, "user-id").block(Duration.ofSeconds(5)); + + assertThat(result).isTrue(); + ArgumentCaptor captor = ArgumentCaptor.forClass(ApplicationHistorySnapshot.class); + verify(repository).save(captor.capture()); + ApplicationHistorySnapshot snapshot = captor.getValue(); + System.out.println("[ApplicationHistorySnapshotServiceImplTest] stored: " + snapshot); + assertThat(snapshot.getApplicationId()).isEqualTo("app-object-id"); + assertThat(snapshot.getApplicationIdResolved()).isEqualTo(Boolean.TRUE); + assertThat(snapshot.getDsl()).isEqualTo(dsl); + assertThat(snapshot.getContext()).isEqualTo(context); + verifyNoInteractions(repositoryArchived); + } +} diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/organization/model/OrganizationJsonTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/organization/model/OrganizationJsonTest.java new file mode 100644 index 0000000000..fae27a9cfb --- /dev/null +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/organization/model/OrganizationJsonTest.java @@ -0,0 +1,96 @@ +package org.lowcoder.domain.organization.model; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.lowcoder.sdk.auth.AbstractAuthConfig; +import org.lowcoder.sdk.auth.Oauth2SimpleAuthConfig; +import org.lowcoder.sdk.auth.constants.AuthTypeConstants; +import org.lowcoder.sdk.config.JsonViews; +import org.lowcoder.sdk.util.JsonUtils; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * {@link Organization#getAuthConfigs()} must never reach JSON (D-14): the configs hold OAuth client secrets, and + * admins read them through {@code GET /api/auth/configs}, never through an organization. Java access and MongoDB + * storage (through {@code OrganizationDomain}'s hooks) are unaffected. + */ +class OrganizationJsonTest { + + private static final String CLIENT_SECRET = "OrganizationJsonTest.clientSecret"; + private static final String CLIENT_ID = "OrganizationJsonTest.clientId"; + private static final String ORG_NAME = "OrganizationJsonTest.name"; + private static final String AUTH_CONFIGS = "authConfigs"; + private static final String NAME = "name"; + private static final ObjectMapper MAPPER = JsonUtils.getObjectMapper(); + + private static Organization organization() { + OrganizationDomain domain = new OrganizationDomain(); + domain.setConfigs(new ArrayList<>(List.of(Oauth2SimpleAuthConfig.builder() + .id("OrganizationJsonTest.configId") + .source(AuthTypeConstants.GITHUB) + .sourceName(AuthTypeConstants.GITHUB) + .authType(AuthTypeConstants.GITHUB) + .enable(Boolean.TRUE) + .enableRegister(Boolean.FALSE) + .clientId(CLIENT_ID) + .clientSecret(CLIENT_SECRET) + .build()))); + return Organization.builder().name(ORG_NAME).organizationDomain(domain).build(); + } + + private static Stream views() { + return Stream.of( + Arguments.of("no view", (Class) null), + Arguments.of("Public", JsonViews.Public.class), + Arguments.of("Internal", JsonViews.Internal.class)); + } + + private static String write(Class view) throws Exception { + Organization organization = organization(); + return view == null ? MAPPER.writeValueAsString(organization) : MAPPER.writerWithView(view).writeValueAsString(organization); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("views") + void writesNoAuthConfigs(String label, Class view) throws Exception { + String json = write(view); + JsonNode tree = MAPPER.readTree(json); + + System.out.println("[OrganizationJsonTest] writesNoAuthConfigs(" + label + ") json=" + json); + assertThat(tree.get(NAME).asText()).as("positive control: the organization was written").isEqualTo(ORG_NAME); + assertThat(tree.has(AUTH_CONFIGS)).as(label + ": no authConfigs member").isFalse(); + assertThat(json.contains(CLIENT_SECRET)).as(label + ": the secret is nowhere in the JSON").isFalse(); + } + + @Test + void javaAccessKeepsTheConfigs() { + Organization organization = organization(); + + List configs = organization.getAuthConfigs(); + + System.out.println("[OrganizationJsonTest] javaAccessKeepsTheConfigs configs=" + configs); + assertThat(configs).hasSize(1); + assertThat(((Oauth2SimpleAuthConfig) configs.get(0)).getClientSecret()).isEqualTo(CLIENT_SECRET); + } + + @Test + void anAuthConfigsMemberInABodyIsIgnored() throws Exception { + String body = "{\"name\":\"" + ORG_NAME + "\",\"authConfigs\":[{\"authType\":\"GITHUB\",\"clientSecret\":\"" + CLIENT_SECRET + "\"}]}"; + + Organization bound = MAPPER.readValue(body, Organization.class); + + System.out.println("[OrganizationJsonTest] anAuthConfigsMemberInABodyIsIgnored name=" + bound.getName() + " configs=" + bound.getAuthConfigs()); + assertThat(bound.getName()).isEqualTo(ORG_NAME); + assertThat(bound.getAuthConfigs()).isEmpty(); + } +} diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/BundlePermissionHandlerTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/BundlePermissionHandlerTest.java index fe52799ae8..6888ee22b9 100644 --- a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/BundlePermissionHandlerTest.java +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/BundlePermissionHandlerTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.GROUP_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.ORG_ID; +import static org.lowcoder.domain.permission.service.PermissionTestFixtures.OTHER_ORG_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.RESOURCE_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.USER_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.orgMember; @@ -14,10 +15,12 @@ import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; @@ -43,7 +46,11 @@ import org.lowcoder.domain.permission.model.UserPermissionOnResourceStatus; import org.lowcoder.domain.solutions.TemplateSolutionService; import org.lowcoder.sdk.config.CommonConfig; +import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; +import org.mockito.ArgumentCaptor; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -131,6 +138,89 @@ void getAll_member_getsOwnRowMergedWithPublicRow() { System.out.println("[BundlePermissionHandlerTest] member group row + public row both kept"); } + static Stream> ordersOfB1B2() { + return Stream.of(List.of("b1", "b2"), List.of("b2", "b1")); + } + + /** Catches D-38 on bundles: a batch of two bundles of different workspaces, one batch lookup, each decided by its + * own workspace. */ + @ParameterizedTest + @MethodSource("ordersOfB1B2") + void getAll_bundlesOfTwoWorkspaces_oneBatchLookup_eachDecidedByItsOwnWorkspace(List ids) { + when(bundleService.findByIdIn(any())).thenReturn(Flux.just( + Bundle.builder().id("b1").organizationId(ORG_ID).build(), + Bundle.builder().id("b2").organizationId(OTHER_ORG_ID).build())); + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.MEMBER))); + when(orgMemberService.getOrgMember(OTHER_ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(OTHER_ORG_ID, MemberRole.ADMIN))); + when(groupMemberService.getUserGroupIdsInOrg(ORG_ID, USER_ID)).thenReturn(Mono.just(List.of())); + ResourcePermission editorRow = row("b1", ResourceHolder.USER, USER_ID, ResourceRole.EDITOR); + when(resourcePermissionService.getByResourceTypeAndResourceIds(eq(ResourceType.BUNDLE), any())) + .thenReturn(Mono.just(Map.of("b1", List.of(editorRow)))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, ids, ResourceAction.READ_BUNDLES)) + .assertNext(map -> { + assertThat(map).containsOnlyKeys("b1", "b2"); + assertThat(map.get("b1")).containsExactly(editorRow); + ResourcePermission b2Row = map.get("b2").get(0); + assertThat(b2Row.getResourceRole()).isEqualTo(ResourceRole.OWNER); + assertThat(b2Row.getResourceHolderId()).isEqualTo(USER_ID); + }) + .verifyComplete(); + verify(bundleService, times(1)).findByIdIn(any()); + verify(bundleService, never()).findById(any()); + System.out.println("[BundlePermissionHandlerTest] D-38 orders " + ids + ": b1 (ORG_ID member) EDITOR, b2 (OTHER_ORG_ID admin) OWNER"); + } + + /** Catches a bundle the user created in a workspace it is no longer a member of borrowing the first id's answer. */ + @Test + void getAll_bundleOfAWorkspaceTheUserIsNotIn_getsOnlyItsPublicRow() { + when(bundleService.findByIdIn(any())).thenReturn(Flux.just( + Bundle.builder().id("b1").organizationId(ORG_ID).build(), + Bundle.builder().id("b3").organizationId(OTHER_ORG_ID).build())); + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.MEMBER))); + when(orgMemberService.getOrgMember(OTHER_ORG_ID, USER_ID)).thenReturn(Mono.empty()); + ResourcePermission ownRow = row("b1", ResourceHolder.USER, USER_ID, ResourceRole.OWNER); + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Collection.class); + when(resourcePermissionService.getByResourceTypeAndResourceIds(eq(ResourceType.BUNDLE), captor.capture())) + .thenReturn(Mono.just(Map.of( + "b1", List.of(ownRow), + "b3", List.of(row("b3", ResourceHolder.USER, USER_ID, ResourceRole.OWNER))))); + when(bundleService.getPublicBundleIds(any())).thenReturn(Mono.just(Set.of("b3"))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, List.of("b1", "b3"), ResourceAction.READ_BUNDLES)) + .assertNext(map -> { + assertThat(map).containsOnlyKeys("b1", "b3"); + assertThat(map.get("b1")).containsExactly(ownRow); + assertThat(map.get("b3")).as("only the anonymous VIEWER row, not the creator's stored OWNER row").hasSize(1); + assertAnonymousViewerRow(map.get("b3").get(0), "b3"); + }) + .verifyComplete(); + assertThat(captor.getValue()).containsExactly("b1"); + System.out.println("[BundlePermissionHandlerTest] left b3's workspace: only its public row, not the creator's stored OWNER row"); + } + + /** Catches an unknown bundle in a batch failing the whole call, and pins the one-id contract is unchanged. */ + @Test + void getAll_unknownBundleInABatch_getsNoEntry_singleUnknownBundleStillFails() { + when(bundleService.findByIdIn(any())).thenReturn(Flux.just(Bundle.builder().id("b1").organizationId(ORG_ID).build())); + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.ADMIN))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, List.of("b1", "gone"), ResourceAction.READ_BUNDLES)) + .assertNext(map -> assertThat(map).containsOnlyKeys("b1")) + .verifyComplete(); + + when(bundleService.findById("gone")) + .thenReturn(Mono.error(new BizException(BizError.NO_RESOURCE_FOUND, "BUNDLE_NOT_FOUND", "gone"))); + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, List.of("gone"), ResourceAction.READ_BUNDLES)) + .expectErrorSatisfies(error -> { + assertThat(error).isInstanceOf(BizException.class); + assertThat(((BizException) error).getError()).isEqualTo(BizError.NO_RESOURCE_FOUND); + }) + .verify(); + System.out.println("[BundlePermissionHandlerTest] unknown bundle in a batch left out; a single unknown bundle still fails"); + } + static Stream priorityMatrix() { Stream.Builder builder = Stream.builder(); for (Variant variant : Variant.values()) { diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/DatasourcePermissionHandlerTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/DatasourcePermissionHandlerTest.java index 48db55511a..a6348fb933 100644 --- a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/DatasourcePermissionHandlerTest.java +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/DatasourcePermissionHandlerTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.ORG_ID; +import static org.lowcoder.domain.permission.service.PermissionTestFixtures.OTHER_ORG_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.RESOURCE_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.USER_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.orgMember; @@ -9,18 +10,25 @@ import static org.lowcoder.sdk.constants.Authentication.ANONYMOUS_USER_ID; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; import org.lowcoder.domain.application.model.ApplicationRequestType; import org.lowcoder.domain.bundle.model.BundleRequestType; import org.lowcoder.domain.datasource.model.Datasource; @@ -35,8 +43,10 @@ import org.lowcoder.domain.permission.model.ResourceType; import org.lowcoder.domain.permission.model.UserPermissionOnResourceStatus; import org.lowcoder.sdk.config.CommonConfig; +import org.lowcoder.sdk.constants.FieldName; import org.mockito.ArgumentCaptor; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -68,6 +78,23 @@ void setUp() { when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.MEMBER))); when(groupMemberService.getUserGroupIdsInOrg(ORG_ID, USER_ID)).thenReturn(Mono.just(List.of())); when(resourcePermissionService.getByResourceTypeAndResourceIds(any(), any())).thenReturn(Mono.just(Map.of())); + when(datasourceService.getByIds(any())) + .thenAnswer(invocation -> Flux.fromIterable(invocation.> getArgument(0)) + .map(key -> foundBy(key, ORG_ID))); + } + + /** + * A data source as the batch lookup finds it by {@code key} in {@code orgId}: by gid when FieldName.isGID tells the key + * a gid (a hyphen, as in ds-1), else by object id, as IdOrGidLookup splits the keys. The other field holds a value of + * the other kind that no test asks for. + */ + private static Datasource foundBy(String key, String orgId) { + boolean gidKind = FieldName.isGID(key); + return Datasource.builder() + .id(gidKind ? "oid" + key.replace("-", "") : key) + .gid(gidKind ? key : "gid-" + key) + .organizationId(orgId) + .build(); } /** Catches static datasource lock-out: static ids get an OWNER row, the others follow the member rows. */ @@ -141,6 +168,92 @@ void getAll_staticDatasource_grantsOwnerToAnonymousAndNonMemberCallers() { System.out.println("[DatasourcePermissionHandlerTest] static datasource -> OWNER for anonymous and non-member callers"); } + /** Catches D-38 on data sources: a batch of two normal ids of different workspaces, one batch lookup, each decided + * by its own workspace. */ + @ParameterizedTest + @MethodSource("ordersOfDs1Ds2") + void getAll_normalIdsOfTwoWorkspaces_oneBatchLookup_eachDecidedByItsOwnWorkspace(List ids) { + doReturn(Flux.just(foundBy(DATASOURCE_ID, ORG_ID), foundBy(OTHER_DATASOURCE_ID, OTHER_ORG_ID))).when(datasourceService).getByIds(any()); + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.ADMIN))); + when(orgMemberService.getOrgMember(OTHER_ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(OTHER_ORG_ID, MemberRole.MEMBER))); + when(groupMemberService.getUserGroupIdsInOrg(OTHER_ORG_ID, USER_ID)).thenReturn(Mono.just(List.of())); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, ids, ResourceAction.USE_DATASOURCES)) + .assertNext(map -> { + assertThat(map).containsOnlyKeys(DATASOURCE_ID, OTHER_DATASOURCE_ID); + assertStaticOwnerRow(map.get(DATASOURCE_ID), DATASOURCE_ID, USER_ID); + assertThat(map.get(OTHER_DATASOURCE_ID)).as("admin role in ORG_ID grants nothing in OTHER_ORG_ID").isEmpty(); + }) + .verifyComplete(); + verify(datasourceService, times(1)).getByIds(any()); + verify(datasourceService, never()).getById(any()); + System.out.println("[DatasourcePermissionHandlerTest] D-38 orders " + ids + ": ds-1 (ORG_ID admin) OWNER, ds-2 decided by OTHER_ORG_ID, not borrowed"); + } + + static Stream> ordersOfDs1Ds2() { + return Stream.of(List.of(DATASOURCE_ID, OTHER_DATASOURCE_ID), List.of(OTHER_DATASOURCE_ID, DATASOURCE_ID)); + } + + /** Catches a key asked as a gid getting no entry because {@code orgIdsByKey} matched it against the object-id field. */ + @Test + void getAll_gidKeyInABatch_isAnsweredUnderTheGid() { + String objectIdKey = "dsobj1"; + String gidKey = "6a1b2c3d-0000-4000-8000-000000000001"; + doReturn(Flux.just(foundBy(objectIdKey, ORG_ID), foundBy(gidKey, ORG_ID))).when(datasourceService).getByIds(any()); + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.ADMIN))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, List.of(objectIdKey, gidKey), ResourceAction.USE_DATASOURCES)) + .assertNext(map -> assertThat(map).containsOnlyKeys(objectIdKey, gidKey)) + .verifyComplete(); + System.out.println("[DatasourcePermissionHandlerTest] a gid key in a batch is answered under that gid"); + } + + /** Catches an unknown key in a batch of normal ids getting an entry it should not (an error, or a borrowed row). */ + @Test + void getAll_unknownIdInABatch_getsNoEntry() { + doReturn(Flux.just(foundBy(DATASOURCE_ID, ORG_ID))).when(datasourceService).getByIds(any()); + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.ADMIN))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, List.of(DATASOURCE_ID, OTHER_DATASOURCE_ID), ResourceAction.USE_DATASOURCES)) + .assertNext(map -> assertThat(map).containsOnlyKeys(DATASOURCE_ID)) + .verifyComplete(); + System.out.println("[DatasourcePermissionHandlerTest] an unknown data source key in a batch gets no entry"); + } + + static Stream keyEqualToTheOtherKindOfField() { + return Stream.of( + Arguments.of("object-id key equal to a found gid", List.of("dsobj1", "legacygid"), + Datasource.builder().id("dsobj1").gid("legacygid").organizationId(OTHER_ORG_ID).build(), "dsobj1", "legacygid"), + Arguments.of("gid key equal to a found object id", + List.of("6a1b2c3d-0000-4000-8000-000000000001", "6a1b2c3d-0000-4000-8000-000000000002"), + Datasource.builder().id("6a1b2c3d-0000-4000-8000-000000000002").gid("6a1b2c3d-0000-4000-8000-000000000001") + .organizationId(OTHER_ORG_ID).build(), + "6a1b2c3d-0000-4000-8000-000000000001", "6a1b2c3d-0000-4000-8000-000000000002")); + } + + /** Catches {@code orgIdsByKey} matching a key against the field of the WRONG kind: a legacy gid without a hyphen + * stored in the object-id field, or an object id stored with one. Pins the key-kind rule the batch lookup already + * decides (D-38). */ + @ParameterizedTest(name = "{0}") + @MethodSource("keyEqualToTheOtherKindOfField") + void getAll_keyEqualToTheOtherKindOfField_getsNoEntry(String caseName, List keys, Datasource found, + String answeredKey, String absentKey) { + doReturn(Flux.just(found)).when(datasourceService).getByIds(any()); + when(orgMemberService.getOrgMember(OTHER_ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(OTHER_ORG_ID, MemberRole.ADMIN))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, keys, ResourceAction.USE_DATASOURCES)) + .assertNext(map -> { + assertThat(map).containsOnlyKeys(answeredKey); + assertStaticOwnerRow(map.get(answeredKey), answeredKey, USER_ID); + }) + .verifyComplete(); + verify(datasourceService, times(1)).getByIds(any()); + verify(datasourceService, never()).getById(any()); + verify(orgMemberService, times(1)).getOrgMember(OTHER_ORG_ID, USER_ID); + System.out.println("[DatasourcePermissionHandlerTest] " + caseName + ": " + absentKey + + " matches the other kind of field of a found data source -> no entry"); + } + /** The operations of the handler that decide a status: the generic check and the application/bundle clones. */ enum Operation { RESOURCE, APPLICATION, BUNDLE } diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/PermissionTestFixtures.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/PermissionTestFixtures.java index 60ebc6ea67..b853f18459 100644 --- a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/PermissionTestFixtures.java +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/PermissionTestFixtures.java @@ -18,6 +18,7 @@ final class PermissionTestFixtures { static final String ORG_ID = "org-1"; + static final String OTHER_ORG_ID = "org-2"; static final String USER_ID = "user-1"; static final String OTHER_USER_ID = "user-other"; static final String GROUP_ID = "group-1"; @@ -42,6 +43,10 @@ static OrgMember orgMember(MemberRole role) { return OrgMember.builder().orgId(ORG_ID).userId(USER_ID).role(role).build(); } + static OrgMember orgMember(String orgId, MemberRole role) { + return OrgMember.builder().orgId(orgId).userId(USER_ID).role(role).build(); + } + static void inject(ResourcePermissionHandler handler, OrgMemberService orgMemberService, GroupMemberService groupMemberService, ResourcePermissionService resourcePermissionService, CommonConfig config) { diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/ResourcePermissionHandlerTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/ResourcePermissionHandlerTest.java index 84a9673088..4c4dcc05d1 100644 --- a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/ResourcePermissionHandlerTest.java +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/ResourcePermissionHandlerTest.java @@ -4,6 +4,7 @@ import static org.lowcoder.domain.permission.service.PermissionTestFixtures.GROUP_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.ORG_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.OTHER_GROUP_ID; +import static org.lowcoder.domain.permission.service.PermissionTestFixtures.OTHER_ORG_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.OTHER_USER_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.RESOURCE_ID; import static org.lowcoder.domain.permission.service.PermissionTestFixtures.USER_ID; @@ -11,19 +12,24 @@ import static org.lowcoder.domain.permission.service.PermissionTestFixtures.permission; import static org.lowcoder.sdk.constants.Authentication.ANONYMOUS_USER_ID; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.time.Duration; +import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; @@ -47,6 +53,9 @@ import org.lowcoder.domain.permission.model.UserPermissionOnResourceStatus; import org.lowcoder.domain.solutions.TemplateSolutionService; import org.lowcoder.sdk.config.CommonConfig; +import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; +import org.mockito.ArgumentCaptor; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -63,6 +72,10 @@ enum Variant { RESOURCE, APPLICATION } private static final ApplicationRequestType REQUEST_TYPE = ApplicationRequestType.PUBLIC_TO_ALL; + /** Must equal ResourcePermissionHandler.ORG_LOOKUP_CONCURRENCY (D-38); a literal, not a reference, so that this test + * also compiles, and fails, against a handler without the bound. */ + private static final int EXPECTED_MAX_IN_FLIGHT = 16; + private ApplicationService applicationService; private TemplateSolutionService templateSolutionService; private OrgMemberService orgMemberService; @@ -235,6 +248,212 @@ void getAll_publicRowsAreMergedWithMemberRowsByUnion() { System.out.println("[ResourcePermissionHandlerTest] member row and public row of the same id are both kept, in that order"); } + // ---------------------------------------------------------------- getAllMatchingPermissions: D-38 batched ids + + static Stream> ordersOfA1B1() { + return Stream.of(List.of("a1", "b1"), List.of("b1", "a1")); + } + + static Stream> ordersOfGoneA1() { + return Stream.of(List.of("gone", "a1"), List.of("a1", "gone")); + } + + static Stream> ordersOfSharedA1() { + return Stream.of(List.of("shared", "a1"), List.of("a1", "shared")); + } + + /** Catches the D-38 defect: the workspace and admin role of the first id applied to every id of a batch. */ + @ParameterizedTest + @MethodSource("ordersOfA1B1") + void getAll_idsOfTwoWorkspaces_eachIsDecidedByItsOwnWorkspace(List ids) { + when(applicationService.findByIdWithoutDsl("b1")) + .thenReturn(Mono.just(Application.builder().organizationId(OTHER_ORG_ID).build())); + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.ADMIN))); + when(orgMemberService.getOrgMember(OTHER_ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(OTHER_ORG_ID, MemberRole.MEMBER))); + when(groupMemberService.getUserGroupIdsInOrg(OTHER_ORG_ID, USER_ID)).thenReturn(Mono.just(List.of(OTHER_GROUP_ID))); + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Collection.class); + when(resourcePermissionService.getByResourceTypeAndResourceIds(eq(ResourceType.APPLICATION), captor.capture())) + .thenReturn(Mono.just(Map.of("b1", List.of(row("b1", ResourceHolder.GROUP, OTHER_GROUP_ID, ResourceRole.VIEWER))))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, ids, ResourceAction.EDIT_APPLICATIONS)) + .assertNext(map -> { + assertThat(map).containsOnlyKeys("a1", "b1"); + assertThat(map.get("a1")).hasSize(1); + ResourcePermission a1Row = map.get("a1").get(0); + assertThat(a1Row.getResourceRole()).isEqualTo(ResourceRole.OWNER); + assertThat(a1Row.getResourceHolderId()).isEqualTo(USER_ID); + assertThat(map.get("b1")).as("b1's VIEWER row cannot EDIT, and ORG_ID's admin role grants nothing there").isEmpty(); + }) + .verifyComplete(); + assertThat(captor.getValue()).containsExactly("b1"); + verify(groupMemberService, times(1)).getUserGroupIdsInOrg(OTHER_ORG_ID, USER_ID); + verify(groupMemberService, never()).getUserGroupIdsInOrg(ORG_ID, USER_ID); + verify(orgMemberService, times(1)).getOrgMember(ORG_ID, USER_ID); + verify(orgMemberService, times(1)).getOrgMember(OTHER_ORG_ID, USER_ID); + System.out.println("[ResourcePermissionHandlerTest] D-38 orders " + ids + ": a1 (ORG_ID admin) OWNER, b1 (OTHER_ORG_ID) decided there, not borrowed"); + } + + /** Catches an id of a workspace the user left or was never in getting the first id's answer instead of only its public row. */ + @Test + void getAll_idsOfTwoWorkspaces_notAMemberOfOne_itsIdsGetOnlyPublicRows() { + when(applicationService.findByIdWithoutDsl("b1")) + .thenReturn(Mono.just(Application.builder().organizationId(OTHER_ORG_ID).build())); + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.MEMBER))); + when(orgMemberService.getOrgMember(OTHER_ORG_ID, USER_ID)).thenReturn(Mono.empty()); + ResourcePermission editorRow = row("a1", ResourceHolder.USER, USER_ID, ResourceRole.EDITOR); + when(resourcePermissionService.getByResourceTypeAndResourceIds(eq(ResourceType.APPLICATION), any())) + .thenReturn(Mono.just(Map.of( + "a1", List.of(editorRow), + "b1", List.of(row("b1", ResourceHolder.USER, USER_ID, ResourceRole.OWNER))))); + when(applicationService.getPublicApplicationIds(any())).thenReturn(Mono.just(Set.of("b1"))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, List.of("a1", "b1"), ResourceAction.READ_APPLICATIONS)) + .assertNext(map -> { + assertThat(map).containsOnlyKeys("a1", "b1"); + assertThat(map.get("a1")).containsExactly(editorRow); + assertThat(map.get("b1")).as("only the anonymous VIEWER row, not the stored OWNER row").hasSize(1); + assertAnonymousViewerRow(map.get("b1").get(0), "b1"); + }) + .verifyComplete(); + System.out.println("[ResourcePermissionHandlerTest] not a member of b1's workspace -> only b1's public row, not its stored OWNER row"); + } + + /** Catches an unknown id in a batch failing the whole call instead of getting no entry (D-38). */ + @ParameterizedTest + @MethodSource("ordersOfGoneA1") + void getAll_batchWithAnUnknownId_leavesItOut(List ids) { + when(applicationService.findByIdWithoutDsl("gone")) + .thenReturn(Mono.error(new BizException(BizError.NO_RESOURCE_FOUND, "CANT_FIND_APPLICATION", "gone"))); + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.ADMIN))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, ids, ResourceAction.MANAGE_APPLICATIONS)) + .assertNext(map -> { + assertThat(map).containsOnlyKeys("a1"); + assertThat(map.get("a1")).hasSize(1); + assertThat(map.get("a1").get(0).getResourceRole()).isEqualTo(ResourceRole.OWNER); + }) + .verifyComplete(); + System.out.println("[ResourcePermissionHandlerTest] unknown id in a batch, orders " + ids + ": left out, the rest answered"); + } + + /** Catches an application slug shared by two or more applications failing or borrowing an answer in a batch. */ + @ParameterizedTest + @MethodSource("ordersOfSharedA1") + void getAll_batchWithASharedSlug_leavesItOut(List ids) { + when(applicationService.findByIdWithoutDsl("shared")) + .thenReturn(Mono.error(new BizException(BizError.NO_RESOURCE_FOUND, "CANT_FIND_APPLICATION", "shared"))); + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.ADMIN))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, ids, ResourceAction.MANAGE_APPLICATIONS)) + .assertNext(map -> { + assertThat(map).containsOnlyKeys("a1"); + assertThat(map.get("a1")).hasSize(1); + assertThat(map.get("a1").get(0).getResourceRole()).isEqualTo(ResourceRole.OWNER); + }) + .verifyComplete(); + verify(applicationService, times(1)).findByIdWithoutDsl("shared"); + verify(orgMemberService, times(1)).getOrgMember(ORG_ID, USER_ID); + System.out.println("[ResourcePermissionHandlerTest] batch orders " + ids + + ": \"shared\" is an application slug held by more than one application -> no entry, the batch is not failed"); + } + + /** Catches a one-id request for an unknown id losing its NO_RESOURCE_FOUND answer (the unchanged one-id contract). */ + @Test + void getAll_singleUnknownId_stillFailsWithNoResourceFound() { + when(applicationService.findByIdWithoutDsl("gone")) + .thenReturn(Mono.error(new BizException(BizError.NO_RESOURCE_FOUND, "CANT_FIND_APPLICATION", "gone"))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, List.of("gone"), ResourceAction.READ_APPLICATIONS)) + .expectErrorSatisfies(error -> { + assertThat(error).isInstanceOf(BizException.class); + assertThat(((BizException) error).getError()).isEqualTo(BizError.NO_RESOURCE_FOUND); + }) + .verify(); + verifyNoInteractions(orgMemberService); + System.out.println("[ResourcePermissionHandlerTest] a single unknown id still fails with NO_RESOURCE_FOUND, no org lookup made"); + } + + /** Catches a failed lookup (anything but NO_RESOURCE_FOUND) being swallowed instead of failing the whole batch. */ + @Test + void getAll_batchLookupFailure_failsTheWholeAnswer() { + IllegalStateException lookupFailure = new IllegalStateException("lookup failure"); + when(applicationService.findByIdWithoutDsl("a2")).thenReturn(Mono.error(lookupFailure)); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, List.of("a1", "a2"), ResourceAction.READ_APPLICATIONS)) + .expectErrorMatches(error -> error == lookupFailure) + .verify(); + System.out.println("[ResourcePermissionHandlerTest] a failed lookup (not NO_RESOURCE_FOUND) fails the whole batch answer"); + } + + /** Catches a blank id reaching the per-id lookup instead of being dropped before it. */ + @Test + void getAll_batchWithBlankIds_looksUpOnlyTheOthers() { + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.ADMIN))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, List.of("", " ", "a1"), ResourceAction.MANAGE_APPLICATIONS)) + .assertNext(map -> assertThat(map).containsOnlyKeys("a1")) + .verifyComplete(); + verify(applicationService, never()).findByIdWithoutDsl(""); + verify(applicationService, never()).findByIdWithoutDsl(" "); + System.out.println("[ResourcePermissionHandlerTest] blank ids in a batch are dropped before any lookup"); + } + + /** Catches an unbounded fan-out of per-id lookups (D-38, ORG_LOOKUP_CONCURRENCY). */ + @Test + void getAll_manyIdsOfOneWorkspace_oneLookupPerIdAtMostTheBoundInFlight() { + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.MEMBER))); + List ids = new ArrayList<>(); + for (int i = 0; i < 40; i++) { + ids.add("app-" + i); + } + AtomicInteger inFlight = new AtomicInteger(); + AtomicInteger maxInFlight = new AtomicInteger(); + when(applicationService.findByIdWithoutDsl(anyString())).thenAnswer(invocation -> Mono.defer(() -> { + int current = inFlight.incrementAndGet(); + maxInFlight.updateAndGet(max -> Math.max(max, current)); + return Mono.just(Application.builder().organizationId(ORG_ID).build()) + // a single scheduler thread serializes every decrement against the next slot's increment, so the + // measured maximum cannot overshoot from a race between two scheduler threads + .delayElement(Duration.ofMillis(20), reactor.core.scheduler.Schedulers.single()) + .doFinally(signal -> inFlight.decrementAndGet()); + })); + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Collection.class); + when(resourcePermissionService.getByResourceTypeAndResourceIds(eq(ResourceType.APPLICATION), captor.capture())) + .thenReturn(Mono.just(Map.of())); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, ids, ResourceAction.READ_APPLICATIONS)) + .assertNext(map -> { + assertThat(map).hasSize(40); + map.values().forEach(rows -> assertThat(rows).isEmpty()); + }) + .verifyComplete(); + ids.forEach(id -> verify(applicationService, times(1)).findByIdWithoutDsl(id)); + // Measured 2026-11-24 (JDK 17, this classpath's reactor-core): Flux.flatMap's own prefetch/replenish + // bookkeeping lets one extra inner Mono start before a completing one is accounted for, so the observed + // ceiling is the configured bound plus one, not the bound itself. The assertion pins that measured ceiling + // (deterministic across repeated runs here), which still proves the fan-out is bounded far below 40 ids at + // once, and well above the unfixed code's single lookup. + assertThat(maxInFlight.get()).as("max concurrent lookups").isEqualTo(EXPECTED_MAX_IN_FLIGHT + 1); + verify(orgMemberService, times(1)).getOrgMember(ORG_ID, USER_ID); + assertThat(captor.getValue()).containsExactlyElementsOf(ids); + System.out.println("[ResourcePermissionHandlerTest] 40 ids of one workspace: one lookup per id, max " + maxInFlight.get() + + " in flight (configured bound " + EXPECTED_MAX_IN_FLIGHT + ", measured ceiling " + (EXPECTED_MAX_IN_FLIGHT + 1) + ")"); + } + + /** Catches the member-path toMap duplicate-key failure (BF-style) on a batch holding the same id twice. */ + @Test + void getAll_duplicateIdsOfAMember_areAnsweredOnce() { + when(orgMemberService.getOrgMember(ORG_ID, USER_ID)).thenReturn(Mono.just(orgMember(MemberRole.MEMBER))); + + StepVerifier.create(handler.getAllMatchingPermissions(USER_ID, List.of("a1", "a1", "a2"), ResourceAction.READ_APPLICATIONS)) + .assertNext(map -> assertThat(map).containsOnlyKeys("a1", "a2")) + .verifyComplete(); + verify(applicationService, times(1)).findByIdWithoutDsl("a1"); + System.out.println("[ResourcePermissionHandlerTest] duplicate ids in a batch are answered once (no toMap duplicate-key failure)"); + } + // ---------------------------------------------------------------- check*: anonymous /** Catches a wrong status for anonymous users: public -> VIEWER success, otherwise the anonymous-user failure. */ diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/ResourcePermissionServiceImplTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/ResourcePermissionServiceImplTest.java new file mode 100644 index 0000000000..bb75bcae6e --- /dev/null +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/permission/service/ResourcePermissionServiceImplTest.java @@ -0,0 +1,79 @@ +package org.lowcoder.domain.permission.service; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.lowcoder.domain.permission.model.ResourceHolder; +import org.lowcoder.domain.permission.model.ResourceType; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** + * The four {@code removeUser*Permission} methods of {@link ResourcePermissionServiceImpl} (D-59: the data source one + * used to call {@code repository.removePermissionBy} with {@code ResourceType.APPLICATION}, a copy-paste of the + * application method; D-60: folders and bundles had no removal method at all). Each is a one-liner to + * {@code repository.removePermissionBy}; the resource id and the user id are different strings so a swapped argument + * fails. + */ +class ResourcePermissionServiceImplTest { + + private static final String LOG_PREFIX = "[ResourcePermissionServiceImplTest] "; + private static final String RESOURCE_ID = "resource-1"; + private static final String USER_ID = "user-1"; + + private final ResourcePermissionRepository repository = mock(ResourcePermissionRepository.class); + private final ResourcePermissionServiceImpl service = new ResourcePermissionServiceImpl(repository, + mock(ResourcePermissionHandlerService.class), mock(ResourcePermissionHandlerService.class), mock(ResourcePermissionHandlerService.class)); + + private static void say(String format, Object... args) { + System.out.println(LOG_PREFIX + String.format(format, args)); + } + + @Test + void removeUserApplicationPermission_removesByApplicationTypeExactly() { + when(repository.removePermissionBy(ResourceType.APPLICATION, RESOURCE_ID, ResourceHolder.USER, USER_ID)).thenReturn(Mono.just(true)); + + StepVerifier.create(service.removeUserApplicationPermission(RESOURCE_ID, USER_ID)).expectNext(true).verifyComplete(); + + verify(repository).removePermissionBy(ResourceType.APPLICATION, RESOURCE_ID, ResourceHolder.USER, USER_ID); + verifyNoMoreInteractions(repository); + say("removeUserApplicationPermission(%s, %s) -> removePermissionBy(APPLICATION, %s, USER, %s)", RESOURCE_ID, USER_ID, RESOURCE_ID, USER_ID); + } + + @Test + void removeUserDatasourcePermission_removesByDatasourceTypeExactly_notApplicationD59() { + when(repository.removePermissionBy(ResourceType.DATASOURCE, RESOURCE_ID, ResourceHolder.USER, USER_ID)).thenReturn(Mono.just(true)); + + StepVerifier.create(service.removeUserDatasourcePermission(RESOURCE_ID, USER_ID)).expectNext(true).verifyComplete(); + + verify(repository).removePermissionBy(ResourceType.DATASOURCE, RESOURCE_ID, ResourceHolder.USER, USER_ID); + verifyNoMoreInteractions(repository); + say("removeUserDatasourcePermission(%s, %s) -> removePermissionBy(DATASOURCE, %s, USER, %s), D-59", + RESOURCE_ID, USER_ID, RESOURCE_ID, USER_ID); + } + + @Test + void removeUserFolderPermission_removesByFolderTypeExactlyD60() { + when(repository.removePermissionBy(ResourceType.FOLDER, RESOURCE_ID, ResourceHolder.USER, USER_ID)).thenReturn(Mono.just(true)); + + StepVerifier.create(service.removeUserFolderPermission(RESOURCE_ID, USER_ID)).expectNext(true).verifyComplete(); + + verify(repository).removePermissionBy(ResourceType.FOLDER, RESOURCE_ID, ResourceHolder.USER, USER_ID); + verifyNoMoreInteractions(repository); + say("removeUserFolderPermission(%s, %s) -> removePermissionBy(FOLDER, %s, USER, %s), D-60", RESOURCE_ID, USER_ID, RESOURCE_ID, USER_ID); + } + + @Test + void removeUserBundlePermission_removesByBundleTypeExactlyD60() { + when(repository.removePermissionBy(ResourceType.BUNDLE, RESOURCE_ID, ResourceHolder.USER, USER_ID)).thenReturn(Mono.just(true)); + + StepVerifier.create(service.removeUserBundlePermission(RESOURCE_ID, USER_ID)).expectNext(true).verifyComplete(); + + verify(repository).removePermissionBy(ResourceType.BUNDLE, RESOURCE_ID, ResourceHolder.USER, USER_ID); + verifyNoMoreInteractions(repository); + say("removeUserBundlePermission(%s, %s) -> removePermissionBy(BUNDLE, %s, USER, %s), D-60", RESOURCE_ID, USER_ID, RESOURCE_ID, USER_ID); + } +} diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/EmailCommunicationServiceImplTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/EmailCommunicationServiceImplTest.java index deb96bce4f..e3cef70fab 100644 --- a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/EmailCommunicationServiceImplTest.java +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/EmailCommunicationServiceImplTest.java @@ -19,6 +19,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import org.lowcoder.sdk.config.CommonConfig; import org.mockito.ArgumentCaptor; import org.springframework.mail.MailSendException; @@ -131,6 +132,23 @@ void theTokenIsPercentEncodedInTheResetLink() throws Exception { assertThat(URLDecoder.decode(query, StandardCharsets.UTF_8)).isEqualTo(token); } + /** + * D-54: the reset link has exactly one slash before the path whether the configured public URL ends in none, one + * or several slashes. The double-slash case is the one {@code StringUtils.removeEnd} would fail (it removes one + * slash only). + */ + @ParameterizedTest(name = "public URL \"{0}\"") + @ValueSource(strings = {PUBLIC_URL, PUBLIC_URL + "/", PUBLIC_URL + "//"}) + void resetLinkHasExactlyOneSlashWhateverTrailingSlashesThePublicUrlHasD54(String publicUrl) throws Exception { + config.setLowcoderPublicUrl(publicUrl); + + assertThat(service.sendPasswordResetEmail(RECIPIENT, "tok", "%s %s")).isTrue(); + + String link = body(sentOnce()).substring((RECIPIENT + " ").length()); + System.out.println("[EmailCommunicationServiceImplTest] public URL '" + publicUrl + "' -> link '" + link + "'"); + assertThat(link).startsWith(LINK_PREFIX).isEqualTo(LINK_PREFIX + "tok"); + } + /** Catches: a failed send or a broken message being reported as success, or an exception escaping. */ @Test void resetMailFailuresReturnFalseInsteadOfThrowing() { diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/UserServiceImplPasswordTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/UserServiceImplPasswordTest.java index 154de5a62a..1b2fc4a9b0 100644 --- a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/UserServiceImplPasswordTest.java +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/user/service/UserServiceImplPasswordTest.java @@ -6,6 +6,7 @@ import static org.lowcoder.domain.user.service.UserServiceFixture.USER_EMAIL; import static org.lowcoder.domain.user.service.UserServiceFixture.USER_ID; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -35,6 +36,8 @@ import org.lowcoder.sdk.util.HashUtils; import org.mockito.ArgumentCaptor; +import com.mongodb.client.result.UpdateResult; + import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -173,6 +176,57 @@ void setPassword_encryptsAndSaves() { System.out.println("[UserServiceImplPasswordTest] setPassword stored a hash that matches the password"); } + // ---------------------------------------------------------------- setPasswordIfAbsent + + /** Catches the check and the write disagreeing, or a fallback to the unconditional save ({@code UserServiceImpl.setPasswordIfAbsent}). */ + @Test + void setPasswordIfAbsent_noPassword_writesTheHashOfThePassword() { + when(fixture.repository.setPasswordIfAbsent(eq(USER_ID), anyString())) + .thenReturn(Mono.just(UpdateResult.acknowledged(1, 1L, null))); + + StepVerifier.create(service.setPasswordIfAbsent(USER_ID, NEW_PASSWORD)).expectNext(true).verifyComplete(); + + ArgumentCaptor hash = ArgumentCaptor.forClass(String.class); + verify(fixture.repository).setPasswordIfAbsent(eq(USER_ID), hash.capture()); + assertThat(hash.getValue()).isNotEqualTo(NEW_PASSWORD); + assertThat(fixture.encryptionService.matchPassword(NEW_PASSWORD, hash.getValue())).isTrue(); + verify(fixture.repository, never()).save(any(User.class)); + System.out.println("[UserServiceImplPasswordTest] setPasswordIfAbsent on a passwordless account stored a hash that matches the password"); + } + + /** Catches the conditional write losing the race and silently overwriting an existing password ({@code UserServiceImpl.setPasswordIfAbsent}). */ + @Test + void setPasswordIfAbsent_passwordPresent_failsPasswordAlreadySetAndChangesNothing() { + User user = fixture.userWithPassword(OLD_PASSWORD); + String storedHash = user.getPassword(); + when(fixture.repository.setPasswordIfAbsent(eq(USER_ID), anyString())) + .thenReturn(Mono.just(UpdateResult.acknowledged(0, 0L, null))); + when(fixture.repository.findById(USER_ID)).thenReturn(Mono.just(user)); + + StepVerifier.create(service.setPasswordIfAbsent(USER_ID, NEW_PASSWORD)) + .expectErrorSatisfies(error -> assertBizError(error, BizError.INVALID_PASSWORD, "PASSWORD_ALREADY_SET")) + .verify(); + + verify(fixture.repository, never()).save(any(User.class)); + assertThat(user.getPassword()).isEqualTo(storedHash); + System.out.println("[UserServiceImplPasswordTest] setPasswordIfAbsent on an account with a password -> PASSWORD_ALREADY_SET, nothing changed"); + } + + /** Catches an unknown account being reported as "already has a password" instead of USER_NOT_EXIST ({@code UserServiceImpl.setPasswordIfAbsent}). */ + @Test + void setPasswordIfAbsent_unknownUser_failsUserNotExist() { + when(fixture.repository.setPasswordIfAbsent(eq(MISSING_USER_ID), anyString())) + .thenReturn(Mono.just(UpdateResult.acknowledged(0, 0L, null))); + when(fixture.repository.findById(MISSING_USER_ID)).thenReturn(Mono.empty()); + + StepVerifier.create(service.setPasswordIfAbsent(MISSING_USER_ID, NEW_PASSWORD)) + .expectErrorSatisfies(error -> assertBizError(error, BizError.USER_NOT_EXIST, USER_NOT_EXIST_KEY)) + .verify(); + + verify(fixture.repository, never()).save(any(User.class)); + System.out.println("[UserServiceImplPasswordTest] setPasswordIfAbsent on an unknown id -> USER_NOT_EXIST, nothing saved"); + } + /** Catches the super admin flag not being set ({@code UserServiceImpl.markAsSuperAdmin}). */ @Test void markAsSuperAdmin_setsFlagAndSaves() { @@ -238,7 +292,7 @@ void resetLostPassword_success_setsHashAndInvalidatesTheToken() { stubEmailLookup(user); StepVerifier.create(service.resetLostPassword(USER_EMAIL, TOKEN, NEW_PASSWORD)) - .expectNext(true) + .expectNext(USER_ID) .verifyComplete(); assertThat(fixture.encryptionService.matchPassword(NEW_PASSWORD, user.getPassword())).isTrue(); @@ -274,7 +328,7 @@ void resetLostPassword_fallsBackToLookupByName() { when(fixture.repository.findByName("some-handle")).thenReturn(Mono.just(user)); StepVerifier.create(service.resetLostPassword("some-handle", TOKEN, NEW_PASSWORD)) - .expectNext(true) + .expectNext(USER_ID) .verifyComplete(); verify(fixture.repository).findByName("some-handle"); System.out.println("[UserServiceImplPasswordTest] reset resolved the account by name after an empty e-mail lookup"); diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/config/CommonConfig.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/config/CommonConfig.java index 917aad6b52..b5596df997 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/config/CommonConfig.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/config/CommonConfig.java @@ -69,6 +69,15 @@ public static String normalizeDataUnits(String dataWithUnits) return normalized; } + /** + * D-54: the public URL without its trailing run of slashes, so that {@code url + "/path"} has exactly one slash before + * the path whether the configured URL ends in none, one or several. Only the trailing run is removed; a doubled slash + * elsewhere is kept. {@code null} stays {@code null}. + */ + public static String withoutTrailingSlashes(String url) { + return StringUtils.stripEnd(url, "/"); + } + public void setMaxUploadSize(String size) { this.maxUploadSize = normalizeDataUnits(size); diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/exception/BizError.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/exception/BizError.java index d7ecb6f1ff..3197ad4b97 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/exception/BizError.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/exception/BizError.java @@ -134,6 +134,7 @@ public enum BizError { // user related, code range 6200 - 6250, INVALID_USER_STATUS(500, 6200), USER_BANNED(500, 6201), + PASSWORD_CHANGED_SESSIONS_NOT_ENDED(500, 6202), // license related, code range 6251 - 6300 CANT_DEPLOY_IN_AIR_GAPPED_ENV(400, 6251), diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/PasswordRule.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/PasswordRule.java new file mode 100644 index 0000000000..4d21e7b530 --- /dev/null +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/PasswordRule.java @@ -0,0 +1,41 @@ +package org.lowcoder.sdk.util; + +import java.util.regex.Pattern; + +/** + * The password rule of the client ({@code client/packages/lowcoder/src/pages/userAuth/authUtils.ts} {@code checkPassWithMsg}), + * enforced by the server for every password a user chooses (D-48): sign-up, an admin's create-user route, password change, + * lost-password reset, first password of a provider-only account. Same definitions as the browser: length in UTF-16 code + * units ({@code String.length()} = JS {@code length}); an ASCII letter ({@code /[a-zA-Z]/}); an ASCII digit ({@code /\d/} + * without the {@code u} flag); no character of JS {@code /\s/}, i.e. ECMAScript WhiteSpace plus LineTerminator, listed + * explicitly because Java's {@code \s} matches only six of those 25 code points. + * + *

Not applied, on purpose: sign-in (existing weak passwords keep working), the super admin password from the environment + * and server-generated passwords (ENTERPRISE reset). Limits: the whitespace list is the one Node v24.14.1 enumerates; a + * future Unicode version that adds a space separator changes the browser's set but not this one. The en/zh/de texts of + * {@code PASSWORD_TOO_WEAK} state the number 8; change them with {@link #MIN_LENGTH}. The rule is length, letter, digit + * and whitespace only; no breach list or strength estimate (the client has none either); there is no forced rotation of + * existing weak passwords. + */ +public final class PasswordRule { + + public static final int MIN_LENGTH = 8; + + /** JS {@code /\s/}: U+0009-000D, U+0020, U+00A0, U+1680, U+2000-200A, U+2028, U+2029, U+202F, U+205F, U+3000, U+FEFF. */ + private static final Pattern WHITESPACE = Pattern.compile( + "[\\t\\n\\u000B\\f\\r \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF]"); + private static final Pattern ASCII_LETTER = Pattern.compile("[a-zA-Z]"); + private static final Pattern ASCII_DIGIT = Pattern.compile("[0-9]"); + + private PasswordRule() { + } + + /** Whether the client's rule accepts {@code password}; {@code null} is not acceptable. */ + public static boolean isAcceptable(String password) { + return password != null + && password.length() >= MIN_LENGTH + && ASCII_LETTER.matcher(password).find() + && ASCII_DIGIT.matcher(password).find() + && !WHITESPACE.matcher(password).find(); + } +} diff --git a/server/api-service/lowcoder-sdk/src/main/resources/locale_de.properties b/server/api-service/lowcoder-sdk/src/main/resources/locale_de.properties index 7f1d45c9c1..19cc2e584d 100644 --- a/server/api-service/lowcoder-sdk/src/main/resources/locale_de.properties +++ b/server/api-service/lowcoder-sdk/src/main/resources/locale_de.properties @@ -52,6 +52,9 @@ LOG_IN_SOURCE_NOT_SUPPORTED=Entschuldigung, dieser Anmeldekanal wird nicht unter USER_LOGIN_ID_EXIST=Die aktuelle E-Mail wird bereits von einem anderen Benutzer verwendet. INVALID_PASSWORD=Entschuldigung, die Passwörter stimmen nicht überein. PASSWORD_NOT_SET_YET=Dieser Benutzer hat noch kein Passwort festgelegt und kann es daher nicht zurücksetzen. +PASSWORD_ALREADY_SET=Dieses Konto hat bereits ein Passwort; ändern Sie es mit dem aktuellen Passwort. +PASSWORD_TOO_WEAK=Das Passwort muss mindestens 8 Zeichen lang sein, Buchstaben und Ziffern enthalten und darf keine Leerzeichen enthalten. +PASSWORD_CHANGED_SESSIONS_NOT_ENDED=Das Passwort wurde geändert, aber {0} frühere Sitzung(en) konnten nicht abgemeldet werden. Ändern oder setzen Sie das Passwort erneut zurück, um sie abzumelden. INVALID_EMAIL_OR_PASSWORD=Ungültige E-Mail oder ungültiges Passwort. ALREADY_BIND=Entschuldigung, {0} wurde bereits von Benutzer {1} gebunden. NEED_BIND_THIRD_PARTY_CONNECTION=Entschuldigung, es muss ein Drittanbieter-Anmeldekanal mit dem aktuellen Workspace verbunden werden. diff --git a/server/api-service/lowcoder-sdk/src/main/resources/locale_en.properties b/server/api-service/lowcoder-sdk/src/main/resources/locale_en.properties index 390fdc2d18..446afeca05 100644 --- a/server/api-service/lowcoder-sdk/src/main/resources/locale_en.properties +++ b/server/api-service/lowcoder-sdk/src/main/resources/locale_en.properties @@ -98,6 +98,9 @@ BAD_REQUEST=Bad request. INVALID_USER_ID=Invalid parameter: the user ID is invalid. INVALID_USER_ROLE=Invalid parameter: the user role is invalid. PASSWORD_EMPTY=Invalid parameter: the password is empty. +PASSWORD_ALREADY_SET=This account already has a password; change it with the current password. +PASSWORD_TOO_WEAK=The password must be at least 8 characters long, contain a letter and a digit, and contain no whitespace. +PASSWORD_CHANGED_SESSIONS_NOT_ENDED=The password was changed, but {0} earlier session(s) could not be signed out. Change or reset the password again to sign them out. INSUFFICIENT_PERMISSION=Insufficient permissions: you are not in the workspace, please contact admin of this workspace. NO_PERMISSION_TO_EDIT=It appears you don''t have the permission to edit, please contact the app owners {0}. NO_PERMISSION_TO_VIEW=It appears you don''t have the permission to view, please contact the app owners {0}. diff --git a/server/api-service/lowcoder-sdk/src/main/resources/locale_zh.properties b/server/api-service/lowcoder-sdk/src/main/resources/locale_zh.properties index bad5796548..45b8c13f65 100644 --- a/server/api-service/lowcoder-sdk/src/main/resources/locale_zh.properties +++ b/server/api-service/lowcoder-sdk/src/main/resources/locale_zh.properties @@ -98,6 +98,9 @@ BAD_REQUEST=错误的请求。 INVALID_USER_ID=无效参数:用户ID无效。 INVALID_USER_ROLE=参数无效:用户角色无效。 PASSWORD_EMPTY=无效参数:密码为空。 +PASSWORD_ALREADY_SET=该账户已设置密码,请使用当前密码修改。 +PASSWORD_TOO_WEAK=密码至少需要 8 个字符,必须包含字母和数字,且不能包含空白字符。 +PASSWORD_CHANGED_SESSIONS_NOT_ENDED=密码已修改,但有 {0} 个此前的会话未能退出。请再次修改或重置密码以退出这些会话。 INSUFFICIENT_PERMISSION=权限不足:您不在工作区,请联系该工作区管理员。 NO_PERMISSION_TO_EDIT=您似乎没有编辑权限,请联系应用程序所有者 {0}。 NO_PERMISSION_TO_VIEW=您似乎没有查看权限,请联系应用程序所有者 {0}。 diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/config/CommonConfigTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/config/CommonConfigTest.java index de3cd44da9..0ea4d21e14 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/config/CommonConfigTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/config/CommonConfigTest.java @@ -77,6 +77,25 @@ public void corsDomainsFromTheListAndTheCommaStringAreCombinedListFirst() { assertEquals(List.of("*"), security.getAllCorsAllowedDomains(), "the default of the application yaml"); } + /** D-54: only the trailing run of slashes is removed; a doubled slash elsewhere, an empty string and null are kept as they are. */ + @Test + public void withoutTrailingSlashesRemovesOnlyTheTrailingRun() { + Map expected = new LinkedHashMap<>(); + expected.put("http://h", "http://h"); + expected.put("http://h/", "http://h"); + expected.put("http://h//", "http://h"); + expected.put("http://h///", "http://h"); + expected.put("http://h/base//", "http://h/base"); + expected.put("http://h//base/", "http://h//base"); + expected.put("", ""); + expected.forEach((input, normalized) -> { + System.out.println("[CommonConfigTest] withoutTrailingSlashes('" + input + "') -> '" + CommonConfig.withoutTrailingSlashes(input) + "'"); + assertEquals(normalized, CommonConfig.withoutTrailingSlashes(input), "'" + input + "'"); + }); + + assertEquals(null, CommonConfig.withoutTrailingSlashes(null), "null stays null"); + } + @Test public void derivedValuesFollowTheirSettings() { CommonConfig config = new CommonConfig(); diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/PasswordRuleTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/PasswordRuleTest.java new file mode 100644 index 0000000000..453d684aa2 --- /dev/null +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/PasswordRuleTest.java @@ -0,0 +1,94 @@ +package org.lowcoder.sdk.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Set; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * {@link PasswordRule} (D-48) must accept and refuse exactly what the client's JS rule + * ({@code checkPassWithMsg}) does. Every non-ASCII or invisible character is written as a Java + * Unicode escape (backslash, u, four hex digits), never as a literal character, so the file + * stays readable in any editor (tab, LF, VT, FF and CR use the standard one-letter escapes instead). + */ +class PasswordRuleTest { + + /** + * The 25 code points of ECMAScript {@code /\s/} (WhiteSpace + LineTerminator), measured on Node + * v24.14.1 as documented in {@link PasswordRule}'s javadoc. + */ + private static final Set JS_WHITESPACE = Set.of( + 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x0020, + 0x00A0, 0x1680, + 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, + 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0xFEFF); + + private static Stream acceptanceCases() { + return Stream.of( + Arguments.of("null", null, false), + Arguments.of("empty", "", false), + Arguments.of("7 UTF-16 code units", "Passw0r", false), + Arguments.of("exactly 8", "Passw0rd", true), + Arguments.of("8 code units, 5 code points", "a1" + "\uD83D\uDE00".repeat(3), true), + Arguments.of("7 code units", "a1" + "\uD83D\uDE00".repeat(2) + "b", false), + Arguments.of("no ASCII digit", "Passwordx", false), + Arguments.of("no ASCII letter", "12345678", false), + Arguments.of("non-ASCII letters only", "\u00E9".repeat(7) + "1", false), + Arguments.of("non-ASCII digit only", "Password\u0663", false), + Arguments.of("space", "Pass w0rd", false), + Arguments.of("tab", "Passw0rd\t", false), + Arguments.of("LF", "Passw0rd\n", false), + Arguments.of("VT", "Passw0rd\u000B", false), + Arguments.of("FF", "Passw0rd\f", false), + Arguments.of("CR", "Passw0rd\r", false), + Arguments.of("NBSP", "Passw0rd\u00A0", false), + Arguments.of("U+1680", "Passw0rd\u1680", false), + Arguments.of("U+2000", "Passw0rd\u2000", false), + Arguments.of("U+200A", "Passw0rd\u200A", false), + Arguments.of("U+2028", "Passw0rd\u2028", false), + Arguments.of("U+2029", "Passw0rd\u2029", false), + Arguments.of("U+202F", "Passw0rd\u202F", false), + Arguments.of("U+205F", "Passw0rd\u205F", false), + Arguments.of("U+3000", "Passw0rd\u3000", false), + Arguments.of("U+FEFF", "Passw0rd\uFEFF", false), + Arguments.of("zero-width space (not JS whitespace)", "Passw0rd\u200B", true), + Arguments.of("U+180E (not JS whitespace since Unicode 6.3)", "Passw0rd\u180E", true), + Arguments.of("e2e password", "Passw0rd-e2e", true), + Arguments.of("e2e password changed", "Passw0rd-e2e-changed", true), + Arguments.of("e2e password other", "Passw0rd-e2e-other", true), + Arguments.of("UpdatePasswordRequest fixture", "UpdatePasswordRequest.newPassword1", true), + Arguments.of("ResetLostPasswordRequest fixture", "ResetLostPasswordRequest.newPassword1", true), + Arguments.of("UserEndpointsContractTest fixture", "UserEndpointsContractTest.password1", true), + Arguments.of("lowcoder1 fixture", "lowcoder1", true), + Arguments.of("the measured defect value", "a", false)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("acceptanceCases") + void isAcceptable_matchesTheClientRule(String label, String value, boolean expected) { + boolean actual = PasswordRule.isAcceptable(value); + System.out.println("[PasswordRuleTest] " + label + " -> " + actual + " (expected " + expected + ")"); + assertEquals(expected, actual, label); + } + + @Test + void everyCodeUnitIsRefusedExactlyWhenItIsJsWhitespace() { + for (int c = 0; c <= 0xFFFF; c++) { + boolean expectedAcceptable = !JS_WHITESPACE.contains(c); + boolean actual = PasswordRule.isAcceptable("Passw0rd" + (char) c); + assertEquals(expectedAcceptable, actual, "code unit 0x" + Integer.toHexString(c)); + } + System.out.println("[PasswordRuleTest] every code unit 0x0000-0xFFFF matches JS_WHITESPACE membership"); + } + + @Test + void minLengthIsEight() { + assertEquals(8, PasswordRule.MIN_LENGTH); + System.out.println("[PasswordRuleTest] MIN_LENGTH=" + PasswordRule.MIN_LENGTH); + } +} diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationApiServiceImpl.java index ecc6364416..83c7a1d4d7 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationApiServiceImpl.java @@ -130,7 +130,8 @@ public Mono create(CreateApplicationRequest createApplicationRe return sessionUserService.getVisitorId() .flatMap(userId -> orgMemberService.getOrgMember(application.getOrganizationId(), userId)) .switchIfEmpty(deferredError(NOT_AUTHORIZED, "NOT_AUTHORIZED")) - .delayUntil(orgMember -> orgDevChecker.checkCurrentOrgDev()) + // developer of the target workspace, not of the current one (D-11, D-41) + .delayUntil(orgDevChecker::checkOrgDev) .delayUntil(bizThresholdChecker::checkMaxOrgApplicationCount) .delayUntil(orgMember -> { String folderId = createApplicationRequest.folderId(); @@ -389,10 +390,12 @@ public Mono updateUserApplicationLastViewTime(String applicationId) { @Override public Mono update(String applicationId, Application application, Boolean updateStatus) { + // a status change needs the owner right, like recycle, restore and delete (D-9) + ResourceAction required = Boolean.TRUE.equals(updateStatus) ? MANAGE_APPLICATIONS : EDIT_APPLICATIONS; return (Boolean.TRUE.equals(updateStatus) ? Mono.empty() : checkApplicationStatus(applicationId, NORMAL)) .then(sessionUserService.getVisitorId()) .flatMap(userId -> resourcePermissionService.checkAndReturnMaxPermission(userId, - applicationId, EDIT_APPLICATIONS)) + applicationId, required)) // the organization of the stored application, not of the request body, which the client may leave out .delayUntil(__ -> applicationService.findById(applicationId) .flatMap(stored -> checkDatasourcePermissions(application, stored.getOrganizationId()))) @@ -683,7 +686,9 @@ public Mono setApplicationAsAgencyProfile(String applicationId, boolean @Override public Mono updateSlug(String applicationId, String slug) { - return applicationService.updateSlug(applicationId, slug); + // D-37: EDIT on the app; deferred so the domain call is not even built on a denial + return checkCurrentUserApplicationPermission(applicationId, EDIT_APPLICATIONS) + .then(Mono.defer(() -> applicationService.updateSlug(applicationId, slug))); } private Map sanitizeDsl(Map applicationDsl) { diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationHistorySnapshotController.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationHistorySnapshotController.java index b637f576ed..eab279b430 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationHistorySnapshotController.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationHistorySnapshotController.java @@ -29,6 +29,8 @@ import java.util.stream.Collectors; import static org.lowcoder.api.util.ViewBuilder.multiBuild; +import static org.lowcoder.sdk.exception.BizError.INVALID_HISTORY_SNAPSHOT; +import static org.lowcoder.sdk.util.ExceptionUtils.deferredError; @RequiredArgsConstructor @RestController @@ -45,14 +47,12 @@ public class ApplicationHistorySnapshotController implements ApplicationHistoryS @Override public Mono> create(@RequestBody ApplicationHistorySnapshotRequest request) { return sessionUserService.getVisitorId() - .delayUntil(visitor -> resourcePermissionService.checkResourcePermissionWithError(visitor, request.applicationId(), - ResourceAction.EDIT_APPLICATIONS)) - .delayUntil(visitorId -> applicationHistorySnapshotService.createHistorySnapshot(request.applicationId(), - request.dsl(), - request.context(), - visitorId) - ) - .flatMap(visitorId -> applicationService.updateLastEditedAt(request.applicationId(), Instant.now(), visitorId)) + .flatMap(visitorId -> editableApplication(visitorId, request.applicationId()) + .map(Application::getId) + // D-31: stored under the object id the check ran on, never under the key the caller sent + .delayUntil(applicationId -> applicationHistorySnapshotService.createHistorySnapshot(applicationId, + request.dsl(), request.context(), visitorId)) + .flatMap(applicationId -> applicationService.updateLastEditedAt(applicationId, Instant.now(), visitorId))) .map(ResponseView::success); } @@ -134,9 +134,12 @@ public Mono>> listAllHistorySnapshotBriefInfoAr public Mono> getHistorySnapshotDsl(@PathVariable String applicationId, @PathVariable String snapshotId) { return sessionUserService.getVisitorId() - .delayUntil(visitor -> resourcePermissionService.checkResourcePermissionWithError(visitor, applicationId, - ResourceAction.EDIT_APPLICATIONS)) - .flatMap(__ -> applicationHistorySnapshotService.getHistorySnapshotDetail(snapshotId)) + .flatMap(visitor -> editableApplication(visitor, applicationId)) + // D-31: served only through the app it was saved for + .flatMap(application -> applicationHistorySnapshotService.getHistorySnapshotDetail(snapshotId) + .filter(snapshot -> savedFor(application, snapshot.getApplicationId(), + snapshot.getApplicationIdResolved(), snapshot.getCreatedAt())) + .switchIfEmpty(deferredError(INVALID_HISTORY_SNAPSHOT, "INVALID_HISTORY_SNAPSHOT", snapshotId))) .map(ApplicationHistorySnapshot::getDsl) .zipWhen(applicationService::getAllDependentModulesFromDsl) .flatMap(tuple -> { @@ -159,9 +162,12 @@ public Mono> getHistorySnapshotDsl(@PathVar public Mono> getHistorySnapshotDslArchived(@PathVariable String applicationId, @PathVariable String snapshotId) { return sessionUserService.getVisitorId() - .delayUntil(visitor -> resourcePermissionService.checkResourcePermissionWithError(visitor, applicationId, - ResourceAction.EDIT_APPLICATIONS)) - .flatMap(__ -> applicationHistorySnapshotService.getHistorySnapshotDetailArchived(snapshotId)) + .flatMap(visitor -> editableApplication(visitor, applicationId)) + // D-31: served only through the app it was saved for + .flatMap(application -> applicationHistorySnapshotService.getHistorySnapshotDetailArchived(snapshotId) + .filter(snapshot -> savedFor(application, snapshot.getApplicationId(), + snapshot.getApplicationIdResolved(), snapshot.getCreatedAt())) + .switchIfEmpty(deferredError(INVALID_HISTORY_SNAPSHOT, "INVALID_HISTORY_SNAPSHOT", snapshotId))) .map(ApplicationHistorySnapshotTS::getDsl) .zipWhen(applicationService::getAllDependentModulesFromDsl) .flatMap(tuple -> { @@ -179,4 +185,55 @@ public Mono> getHistorySnapshotDslArchived( }) .map(ResponseView::success); } + + /** + * The application {@code applicationKey} names (an object id, a gid or a slug), once {@code visitorId} is found to hold + * EDIT on it (D-31). The key is resolved ONCE, with {@link ApplicationService#findByIdWithoutDsl} (the lookup the EDIT + * check uses for the workspace; not {@link ApplicationService#findById}, which never reads a slug), and the check + * receives the resolved object id, so the check and what the caller does next (store a snapshot under that object id, + * or compare a stored one with it) concern the same application even when a slug moves meanwhile. A key that lookup + * refuses fails with its NO_RESOURCE_FOUND (INVALID_PARAMETER for null) before any check. + * Limits: the check looks the object id up again for the workspace, which names the same application as long as its + * document exists (no route deletes one). + */ + private Mono editableApplication(String visitorId, String applicationKey) { + return applicationService.findByIdWithoutDsl(applicationKey) + .delayUntil(application -> resourcePermissionService.checkResourcePermissionWithError(visitorId, + application.getId(), ResourceAction.EDIT_APPLICATIONS)); + } + + /** + * Whether a snapshot with this stored application id, marker and creation time was saved for {@code application} + * (D-31). The stored id must equal the application's object id: a gid or a slug, even the application's own, is + * refused, because a slug moves between applications and a hyphenated one can become another application's gid. + * Equality is enough when the snapshot carries the marker: the create route stored the object id it had resolved and + * checked. A snapshot without it was stored under whatever key its caller sent, and a slug shaped like an object id + * equals the id of an application created after it; such a snapshot is accepted only when the application was created + * STRICTLY before the snapshot, and refused when either creation time is missing. Strict, not {@code !isAfter}: a + * deliberate narrowing, not a claim that equal timestamps cannot occur in a legitimate flow (createdAt has no + * uniqueness or monotonicity guarantee); a legacy snapshot genuinely taken in the same timestamp tick as its own + * application's creation is refused by this rule, an accepted cost of closing the equal-timestamp collision case. + * A snapshot with the marker is unaffected, since its ownership is proven by the marker, not by time order. + * Limits (D-31 residual, narrowed by strict order, not eliminated): (1) a snapshot without the marker, stored under a + * lookup that asked for the slug first, through a slug equal to the object id of an application that already existed + * in the SAME OR A DIFFERENT workspace (a slug is checked against another application's slug only within the same + * workspace, never against another application's id, and the slug lookup itself has no workspace constraint), still + * passes; (2) both creation times are server wall-clock timestamps, not a monotonic sequence, so clock skew between + * the nodes that wrote each one could still admit a colliding application whose real creation came after the + * snapshot. The creation times are the servers' clocks at insert; a refused snapshot answers as an unknown snapshot + * id but not in the same time (its document was read); a snapshot saved under a gid or a slug is still listed + * through that key but no longer served; + * the modules the snapshot's DSL names are not checked. + */ + private static boolean savedFor(Application application, String storedApplicationId, Boolean applicationIdResolved, + Instant snapshotCreatedAt) { + if (!application.getId().equals(storedApplicationId)) { + return false; + } + if (Boolean.TRUE.equals(applicationIdResolved)) { + return true; + } + Instant applicationCreatedAt = application.getCreatedAt(); + return applicationCreatedAt != null && snapshotCreatedAt != null && applicationCreatedAt.isBefore(snapshotCreatedAt); + } } diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationRecordApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationRecordApiServiceImpl.java index f3e9f08b13..6b3661eb56 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationRecordApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/application/ApplicationRecordApiServiceImpl.java @@ -10,6 +10,7 @@ import org.lowcoder.domain.application.model.ApplicationCombineId; import org.lowcoder.domain.application.service.ApplicationRecordService; import org.lowcoder.domain.application.service.ApplicationService; +import org.lowcoder.domain.permission.service.ResourcePermissionService; import org.lowcoder.domain.user.service.UserService; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; @@ -18,7 +19,9 @@ import java.util.Map; import static org.lowcoder.api.util.ViewBuilder.multiBuild; +import static org.lowcoder.domain.permission.model.ResourceAction.EDIT_APPLICATIONS; import static org.lowcoder.sdk.exception.BizError.APPLICATION_AND_ORG_NOT_MATCH; +import static org.lowcoder.sdk.exception.BizError.NOT_AUTHORIZED; import static org.lowcoder.sdk.util.ExceptionUtils.ofError; @RequiredArgsConstructor @@ -31,6 +34,7 @@ public class ApplicationRecordApiServiceImpl implements ApplicationRecordApiServ private final SessionUserService sessionUserService; private final OrgDevChecker orgDevChecker; private final UserService userService; + private final ResourcePermissionService resourcePermissionService; @Override public Mono> getRecordDSLFromApplicationCombineId(ApplicationCombineId applicationCombineId) { @@ -52,8 +56,9 @@ public Mono delete(String id) { /** * The versions of an application of the visitor's organization; another organization's is APPLICATION_AND_ORG_NOT_MATCH, - * as for the record DSL and the delete (BF-012). Limit: like them, this checks the organization only, not a permission - * on the application itself. + * as for the record DSL and the delete (BF-012). Limit: unlike the record DSL (D-32), this still checks the + * organization only, not EDIT_APPLICATIONS on the application itself; the delete still checks the developer role and + * the organization only. */ @Override public Mono> getByApplicationId(String applicationId) { @@ -73,14 +78,25 @@ Mono checkApplicationRecordManagementPermission(String applicationRecordId .flatMap(applicationRecord -> applicationService.findById(applicationRecord.getApplicationId())))); } + /** + * Workspace match, then EDIT_APPLICATIONS on the record's own application (D-32); an empty visitor id is + * NOT_AUTHORIZED. + */ Mono checkApplicationRecordViewPermission(ApplicationCombineId applicationCombineId) { - return checkApplicationOfVisitorOrg(Mono.defer(() -> { + return Mono.defer(() -> { if (applicationCombineId.isUsingLiveRecord()) { return applicationService.findById(applicationCombineId.applicationId()); } return applicationRecordService.getById(applicationCombineId.applicationRecordId()) .flatMap(applicationRecord -> applicationService.findById(applicationRecord.getApplicationId())); - })); + }).flatMap(application -> checkApplicationOfVisitorOrg(Mono.just(application)) + .then(Mono.defer(() -> checkEditable(application)))); + } + + private Mono checkEditable(Application application) { + return sessionUserService.getVisitorId() + .switchIfEmpty(ofError(NOT_AUTHORIZED, "NOT_AUTHORIZED")) + .flatMap(visitorId -> resourcePermissionService.checkResourcePermissionWithError(visitorId, application.getId(), EDIT_APPLICATIONS)); } /** The application belongs to the visitor's current organization, else APPLICATION_AND_ORG_NOT_MATCH. */ diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/authentication/request/form/FormAuthRequest.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/authentication/request/form/FormAuthRequest.java index f9744202a4..1268d176fb 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/authentication/request/form/FormAuthRequest.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/authentication/request/form/FormAuthRequest.java @@ -12,6 +12,7 @@ import org.lowcoder.sdk.exception.BizError; import org.lowcoder.sdk.exception.BizException; import org.lowcoder.sdk.util.EmailUtils; +import org.lowcoder.sdk.util.PasswordRule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @@ -43,6 +44,11 @@ public Mono auth(AuthRequestContext authRequestContext) { if (!EmailUtils.looksLikeEmail(EmailUtils.normalize(context.getLoginId()))) { return ofError(BizError.INVALID_EMAIL_FORMAT, "INVALID_EMAIL_FORMAT"); } + // D-48: the client's password rule, before the duplicate lookup and before anything is stored. + // Sign-in (below) never applies it: existing weak passwords keep working. + if (!PasswordRule.isAcceptable(context.getPassword())) { + return ofError(BizError.INVALID_PASSWORD, "PASSWORD_TOO_WEAK"); + } // Passed AS SUPPLIED on purpose: findBySourceAndId probes the value given and // then its normalized form, so this now rejects JoHn@DoE.com when // john@doe.com already exists -- the duplicate that used to get through. diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/bundle/BundleApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/bundle/BundleApiServiceImpl.java index d9744b08a0..5c50ba0490 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/bundle/BundleApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/bundle/BundleApiServiceImpl.java @@ -42,7 +42,6 @@ import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; import java.util.*; @@ -94,7 +93,8 @@ public Mono create(CreateBundleRequest createBundleRequest) { return sessionUserService.getVisitorId() .flatMap(userId -> orgMemberService.getOrgMember(bundle.getOrganizationId(), userId)) .switchIfEmpty(deferredError(NOT_AUTHORIZED, "NOT_AUTHORIZED")) - .delayUntil(orgMember -> orgDevChecker.checkCurrentOrgDev()) + // developer of the target workspace, not of the current one (D-11, D-41) + .delayUntil(orgDevChecker::checkOrgDev) .delayUntil(orgMember -> checkBundleNameUnique(bundle.getName(), orgMember.getUserId())) .delayUntil(orgMember -> { String folderId = createBundleRequest.folderId(); @@ -361,11 +361,43 @@ private Mono checkAppAndBundlesManageable(String userId, String applicatio private Mono addAppToBundle(Bundle bundle, Application newapplication) { var map = bundle.getEditingBundleDSL(); if(map == null) map = new HashMap<>(); - ((List) map.computeIfAbsent("applications", k-> new ArrayList<>())).add(newapplication); + // no app editing DSL in bundle DSLs: their readers may not edit the app (D-42) + ((List) map.computeIfAbsent("applications", k-> new ArrayList<>())).add(withoutEditingDsl(newapplication)); bundle.setEditingBundleDSL(map); return bundleRepository.save(bundle); } + /** + * A detached copy of the application for a reader who may not edit it (D-42): every field the application stores, with an + * empty editing DSL. The copy is a new instance, so its memoized editingQueries and editingModules are computed from the + * empty map (empty sets), whatever the original has already computed; the original is not changed. The DSL is an empty map, + * not null: getEditingModules() of a null DSL throws, which would fail the answer's serialization. + * Limits: the fields are copied by name; a field added to Application later is missing from the copy (absent, not + * leaked) until it is added here. The flags and the type are read through their getters, so a stored null becomes + * false / APPLICATION in the copy (the JSON already shows those values). + */ + private static Application withoutEditingDsl(Application application) { + return Application.builder() + .id(application.getId()) + .createdAt(application.getCreatedAt()) + .updatedAt(application.getUpdatedAt()) + .createdBy(application.getCreatedBy()) + .modifiedBy(application.getModifiedBy()) + .gid(application.getGid()) + .slug(application.getSlug()) + .organizationId(application.getOrganizationId()) + .name(application.getName()) + .applicationType(application.getApplicationType()) + .applicationStatus(application.getApplicationStatus()) + .editingApplicationDSL(new HashMap<>()) + .publicToAll(application.isPublicToAll()) + .publicToMarketplace(application.isPublicToMarketplace()) + .agencyProfile(application.agencyProfile()) + .editingUserId(application.getEditingUserId()) + .lastEditedAt(application.getLastEditedAt()) + .build(); + } + /** * @param applicationId app id to add * @param toBundleId bundle id to add app to @@ -414,24 +446,36 @@ public Mono reorder(String bundleId, List elementIds) { /** * The elements of a bundle, with the checks of {@link #getEditingBundle} (BF-020): the visitor may read the bundle * (READ_BUNDLES, computed in the bundle's organization; the readable errors of - * {@link #checkPermissionWithReadableErrorMsg}) and the bundle is NORMAL (BAD_REQUEST otherwise). + * {@link #checkPermissionWithReadableErrorMsg}) and the bundle is NORMAL (BAD_REQUEST otherwise). Each element is the + * application as stored now (not the bundle DSL's copy), in position order; it carries its editing DSL only when the + * visitor may edit it (EDIT_APPLICATIONS, one single-id check per element, in sequence), otherwise it is a copy without + * it (D-42). Limits: an empty visitor id answers no elements; the stored copies in the bundle DSLs are not filtered here. * * @return flux of {@link BundleApplication} */ @Override public Flux getElements(String bundleId, @Nullable ApplicationType applicationType) { - return checkPermissionWithReadableErrorMsg(bundleId, READ_BUNDLES) - .then(bundleService.findById(bundleId)) - .flatMap(bundle -> checkBundleStatus(bundle, BundleStatus.NORMAL)) - .thenMany(biRelationService.getBySourceId(BiRelationBizType.BUNDLE_ELEMENT, bundleId)) - .sort((o1, o2) -> { - var pos1 = Integer.parseInt(o1.getExtParam1()); - var pos2 = Integer.parseInt(o2.getExtParam1()); - return pos1 - pos2; - }).map(bi -> applicationServiceImpl.findById(bi.getTargetId())) - .index() - .publishOn(Schedulers.boundedElastic()) - .map(tuple -> new BundleApplication(tuple.getT2().block(), tuple.getT1())); + return sessionUserService.getVisitorId() + .flatMapMany(visitorId -> checkPermissionWithReadableErrorMsg(bundleId, READ_BUNDLES) + .then(bundleService.findById(bundleId)) + .flatMap(bundle -> checkBundleStatus(bundle, BundleStatus.NORMAL)) + .thenMany(biRelationService.getBySourceId(BiRelationBizType.BUNDLE_ELEMENT, bundleId)) + .sort((o1, o2) -> { + var pos1 = Integer.parseInt(o1.getExtParam1()); + var pos2 = Integer.parseInt(o2.getExtParam1()); + return pos1 - pos2; + }) + .concatMap(bi -> applicationServiceImpl.findById(bi.getTargetId()) + .flatMap(application -> withDslOnlyForEditors(visitorId, bi.getTargetId(), application))) + .index() + .map(tuple -> new BundleApplication(tuple.getT2(), tuple.getT1()))); + } + + private Mono withDslOnlyForEditors(String visitorId, String applicationId, Application application) { + return resourcePermissionService.checkUserPermissionStatusOnResource(visitorId, applicationId, EDIT_APPLICATIONS) + .map(UserPermissionOnResourceStatus::hasPermission) + .defaultIfEmpty(false) + .map(editable -> editable ? application : withoutEditingDsl(application)); } @Override diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/datasource/DatasourceApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/datasource/DatasourceApiServiceImpl.java index fdd2324bea..f4ea20f77a 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/datasource/DatasourceApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/datasource/DatasourceApiServiceImpl.java @@ -82,7 +82,8 @@ public Mono create(Datasource datasource) { return sessionUserService.getVisitorId() .flatMap(userId -> orgMemberService.getOrgMember(datasource.getOrganizationId(), userId)) .switchIfEmpty(deferredError(NOT_AUTHORIZED, "NOT_AUTHORIZED")) - .delayUntil(orgMember -> orgDevChecker.checkCurrentOrgDev()) + // developer of the target workspace, not of the current one (D-11, D-41) + .delayUntil(orgDevChecker::checkOrgDev) .flatMap(orgMember -> datasourceService.create(datasource, orgMember.getUserId())) .delayUntil(jsDatasourceHelper::processDynamicQueryConfig); } diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/framework/security/SecurityConfig.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/framework/security/SecurityConfig.java index ec6788d947..b059e0a17a 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/framework/security/SecurityConfig.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/framework/security/SecurityConfig.java @@ -113,7 +113,6 @@ SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, ORGANIZATION_URL + "/*/datasourceTypes"), // datasource types ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, ORGANIZATION_URL + "/byuser/*"), ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, DATASOURCE_URL + "/jsDatasourcePlugins"), - ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, META_URL + "/"), ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, GITHUB_STAR), @@ -132,7 +131,9 @@ SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, NewUrl.FLOW_URL), ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, NewUrl.CONFIG_URL + "/deploymentId"), ServerWebExchangeMatchers.pathMatchers(HttpMethod.HEAD, NewUrl.STATE_URL + "/healthCheck"), - ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, NewUrl.PREFIX + "/status/**"), + // health only, for probes; metrics and prometheus require authentication (D-39) + ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, NewUrl.PREFIX + "/status/health"), + ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, NewUrl.PREFIX + "/status/health/**"), ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, NewUrl.APPLICATION_URL + "/*"), ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, NewUrl.APPLICATION_URL + "/*/view"), ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, NewUrl.APPLICATION_URL + "/*/view_marketplace"), @@ -149,7 +150,6 @@ SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, NewUrl.ORGANIZATION_URL + "/*/datasourceTypes"), // datasource types ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, NewUrl.ORGANIZATION_URL + "/byuser/*"), ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, NewUrl.DATASOURCE_URL + "/jsDatasourcePlugins"), - ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, NewUrl.META_URL + "/"), ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, NewUrl.NPM_REGISTRY + "/**"), ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/api/docs/**") ) @@ -179,39 +179,77 @@ SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { /** - * enable CORS + * CORS, resolved per request. CORS controls only whether the BROWSER exposes a cross-origin answer to the calling + * page's script (the {@code Access-Control-Allow-Credentials} response header); it never stops the browser from + * attaching the session cookie to the request in the first place (see the limit below). The single rule: + * {@code Access-Control-Allow-Credentials} is granted only to an origin matching a non-wildcard entry of + * {@code LOWCODER_CORS_DOMAINS} ({@code commonConfig.getSecurity().getAllCorsAllowedDomains()}); a wildcard + * sub-pattern entry such as {@code https://*.example.com} counts as listed (it is kept as written and matched by + * {@code CorsConfiguration#checkOrigin}), only a standalone {@code "*"} entry does not. An origin that is not + * listed still gets a 200 answer, with no {@code Access-Control-Allow-Credentials} (so a credentialed `fetch` + * from that origin cannot read the answer's body or headers), on a path this method used to grant "any origin, + * with credentials" unconditionally ({@code publicPaths}, the former {@code skipCheckCorsForAll} list), or on any + * path at all when the configured domains contain the literal entry {@code "*"}; otherwise it is refused (403), + * the same as for any other unlisted path today. + *

+ * Limit NOT closed by this method: CSRF stays off and the session cookie is {@code SameSite=None} on HTTPS + * regardless, so the cookie still reaches the server, with the server still acting on it, on a cross-site SIMPLE + * request (a plain HTML form submit, which triggers no CORS preflight and needs no credential grant to be SENT, + * only to have its ANSWER read) — e.g. {@code POST /api/users/password?password=...}. This method only withholds + * the answer from the calling page's own script; it was never a defense against the request itself being made + * with the cookie attached. */ private CorsConfigurationSource buildCorsConfigurationSource() { - CorsConfiguration skipCheckCorsForAll = skipCheckCorsForAll(); - CorsConfiguration skipCheckCorsForAllowListDomains = skipCheckCorsForAllowListDomains(); + UrlBasedCorsConfigurationSource publicPaths = buildPublicPathsSource(); + CorsConfiguration credentialedListed = credentialedListedOriginsConfiguration(); + CorsConfiguration anyOriginNoCredentials = anyOriginNoCredentialsConfiguration(); + boolean wildcardConfigured = commonConfig.getSecurity().getAllCorsAllowedDomains().contains("*"); + return exchange -> { + String origin = exchange.getRequest().getHeaders().getOrigin(); + if (origin == null) { + return null; + } + if (credentialedListed.checkOrigin(origin) != null) { + return credentialedListed; + } + boolean formerAnyOriginPath = publicPaths.getCorsConfiguration(exchange) != null; + return (formerAnyOriginPath || wildcardConfigured) ? anyOriginNoCredentials : credentialedListed; + }; + } + + /** + * Path matcher only: the configurations registered here are never returned to a caller (only checked for + * presence), they merely mark the paths that used to grant "any origin, with credentials" unconditionally. + */ + @Nonnull + private UrlBasedCorsConfigurationSource buildPublicPathsSource() { + CorsConfiguration marker = skipCheckCorsForAll(); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - source.registerCorsConfiguration(USER_URL + "/me", skipCheckCorsForAll); - source.registerCorsConfiguration(CONFIG_URL, skipCheckCorsForAll); - source.registerCorsConfiguration(GROUP_URL + "/list", skipCheckCorsForAll); - source.registerCorsConfiguration(QUERY_URL + "/execute", skipCheckCorsForAll); - source.registerCorsConfiguration(APPLICATION_URL + "/*", skipCheckCorsForAll); - source.registerCorsConfiguration(APPLICATION_URL + "/*/view", skipCheckCorsForAll); - source.registerCorsConfiguration(APPLICATION_URL + "/*/view_marketplace", skipCheckCorsForAll); - source.registerCorsConfiguration(APPLICATION_URL + "/*/marketplace-preview/image", skipCheckCorsForAll); - source.registerCorsConfiguration(APPLICATION_URL + "/marketplace-apps", skipCheckCorsForAll); - source.registerCorsConfiguration(GITHUB_STAR, skipCheckCorsForAll); - source.registerCorsConfiguration(ORGANIZATION_URL + "/*/datasourceTypes", skipCheckCorsForAll); - source.registerCorsConfiguration(DATASOURCE_URL + "/jsDatasourcePlugins", skipCheckCorsForAll); - - source.registerCorsConfiguration(NewUrl.USER_URL + "/me", skipCheckCorsForAll); - source.registerCorsConfiguration(NewUrl.CONFIG_URL, skipCheckCorsForAll); - source.registerCorsConfiguration(NewUrl.GROUP_URL + "/list", skipCheckCorsForAll); - source.registerCorsConfiguration(NewUrl.QUERY_URL + "/execute", skipCheckCorsForAll); - source.registerCorsConfiguration(NewUrl.APPLICATION_URL + "/*", skipCheckCorsForAll); - source.registerCorsConfiguration(NewUrl.APPLICATION_URL + "/*/view", skipCheckCorsForAll); - source.registerCorsConfiguration(NewUrl.APPLICATION_URL + "/*/view_marketplace", skipCheckCorsForAll); - source.registerCorsConfiguration(NewUrl.APPLICATION_URL + "/*/marketplace-preview/image", skipCheckCorsForAll); - source.registerCorsConfiguration(NewUrl.APPLICATION_URL + "/marketplace-apps", skipCheckCorsForAll); - source.registerCorsConfiguration(NewUrl.ORGANIZATION_URL + "/*/datasourceTypes", skipCheckCorsForAll); - source.registerCorsConfiguration(NewUrl.DATASOURCE_URL + "/jsDatasourcePlugins", skipCheckCorsForAll); - - source.registerCorsConfiguration("/**", skipCheckCorsForAllowListDomains); + source.registerCorsConfiguration(USER_URL + "/me", marker); + source.registerCorsConfiguration(CONFIG_URL, marker); + source.registerCorsConfiguration(GROUP_URL + "/list", marker); + source.registerCorsConfiguration(QUERY_URL + "/execute", marker); + source.registerCorsConfiguration(APPLICATION_URL + "/*", marker); + source.registerCorsConfiguration(APPLICATION_URL + "/*/view", marker); + source.registerCorsConfiguration(APPLICATION_URL + "/*/view_marketplace", marker); + source.registerCorsConfiguration(APPLICATION_URL + "/*/marketplace-preview/image", marker); + source.registerCorsConfiguration(APPLICATION_URL + "/marketplace-apps", marker); + source.registerCorsConfiguration(GITHUB_STAR, marker); + source.registerCorsConfiguration(ORGANIZATION_URL + "/*/datasourceTypes", marker); + source.registerCorsConfiguration(DATASOURCE_URL + "/jsDatasourcePlugins", marker); + + source.registerCorsConfiguration(NewUrl.USER_URL + "/me", marker); + source.registerCorsConfiguration(NewUrl.CONFIG_URL, marker); + source.registerCorsConfiguration(NewUrl.GROUP_URL + "/list", marker); + source.registerCorsConfiguration(NewUrl.QUERY_URL + "/execute", marker); + source.registerCorsConfiguration(NewUrl.APPLICATION_URL + "/*", marker); + source.registerCorsConfiguration(NewUrl.APPLICATION_URL + "/*/view", marker); + source.registerCorsConfiguration(NewUrl.APPLICATION_URL + "/*/view_marketplace", marker); + source.registerCorsConfiguration(NewUrl.APPLICATION_URL + "/*/marketplace-preview/image", marker); + source.registerCorsConfiguration(NewUrl.APPLICATION_URL + "/marketplace-apps", marker); + source.registerCorsConfiguration(NewUrl.ORGANIZATION_URL + "/*/datasourceTypes", marker); + source.registerCorsConfiguration(NewUrl.DATASOURCE_URL + "/jsDatasourcePlugins", marker); return source; } @@ -225,14 +263,29 @@ private CorsConfiguration skipCheckCorsForAll() { return skipForAllowlistDomains; } + /** The configured domains with the literal {@code "*"} entry removed; a wildcard sub-pattern entry is kept as written. */ @Nonnull - private CorsConfiguration skipCheckCorsForAllowListDomains() { - CorsConfiguration skipForAllowlistDomains = new CorsConfiguration(); - skipForAllowlistDomains.setAllowedOriginPatterns(commonConfig.getSecurity().getAllCorsAllowedDomains()); - skipForAllowlistDomains.setAllowedMethods(List.of("*")); - skipForAllowlistDomains.setAllowedHeaders(List.of("*")); - skipForAllowlistDomains.setAllowCredentials(true); - return skipForAllowlistDomains; + private CorsConfiguration credentialedListedOriginsConfiguration() { + List listedOrigins = commonConfig.getSecurity().getAllCorsAllowedDomains().stream() + .filter(domain -> !"*".equals(domain)) + .toList(); + CorsConfiguration credentialedListed = new CorsConfiguration(); + credentialedListed.setAllowedOriginPatterns(listedOrigins); + credentialedListed.setAllowedMethods(List.of("*")); + credentialedListed.setAllowedHeaders(List.of("*")); + credentialedListed.setAllowCredentials(true); + return credentialedListed; + } + + /** Any origin, no {@code Access-Control-Allow-Credentials}: the fallback for an unlisted origin. */ + @Nonnull + private CorsConfiguration anyOriginNoCredentialsConfiguration() { + CorsConfiguration anyOriginNoCredentials = new CorsConfiguration(); + anyOriginNoCredentials.setAllowedOriginPatterns(List.of("*")); + anyOriginNoCredentials.setAllowedMethods(List.of("*")); + anyOriginNoCredentials.setAllowedHeaders(List.of("*")); + anyOriginNoCredentials.setAllowCredentials(false); + return anyOriginNoCredentials; } @Bean diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/FolderApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/FolderApiServiceImpl.java index a743f5c493..b1a047b098 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/FolderApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/FolderApiServiceImpl.java @@ -22,6 +22,7 @@ import org.lowcoder.domain.organization.model.OrgMember; import org.lowcoder.domain.organization.model.Organization; import org.lowcoder.domain.organization.service.OrganizationService; +import org.lowcoder.domain.organization.service.OrgMemberService; import org.lowcoder.domain.permission.model.ResourceAction; import org.lowcoder.domain.permission.model.ResourcePermission; import org.lowcoder.domain.permission.model.ResourceRole; @@ -45,6 +46,7 @@ import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; import static org.lowcoder.infra.util.MonoUtils.emptyIfNull; import static org.lowcoder.sdk.exception.BizError.*; +import static org.lowcoder.sdk.util.ExceptionUtils.deferredError; import static org.lowcoder.sdk.util.ExceptionUtils.ofError; @RequiredArgsConstructor @@ -52,6 +54,7 @@ public class FolderApiServiceImpl implements FolderApiService { private static final String INVALID_PARAMETER_KEY = "INVALID_PARAMETER"; + private static final String NOT_AUTHORIZED_KEY = "NOT_AUTHORIZED"; private static final Comparator> DEFAULT_COMPARATOR = // compare by last view time reversed. @@ -82,6 +85,7 @@ public class FolderApiServiceImpl implements FolderApiService { private final UserService userService; private final OrganizationService organizationService; private final UserFolderInteractionService userFolderInteractionService; + private final OrgMemberService orgMemberService; /** * Creates a new folder in the visitor's organization. Its id and gid are always the server's: an id in the request body @@ -473,9 +477,31 @@ private Mono checkPermissionResource(String permissionId, String folderId) .then(); } + /** + * The permission list of a folder (its user and group rows, its creator id and its workspace's name), for a member of + * the folder's workspace in any role, whichever workspace is current (D-8: any signed-in user read any folder's list). + * A visitor who is not a member of that workspace, or no visitor, gets NOT_AUTHORIZED, and no permission row, user, + * group or workspace is read before the check passes. App and bundle create call this for the folder they create in, + * after checking that the visitor is a member of the folder's workspace, so they pass. Limits: the folder is looked up + * first and its lookup error passes through unchanged (an object id no folder has is NO_RESOURCE_FOUND from + * {@link FolderServiceImpl#findById}; the controller answers a gid no folder has with FOLDER_NOT_EXIST before this + * method runs, BF-158), so an outsider can still tell an existing folder from an unknown one; the rows are read by the + * id passed in, as before; the membership query runs for every caller, its timing is not equalized. + */ @Override public Mono getPermissions(String folderId) { + return folderService.findById(folderId) + .flatMap(folder -> requireMemberOfFolderOrg(folder) + .then(Mono.defer(() -> buildPermissionView(folderId, folder)))); + } + private Mono requireMemberOfFolderOrg(Folder folder) { + return sessionUserService.getVisitorId() + .flatMap(visitorId -> orgMemberService.getOrgMember(folder.getOrganizationId(), visitorId)) + .switchIfEmpty(deferredError(NOT_AUTHORIZED, NOT_AUTHORIZED_KEY)); + } + + private Mono buildPermissionView(String folderId, Folder folder) { Mono> folderPermissions = resourcePermissionService.getByResourceTypeAndResourceId(ResourceType.FOLDER, folderId).cache(); @@ -485,21 +511,18 @@ public Mono getPermissions(String folderId) { Mono> userPermissionPairsMono = folderPermissions .flatMap(permissionHelper::getUserPermissions); - return folderService.findById(folderId) - .flatMap(folder -> { - Mono orgMono = organizationService.getById(folder.getOrganizationId()); - return Mono.zip(groupPermissionPairsMono, userPermissionPairsMono, orgMono) - .map(tuple -> { - List groupPermissionPairs = tuple.getT1(); - List userPermissionPairs = tuple.getT2(); - Organization organization = tuple.getT3(); - return ApplicationPermissionView.builder() - .groupPermissions(groupPermissionPairs) - .userPermissions(userPermissionPairs) - .creatorId(folder.getCreatedBy()) - .orgName(organization.getName()) - .build(); - }); + Mono orgMono = organizationService.getById(folder.getOrganizationId()); + return Mono.zip(groupPermissionPairsMono, userPermissionPairsMono, orgMono) + .map(tuple -> { + List groupPermissionPairs = tuple.getT1(); + List userPermissionPairs = tuple.getT2(); + Organization organization = tuple.getT3(); + return ApplicationPermissionView.builder() + .groupPermissions(groupPermissionPairs) + .userPermissions(userPermissionPairs) + .creatorId(folder.getCreatedBy()) + .orgName(organization.getName()) + .build(); }); } diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/SessionUserService.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/SessionUserService.java index a96485eaef..0536cba62b 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/SessionUserService.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/SessionUserService.java @@ -1,6 +1,7 @@ package org.lowcoder.api.home; import io.jsonwebtoken.Claims; +import jakarta.annotation.Nullable; import org.lowcoder.domain.organization.model.OrgMember; import org.lowcoder.domain.user.model.User; import org.lowcoder.infra.annotation.NonEmptyMono; @@ -37,4 +38,12 @@ public interface SessionUserService { Mono tokenExist(String token); Mono getVisitorToken(); + + /** + * Ends every session whose token is stored on the user's connections, except {@code keepToken} (D-34). A null + * or blank {@code keepToken} keeps none. Limits: a session whose token is not in the stored list is not found + * (a login racing a password change can keep its session, or add a token that is never swept); API keys are + * untouched. + */ + Mono endSessionsOfUser(String userId, @Nullable String keepToken); } diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/SessionUserServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/SessionUserServiceImpl.java index d4aadefd8a..f9c4896b6e 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/SessionUserServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/home/SessionUserServiceImpl.java @@ -1,6 +1,7 @@ package org.lowcoder.api.home; import io.jsonwebtoken.Claims; +import jakarta.annotation.Nullable; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.lowcoder.api.usermanagement.UserApiService; @@ -10,20 +11,24 @@ import org.lowcoder.domain.user.model.UserState; import org.lowcoder.domain.user.service.UserService; import org.lowcoder.sdk.config.CommonConfig; +import org.lowcoder.sdk.exception.BizError; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.data.redis.core.ReactiveValueOperations; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.stereotype.Service; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.time.Duration; +import java.util.List; import java.util.Objects; import static org.lowcoder.sdk.constants.GlobalContext.CURRENT_ORG_MEMBER; import static org.lowcoder.sdk.constants.GlobalContext.VISITOR_TOKEN; import static org.lowcoder.sdk.exception.BizError.UNABLE_TO_FIND_VALID_ORG; import static org.lowcoder.sdk.util.ExceptionUtils.deferredError; +import static org.lowcoder.sdk.util.ExceptionUtils.ofError; import static org.lowcoder.sdk.util.JsonUtils.fromJsonQuietly; @Slf4j @@ -163,5 +168,46 @@ public Mono resolveSessionUserForJWT(Claims claims, String token) { public Mono tokenExist(String token) { return reactiveTemplate.hasKey(token); } + + /** One more attempt at a Redis delete that failed: a transient error should not leave a session alive. */ + private static final long SESSION_DELETE_RETRIES = 1; + + @Override + public Mono endSessionsOfUser(String userId, @Nullable String keepToken) { + return userService.findById(userId) + .map(user -> tokensToEnd(user, keepToken)) + .flatMapMany(Flux::fromIterable) + .concatMap(token -> endOneSession(userId, token) + .then(Mono.empty()) + .onErrorResume(error -> { + log.warn("D-34: a session of user {} could not be ended", userId, error); + return Mono.just(token); + })) + .collectList() + .filter(failed -> !failed.isEmpty()) + .flatMap(failed -> ofError(BizError.PASSWORD_CHANGED_SESSIONS_NOT_ENDED, + "PASSWORD_CHANGED_SESSIONS_NOT_ENDED", failed.size())) + .then(); + } + + /** The Redis delete ends the session; then the Mongo copy is removed. A missing key is not an error. */ + private Mono endOneSession(String userId, String token) { + return reactiveTemplate.opsForValue().delete(token) + .retry(SESSION_DELETE_RETRIES) + .then(Mono.defer(() -> userApiService.removeToken(userId, token)) + .onErrorResume(error -> { + log.warn("D-34: user {} still lists an ended session", userId, error); + return Mono.empty(); + })); + } + + private static List tokensToEnd(User user, @Nullable String keepToken) { + return user.getConnections().stream() + .flatMap(connection -> connection.getTokens().stream()) + .filter(StringUtils::isNotBlank) + .filter(token -> !token.equals(keepToken)) + .distinct() + .toList(); + } } diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/meta/MetaEndpoints.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/meta/MetaEndpoints.java index f3f1a527de..794def9438 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/meta/MetaEndpoints.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/meta/MetaEndpoints.java @@ -19,10 +19,11 @@ public interface MetaEndpoints /** * The meta views (id and name; for an application also title, description, category and icon, for a user also the * email) of every application, user, organization, folder, datasource, bundle, group and library query the request - * names by key. No permission is checked, and the route is open to anonymous callers unless it is listed in - * {@code common.security.forbiddenEndpoints} (NEW-105: kept as upstream designed, owner decision D4). + * names by key. No permission is checked. The route requires authentication (a session or an API key); an + * anonymous caller gets 401 (D-12). It can still be closed entirely through + * {@code common.security.forbiddenEndpoints}. *

- * Limits: a caller who knows a key can learn that entity's meta view; the eight lookups are joined, so one failing + * Limits: any signed-in caller who knows a key, in any workspace, can learn that entity's meta view; the eight lookups are joined, so one failing * lookup fails the whole answer; blank keys are dropped from the organization, application and folder lists (NEW-81, * NEW-104, NEW-106), and the other lists pass them to their queries (a null bundle key matched no bundle, NEW-110). */ diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/npm/PrivateNpmRegistryController.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/npm/PrivateNpmRegistryController.java index 9e967605c7..339c7ed43d 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/npm/PrivateNpmRegistryController.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/npm/PrivateNpmRegistryController.java @@ -8,6 +8,8 @@ import org.lowcoder.domain.organization.model.Organization; import org.lowcoder.domain.organization.service.OrgMemberServiceImpl; import org.lowcoder.domain.organization.service.OrganizationService; +import org.lowcoder.domain.permission.model.ResourceAction; +import org.lowcoder.domain.permission.service.ResourcePermissionService; import org.lowcoder.infra.constant.NewUrl; import org.lowcoder.infra.js.NodeServerHelper; import org.lowcoder.sdk.webclient.WebClientBuildHelper; @@ -35,6 +37,7 @@ public class PrivateNpmRegistryController implements PrivateNpmRegistryEndpoint{ private static final String NPM_REGISTRY_ASSET = "npm/package"; private final OrgMemberServiceImpl orgMemberServiceImpl; private final ApplicationServiceImpl applicationServiceImpl; + private final ResourcePermissionService resourcePermissionService; @Override public Mono> getNpmPackageMeta(String applicationId, String path) { @@ -46,6 +49,16 @@ public Mono> getNpmPackageAsset(String applicationId, S return forwardToNodeService(applicationId, path, NPM_REGISTRY_ASSET); } + /** + * Forwards an npm registry/package request to node-service with the workspace's {@code npmRegistries} setting + * (registry URL and credential). For an {@code applicationId} other than {@code "none"}, the visitor must have + * READ on that app id (D-35): the check runs, and resolves the app's workspace as part of resolving the + * permission, before {@code applicationServiceImpl.findById}, {@code organizationService.getById} or + * {@code getOrgCommonSettings} are called, and before anything is forwarded to node-service. Clients send the + * OUTERMOST, actually READ-checked host app id for a component embedded in a module (never the module's own + * id): see {@code ExternalEditorContext.readCheckedApplicationId}. The {@code "none"} branch is unchanged: it + * uses the visitor's own current workspace and performs no permission check. + */ @NotNull private Mono> forwardToNodeService(String applicationId, String path, String prefix) { @@ -85,7 +98,9 @@ private Mono> forwardToNodeService(String applicationId })); } else{ - return applicationServiceImpl.findById(applicationId).flatMap(application -> organizationService.getById(application.getOrganizationId())).flatMap(orgMember -> organizationService.getOrgCommonSettings(orgMember.getId()).flatMap(organizationCommonSettings -> { + return sessionUserService.getVisitorId() + .flatMap(visitorId -> resourcePermissionService.checkResourcePermissionWithError(visitorId, applicationId, ResourceAction.READ_APPLICATIONS)) + .then(Mono.defer(() -> applicationServiceImpl.findById(applicationId).flatMap(application -> organizationService.getById(application.getOrganizationId())).flatMap(orgMember -> organizationService.getOrgCommonSettings(orgMember.getId()).flatMap(organizationCommonSettings -> { Map config = Map.of("npmRegistries", Objects.requireNonNullElse(organizationCommonSettings.get("npmRegistries"), new ArrayList<>(0)), "workspaceId", orgMember.getId()); return WebClientBuildHelper.builder() .systemProxy() @@ -101,7 +116,7 @@ private Mono> forwardToNodeService(String applicationId .headers(response.getHeaders()) .body(response.getBody()); }); - })); + })))); // closes: Mono.defer(..), the getOrgCommonSettings flatMap, the getById flatMap, the findById flatMap } } } diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/query/ApplicationQueryApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/query/ApplicationQueryApiServiceImpl.java index 7e8e88d029..05db4982d1 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/query/ApplicationQueryApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/query/ApplicationQueryApiServiceImpl.java @@ -45,6 +45,7 @@ import java.util.Optional; import java.util.stream.Collectors; +import static org.lowcoder.domain.permission.model.ResourceAction.EDIT_APPLICATIONS; import static org.lowcoder.domain.permission.model.ResourceAction.READ_APPLICATIONS; import static org.lowcoder.sdk.exception.BizError.DATASOURCE_AND_APP_ORG_NOT_MATCH; import static org.lowcoder.sdk.exception.BizError.INVALID_PARAMETER; @@ -79,9 +80,11 @@ public Mono executeApplicationQuery(ServerWebExchange exch } boolean viewMode = queryExecutionRequest.isViewMode(); String queryId = queryExecutionRequest.getQueryId(); + // a module run in another application's editor uses its published queries, which that editor shows (D-10) + boolean useLiveQueries = viewMode || hostAppIdOf(queryExecutionRequest.getPath(), appId) != null; Mono appMono = applicationService.findById(appId).cache(); Mono appQueryMono = appMono - .flatMap(app -> app.getQueryByViewModeAndQueryId(viewMode, queryId, applicationRecordService)) + .flatMap(app -> app.getQueryByViewModeAndQueryId(useLiveQueries, queryId, applicationRecordService)) .cache(); Mono baseQueryMono = appQueryMono.flatMap(this::getBaseQuery).cache(); @@ -143,13 +146,36 @@ private boolean shouldCheckDatasourceOrgMatch(Datasource datasource) { return !datasource.isSystemStatic() && !datasource.isLegacyQuickRestApi() && !datasource.isLegacyLowcoderApi(); } + /** + * Permission required before a query runs (D-10): + *

    + *
  • {@code viewMode: true} (any path): unchanged. Membership of {@code appId} in the root's live module set + * when a root is given (INVALID_PARAMETER otherwise, including a root equal to {@code appId}), then READ + * on the root.
  • + *
  • {@code viewMode: false}, own app (no host): EDIT_APPLICATIONS on {@code appId}.
  • + *
  • {@code viewMode: false}, module of a host H: (1) EDIT_APPLICATIONS on H; (2) {@code appId} is in H's + * module set built with {@code viewMode: false} (H's editing DSL for the first level, each module's live + * modules below), else INVALID_PARAMETER; (3) READ_APPLICATIONS on {@code appId} itself (the module) -- + * kept unchanged from today's edit-mode check, since a host editor can write any module id into the host's + * DSL with no check (the save does not validate modules), so step 2 alone is only a membership test.
  • + *
+ * Limits (unchanged by this method): a never-published app or module has its draft as its live version, so READ + * on it already runs that draft in view mode; view mode checks no right on the module itself, only membership + * and READ on the root; intermediate modules of a nested path are not checked. + */ protected Mono checkExecutePermission(String userId, String[] path, String appId, boolean viewMode) { if (viewMode) { return checkAppPathAndReturnRootAppId(path, appId, true) .flatMap(rootAppId -> resourcePermissionService.checkResourcePermissionWithError(userId, rootAppId, READ_APPLICATIONS)); } - return resourcePermissionService.checkResourcePermissionWithError(userId, appId, READ_APPLICATIONS); + String hostAppId = hostAppIdOf(path, appId); + if (hostAppId == null) { + return resourcePermissionService.checkResourcePermissionWithError(userId, appId, EDIT_APPLICATIONS); + } + return resourcePermissionService.checkResourcePermissionWithError(userId, hostAppId, EDIT_APPLICATIONS) + .then(Mono.defer(() -> checkAppPathAndReturnRootAppId(path, appId, false))) + .then(Mono.defer(() -> resourcePermissionService.checkResourcePermissionWithError(userId, appId, READ_APPLICATIONS))); } private Mono checkAppPathAndReturnRootAppId(String[] path, String appId, boolean viewMode) { @@ -165,17 +191,33 @@ private Mono checkAppPathAndReturnRootAppId(String[] path, String appId, return ofError(INVALID_PARAMETER, "INVALID_PARAMETER"); } return Mono.just(rootAppId); - }); + }) + // defensive: getAllDependentModulesFromApplicationId's collectList never completes empty today, so + // this guard is not observable, but a module lookup that did complete empty must not let a request + // pass the membership test by default. + .switchIfEmpty(deferredError(INVALID_PARAMETER, "INVALID_PARAMETER")); } @Nullable - private String getRootAppIdFromPath(String[] path) { + static String getRootAppIdFromPath(String[] path) { if (ArrayUtils.isEmpty(path)) { return null; } return path[0]; } + /** + * The host of a module query run inside another application (D-10): the first path entry when it is not blank and is + * not {@code appId}; {@code null} for the application's own query (no path, a blank first entry, or the application + * itself as first entry). The edit-mode permission check and the query selection both use it, so they always + * classify a request the same way. + */ + @Nullable + static String hostAppIdOf(@Nullable String[] path, String appId) { + String root = getRootAppIdFromPath(path); + return StringUtils.isBlank(root) || root.equals(appId) ? null : root; + } + private Mono getBaseQuery(ApplicationQuery applicationQuery) { if (applicationQuery.isUsingLibraryQuery()) { return getBaseQueryFromLibraryQuery(applicationQuery); diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/GroupApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/GroupApiServiceImpl.java index fab26bfcb2..e70d1c93ce 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/GroupApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/GroupApiServiceImpl.java @@ -360,6 +360,14 @@ public Mono update(String groupId, UpdateGroupRequest updateGroupReques return getGroupAndOrgMemberInfo(groupId) .filter(this::hasManagePermission) .switchIfEmpty(deferredError(BizError.NOT_AUTHORIZED, NOT_AUTHORIZED)) + // D-52: the name of a system group is fixed; the dynamic rule is not. The guard checks the field's + // presence, not its value, so a rename to the same name is refused too (the stored name of a system + // group is never shown, GroupView.java, so "same as before" cannot be compared against what the + // caller saw). + .filterWhen(ignored -> updateGroupRequest.getGroupName() == null + ? Mono.just(true) + : groupService.getById(groupId).map(Group::isNotSystemGroup)) + .switchIfEmpty(deferredError(BizError.UNSUPPORTED_OPERATION, "BAD_REQUEST")) .flatMap(it -> { Group updateGroup = new Group(); updateGroup.setId(groupId); diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/InvitationController.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/InvitationController.java index f0fe3643b2..f341152d65 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/InvitationController.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/InvitationController.java @@ -78,9 +78,10 @@ public Mono> sendInvitationEmails(InviteEmailRequest req) if (ArrayUtils.isEmpty(req.emails()) || StringUtils.isAnyBlank(req.emails())) { return ofError(INVALID_PARAMETER, "INVALID_PARAMETER", EMAILS_PARAMETER); } - return invitationApiService.create(req.orgId()).map(invitation -> - emailCommunicationService.sendInvitationEmails(req.emails(), - config.getLowcoderPublicUrl() + "/invite/" + invitation.getInviteCode(), + return invitationApiService.create(req.orgId()).map(invitation -> + emailCommunicationService.sendInvitationEmails(req.emails(), + // D-54 + CommonConfig.withoutTrailingSlashes(config.getLowcoderPublicUrl()) + "/invite/" + invitation.getInviteCode(), "You have been invited to join our platform. Click here to accept the invitation: %s")) .map(ResponseView::success); } diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/OrgApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/OrgApiServiceImpl.java index 273e4d58ff..cb56ec181a 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/OrgApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/OrgApiServiceImpl.java @@ -177,8 +177,8 @@ public Mono updateRoleForMember(String orgId, UpdateRoleRequest updateR /** * Sets the slug for an admin of the organization (ADMIN or SUPER_ADMIN, {@link #checkVisitorAdminRole}; NEW-102: any * signed-in user could). Limits: {@code orgId} is the object id, not converted from a gid or slug, as before, so a - * gid or slug answers NOT_AUTHORIZED; the slug rules are {@code OrganizationService.updateSlug}'s; the answer is the - * whole organization, as before. + * gid or slug answers NOT_AUTHORIZED; the slug rules are {@code OrganizationService.updateSlug}'s; the answer is + * the organization without its auth configs (D-14). */ @Override public Mono updateSlug(String orgId, String slug) { @@ -192,8 +192,7 @@ public Mono updateSlug(String orgId, String slug) { * organization role), read as {@code ConfigController.updateServerConfig} reads it. Anyone else gets * NOT_AUTHORIZED before this method reads the organization ({@code organizationService.getById} or {@code * getByIdWithDeleted}), whether it exists or not (NEW-102: any signed-in user read any organization). Limits: - * the answer is still the whole organization, its auth configs' {@code clientSecret} included (O22, an owner - * decision not made here); a deleted organization is read, with {@code withDeleted}, by its former members + * the answer carries no auth configs (D-14), but the full common settings; a deleted organization is read, with {@code withDeleted}, by its former members * until the asynchronous cleanup that follows its deletion ({@code OrgAndGroupEventListener.onOrgDeleted}) has * removed their memberships, and by all of them whose membership deletion did not happen (it is the listener's * first step; a later step failing for good does not undo it); that cleanup keeps every membership with the diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/OrgDevChecker.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/OrgDevChecker.java index 925f11a26e..1efc932c5f 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/OrgDevChecker.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/OrgDevChecker.java @@ -5,6 +5,7 @@ import org.lowcoder.api.home.SessionUserService; import org.lowcoder.domain.group.service.GroupMemberService; import org.lowcoder.domain.group.service.GroupService; +import org.lowcoder.domain.organization.model.OrgMember; import org.lowcoder.sdk.exception.BizError; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @@ -45,6 +46,24 @@ public Mono isCurrentOrgDev() { }); } + /** + * check whether the given membership (a workspace, not necessarily the current one) is an org admin or dev + * (D-11, D-41: app, bundle and data source creation check the TARGET workspace's membership, not the visitor's + * current one). + */ + public Mono checkOrgDev(OrgMember member) { + if (member.isAdmin() || member.isSuperAdmin()) { + return Mono.empty(); + } + return inDevGroup(member.getOrgId(), member.getUserId()) + .flatMap(result -> { + if (result) { + return Mono.empty(); + } + return ofError(BizError.NEED_DEV_TO_CREATE_RESOURCE, "NEED_DEV_TO_CREATE_RESOURCE"); + }); + } + @Nonnull private Mono inDevGroup(String orgId, String userId) { return groupService.getDevGroup(orgId) diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserApiServiceImpl.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserApiServiceImpl.java index 5b8b50a408..285840478f 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserApiServiceImpl.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserApiServiceImpl.java @@ -64,13 +64,16 @@ private Mono checkAdminPermissionAndUserBelongsToCurrentOrg(String userId) * SUPER_ADMIN member of every workspace), is refused with {@code UNSUPPORTED_OPERATION} unless the visitor is * resetting their OWN password -- the same rank rule {@code OrgApiServiceImpl#checkSuperAdminRoleUnchanged} * applies to a role change. Limits: an ADMIN may still reset another ADMIN's password (unchanged, by design); - * no session of the target is ended by a reset, fixed or not (tracked separately). + * after the reset every session of the target ends (D-34), except the caller's own when the caller resets its + * own password; when a session cannot be ended the call fails with PASSWORD_CHANGED_SESSIONS_NOT_ENDED after + * the password has changed, so the generated password is never shown and the admin resets again. */ @Override public Mono resetPassword(String userId) { return checkAdminPermissionAndUserBelongsToCurrentOrg(userId) .then(checkResetTargetBelowSuperAdmin(userId)) - .then(userService.resetPassword(userId)); + .then(userService.resetPassword(userId)) + .delayUntil(newPassword -> endSessionsAfterReset(userId)); } private Mono checkResetTargetBelowSuperAdmin(String userId) { @@ -96,6 +99,14 @@ private Mono checkResetTargetBelowSuperAdmin(String userId) { }); } + /** D-34: ends every session of the reset user; keeps the caller's own only when the caller reset its own password. */ + private Mono endSessionsAfterReset(String userId) { + return sessionUserService.getVisitorId() + .zipWith(sessionUserService.getVisitorToken()) + .flatMap(visitor -> sessionUserService.endSessionsOfUser(userId, + visitor.getT1().equals(userId) ? visitor.getT2() : null)); + } + @Override public Mono lostPassword(String userEmail) { return userService.lostPassword(userEmail); @@ -103,7 +114,9 @@ public Mono lostPassword(String userEmail) { @Override public Mono resetLostPassword(String userEmail, String token, String newPassword) { - return userService.resetLostPassword(userEmail, token, newPassword); + return userService.resetLostPassword(userEmail, token, newPassword) + .delayUntil(userId -> sessionUserService.endSessionsOfUser(userId, null)) + .map(userId -> true); } // ========================== TOKEN OPERATIONS START ========================== diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserController.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserController.java index bbc4e31e2e..cccd1d5d90 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserController.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/api/usermanagement/UserController.java @@ -28,6 +28,7 @@ import org.lowcoder.sdk.exception.BizError; import org.lowcoder.sdk.exception.BizException; import org.lowcoder.sdk.util.EmailUtils; +import org.lowcoder.sdk.util.PasswordRule; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.codec.multipart.Part; @@ -263,8 +264,11 @@ public Mono> updatePassword(@RequestBody UpdatePasswordReq if (StringUtils.isBlank(request.oldPassword()) || StringUtils.isBlank(request.newPassword())) { return ofError(BizError.INVALID_PARAMETER, "PASSWORD_EMPTY"); } + if (!PasswordRule.isAcceptable(request.newPassword())) { + return ofError(BizError.INVALID_PASSWORD, "PASSWORD_TOO_WEAK"); // D-48: before the old password is checked or anything is written + } return sessionUserService.getVisitorId() - .flatMap(user -> userService.updatePassword(user, request.oldPassword(), request.newPassword())) + .flatMap(visitorId -> userService.updatePassword(visitorId, request.oldPassword(), request.newPassword()).delayUntil(changed -> endOtherSessionsOf(visitorId))) // D-34 .map(ResponseView::success); } @@ -296,6 +300,9 @@ public Mono> resetLostPassword(@RequestBody ResetLostPassw || StringUtils.isBlank(request.newPassword())) { return ofError(BizError.INVALID_PARAMETER, "INVALID_PARAMETER"); } + if (!PasswordRule.isAcceptable(request.newPassword())) { + return ofError(BizError.INVALID_PASSWORD, "PASSWORD_TOO_WEAK"); // D-48: before the token is checked or used + } return userApiService.resetLostPassword(request.userEmail(), request.token(), request.newPassword()) .map(ResponseView::success); @@ -306,8 +313,11 @@ public Mono> setPassword(@RequestParam String password) { if (StringUtils.isBlank(password)) { return ofError(BizError.INVALID_PARAMETER, "PASSWORD_EMPTY"); } + if (!PasswordRule.isAcceptable(password)) { + return ofError(BizError.INVALID_PASSWORD, "PASSWORD_TOO_WEAK"); // D-48: before setPasswordIfAbsent, which decides and writes in one update + } return sessionUserService.getVisitorId() - .flatMap(user -> userService.setPassword(user, password)) + .flatMap(visitorId -> userService.setPasswordIfAbsent(visitorId, password)) // D-49: refuses an account that has a password .map(ResponseView::success); } @@ -386,4 +396,10 @@ private Mono checkVisitorManagesMember(String orgId, String userId) { return Mono.just(target); })); } + + /** D-34: ends every session of the user except the one making this request (none kept for a request without a session cookie). */ + private Mono endOtherSessionsOf(String userId) { + return sessionUserService.getVisitorToken() + .flatMap(token -> sessionUserService.endSessionsOfUser(userId, token)); + } } diff --git a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/runner/eventlistener/OrgAndGroupEventListener.java b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/runner/eventlistener/OrgAndGroupEventListener.java index f0593dc0ae..dd1cd5c1ad 100644 --- a/server/api-service/lowcoder-server/src/main/java/org/lowcoder/runner/eventlistener/OrgAndGroupEventListener.java +++ b/server/api-service/lowcoder-server/src/main/java/org/lowcoder/runner/eventlistener/OrgAndGroupEventListener.java @@ -9,9 +9,11 @@ import org.lowcoder.domain.application.model.Application; import org.lowcoder.domain.application.model.ApplicationStatus; import org.lowcoder.domain.application.service.ApplicationService; +import org.lowcoder.domain.bundle.service.BundleService; import org.lowcoder.domain.datasource.model.DatasourceStatus; import org.lowcoder.domain.datasource.repository.DatasourceRepository; import org.lowcoder.domain.datasource.service.DatasourceService; +import org.lowcoder.domain.folder.service.FolderService; import org.lowcoder.domain.group.event.GroupDeletedEvent; import org.lowcoder.domain.group.service.GroupMemberService; import org.lowcoder.domain.group.service.GroupService; @@ -65,6 +67,12 @@ public class OrgAndGroupEventListener { @Autowired private ResourcePermissionService resourcePermissionService; + @Autowired + private FolderService folderService; + + @Autowired + private BundleService bundleService; + @EventListener public void onOrgDeleted(OrgDeletedEvent event) { @@ -81,11 +89,14 @@ public void onOrgDeleted(OrgDeletedEvent event) { } /** - * Removes the user who left from the organization's groups and their application and datasource permissions there. The - * three cleanups run independently, each with its own retries (BF-015): one failing for good does not cancel the others, - * and its error is logged once all three have ended. + * Removes the user who left from the organization's groups and their application, data source, folder and bundle + * permissions there (D-59, D-60). The five cleanups run independently, each with its own retries (BF-015): one + * failing for good does not cancel the others, and its error is logged once all five have ended. *

- * Limits: a cleanup that fails after its retries is not attempted again later, so what it should have removed stays. + * Limits: a cleanup that fails after its retries is not attempted again later, so what it should have removed + * stays. This removes only the USER-holder permission rows this organization's resources carry for the leaving + * user; it does not revoke the access a creator (`createdBy`) keeps on the apps, bundles and folders it created, + * which is a separate, unrevoked mechanism (D-26, D-60 residual). */ @EventListener public void onUserLeaveOrg(OrgMemberLeftEvent orgMemberLeftEvent) { @@ -109,7 +120,20 @@ public void onUserLeaveOrg(OrgMemberLeftEvent orgMemberLeftEvent) { .retry(CLEANUP_RETRIES) .subscribeOn(orgEventScheduler); - Mono.whenDelayError(removeGroupMember, removeAppPermissions, removeDatasourcePermissions) + Mono> removeFolderPermissions = folderService.findByOrganizationId(orgId) + .flatMap(folder -> resourcePermissionService.removeUserFolderPermission(folder.getId(), userId)) + .collectList() + .retry(CLEANUP_RETRIES) + .subscribeOn(orgEventScheduler); + + Mono> removeBundlePermissions = bundleService.findByOrganizationId(orgId) + .flatMap(bundle -> resourcePermissionService.removeUserBundlePermission(bundle.getId(), userId)) + .collectList() + .retry(CLEANUP_RETRIES) + .subscribeOn(orgEventScheduler); + + Mono.whenDelayError(removeGroupMember, removeAppPermissions, removeDatasourcePermissions, + removeFolderPermissions, removeBundlePermissions) .doOnError(e -> log.error("fail to handle user {} leaving org {}", userId, orgId, e)) .subscribe(); } diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationApiServiceImplBranchesTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationApiServiceImplBranchesTest.java index 057cb3b4ac..3452d21509 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationApiServiceImplBranchesTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationApiServiceImplBranchesTest.java @@ -22,6 +22,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Stream; @@ -80,8 +81,10 @@ import org.lowcoder.sdk.plugin.common.sql.SqlBasedDatasourceConnectionConfig; import org.lowcoder.sdk.plugin.sqlcommand.GuiSqlCommand; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Flux; @@ -131,6 +134,8 @@ class ApplicationApiServiceImplBranchesTest { private static final String MSG_NO_EDIT = "NO_PERMISSION_TO_EDIT"; private static final String MSG_NO_VIEW = "NO_PERMISSION_TO_VIEW"; private static final String MSG_LACK_OF_DATASOURCE = "APPLICATION_EDIT_ERROR_LACK_OF_DATASOURCE_PERMISSIONS"; + private static final String MSG_NOT_AUTHORIZED = "NOT_AUTHORIZED"; + private static final String MSG_CANT_FIND_APPLICATION = "CANT_FIND_APPLICATION"; /** A SQL query with a key in the SQL, one in a {@code --} comment and one in a block comment (NEW-33). */ private static final String SQL_WITH_KEYS_IN_COMMENTS = "select {{a}} from t -- {{b}}\nwhere c = 1 /* {{c}} */"; private static final String KEY_OUTSIDE_COMMENTS = "{{a}}"; @@ -307,6 +312,34 @@ void create_blankOrganizationIdOrName_isRejectedBeforeAnyLookup(String label, St say("create: %s -> INVALID_PARAMETER %s, no lookup", label, expectedKey); } + /** + * D-11/D-41: the developer check runs on the TARGET workspace (the request's {@code orgId}), not the visitor's + * current one. An admin of a different, current workspace who is a plain member of the target still needs the + * real {@link org.lowcoder.api.usermanagement.OrgDevChecker#checkOrgDev} to refuse, so the call must carry the + * exact target membership; the current-workspace cache is never read in {@code create}. + */ + @Test + void create_developerOfTheCurrentWorkspace_butNotOfTheTargetWorkspace_isRefused() { + CreateApplicationRequest request = new CreateApplicationRequest(ORG_ID, null, "name", + ApplicationType.APPLICATION.getValue(), dsl(), null, null, null); + stubVisitor(); + OrgMember targetMember = new OrgMember(ORG_ID, VISITOR_ID, MemberRole.MEMBER, "normal", 0L); + when(orgMemberService.getOrgMember(ORG_ID, VISITOR_ID)).thenReturn(Mono.just(targetMember)); + when(orgDevChecker.checkOrgDev(targetMember)).thenReturn(Mono.error( + new BizException(BizError.NEED_DEV_TO_CREATE_RESOURCE, "NEED_DEV_TO_CREATE_RESOURCE"))); + lenient().when(sessionUserService.getVisitorOrgMemberCache()) + .thenReturn(Mono.just(new OrgMember("other-org", VISITOR_ID, MemberRole.ADMIN, "normal", 0L))); + + StepVerifier.create(service.create(request)) + .expectErrorSatisfies(error -> assertBizError(error, BizError.NEED_DEV_TO_CREATE_RESOURCE, "NEED_DEV_TO_CREATE_RESOURCE")) + .verify(); + + verify(orgDevChecker).checkOrgDev(targetMember); + verify(sessionUserService, never()).getVisitorOrgMemberCache(); + verifyNoInteractions(applicationService); + say("create: admin of the current workspace, plain member of the target -> refused, target checked"); + } + // ------------------------------------------------------------------ getPublishedApplication: request type gate static Stream requestTypeMatrix() { @@ -999,48 +1032,70 @@ private Application updateRequest(Map dsl, ApplicationStatus sta .organizationId(REQUEST_ORG_ID).build(); } - private void stubUpdate(Application stored) { + private void stubUpdate(Application stored, ResourceRole role) { stubVisitor(); stubViewDependencies(); lenient().when(applicationService.findByIdWithoutDsl(APP_ID)).thenReturn(Mono.just(stored)); lenient().when(resourcePermissionService.checkAndReturnMaxPermission(VISITOR_ID, APP_ID, ResourceAction.EDIT_APPLICATIONS)) - .thenReturn(Mono.just(permission(ResourceRole.EDITOR))); + .thenReturn(Mono.just(permission(role))); + lenient().when(resourcePermissionService.checkAndReturnMaxPermission(VISITOR_ID, APP_ID, ResourceAction.MANAGE_APPLICATIONS)) + .thenReturn(role == ResourceRole.OWNER ? Mono.just(permission(ResourceRole.OWNER)) + : Mono.error(new BizException(BizError.NOT_AUTHORIZED, MSG_NOT_AUTHORIZED))); lenient().when(applicationService.findById(APP_ID)).thenReturn(Mono.just(stored)); lenient().when(applicationService.updateById(eq(APP_ID), any(Application.class))).thenReturn(Mono.just(true)); } + private void stubUpdate(Application stored) { + stubUpdate(stored, ResourceRole.EDITOR); + } + static Stream updateStatusCases() { return Stream.of( - // updateStatus, stored status, refused, status written - Arguments.of(null, ApplicationStatus.NORMAL, false, null), - Arguments.of(false, ApplicationStatus.NORMAL, false, null), - Arguments.of(null, ApplicationStatus.RECYCLED, true, null), - Arguments.of(false, ApplicationStatus.RECYCLED, true, null), - Arguments.of(true, ApplicationStatus.RECYCLED, false, ApplicationStatus.NORMAL)); + // updateStatus, stored status, requested status, role, refused, refusal, refusal key, status written + Arguments.of(null, ApplicationStatus.NORMAL, ApplicationStatus.NORMAL, ResourceRole.EDITOR, false, null, null, null), + Arguments.of(false, ApplicationStatus.NORMAL, ApplicationStatus.NORMAL, ResourceRole.EDITOR, false, null, null, null), + Arguments.of(null, ApplicationStatus.RECYCLED, ApplicationStatus.NORMAL, ResourceRole.EDITOR, true, + BizError.UNSUPPORTED_OPERATION, MSG_BAD_REQUEST, null), + Arguments.of(false, ApplicationStatus.RECYCLED, ApplicationStatus.NORMAL, ResourceRole.EDITOR, true, + BizError.UNSUPPORTED_OPERATION, MSG_BAD_REQUEST, null), + Arguments.of(true, ApplicationStatus.RECYCLED, ApplicationStatus.NORMAL, ResourceRole.OWNER, false, null, null, + ApplicationStatus.NORMAL), + Arguments.of(true, ApplicationStatus.NORMAL, ApplicationStatus.RECYCLED, ResourceRole.EDITOR, true, + BizError.NOT_AUTHORIZED, MSG_NOT_AUTHORIZED, null), + Arguments.of(true, ApplicationStatus.RECYCLED, ApplicationStatus.NORMAL, ResourceRole.EDITOR, true, + BizError.NOT_AUTHORIZED, MSG_NOT_AUTHORIZED, null), + Arguments.of(true, ApplicationStatus.NORMAL, ApplicationStatus.RECYCLED, ResourceRole.OWNER, false, null, null, + ApplicationStatus.RECYCLED), + Arguments.of(null, ApplicationStatus.NORMAL, ApplicationStatus.RECYCLED, ResourceRole.EDITOR, false, null, null, null)); } /** - * Catches a recycled application edited by a plain update (UNSUPPORTED_OPERATION, nothing written) and a status - * written by accident: without {@code updateStatus} the stored status is checked to be NORMAL and the update - * carries no status; with {@code updateStatus = true} the check is skipped and the request's status is written. + * Catches a recycled application edited by a plain update (UNSUPPORTED_OPERATION, nothing written), a status + * written by accident, and an editor changing the status without the owner right: without {@code updateStatus} + * the stored status is checked to be NORMAL and the update carries no status (the body's status is ignored, row + * 9); with {@code updateStatus = true} the status check is skipped but the caller now needs MANAGE_APPLICATIONS, + * not just EDIT_APPLICATIONS (D-9), and only then is the request's status written. */ - @ParameterizedTest(name = "updateStatus={0} stored={1} refused={2} written status={3}") + @ParameterizedTest(name = "updateStatus={0} stored={1} requested={2} role={3} refused={4} written status={7}") @MethodSource("updateStatusCases") - void update_statusHandling(Boolean updateStatus, ApplicationStatus storedStatus, boolean refused, - ApplicationStatus writtenStatus) { + void update_statusHandling(Boolean updateStatus, ApplicationStatus storedStatus, ApplicationStatus requestedStatus, + ResourceRole role, boolean refused, BizError refusal, String refusalKey, ApplicationStatus writtenStatus) { Application stored = appBuilder(APP_ID, dsl()).applicationStatus(storedStatus).build(); - stubUpdate(stored); + stubUpdate(stored, role); ArgumentCaptor written = ArgumentCaptor.forClass(Application.class); lenient().when(applicationService.updateById(eq(APP_ID), written.capture())).thenReturn(Mono.just(true)); Map newDsl = dsl("ui", dsl()); - Mono result = service.update(APP_ID, updateRequest(newDsl, ApplicationStatus.NORMAL), updateStatus); + Mono result = service.update(APP_ID, updateRequest(newDsl, requestedStatus), updateStatus); if (refused) { StepVerifier.create(result) - .expectErrorSatisfies(error -> assertBizError(error, BizError.UNSUPPORTED_OPERATION, MSG_BAD_REQUEST)) + .expectErrorSatisfies(error -> assertBizError(error, refusal, refusalKey)) .verify(); verify(applicationService, never()).updateById(any(), any()); + if (Boolean.TRUE.equals(updateStatus)) { + verify(applicationService, never()).findById(APP_ID); + } } else { StepVerifier.create(result).expectNextCount(1).verifyComplete(); Application update = written.getValue(); @@ -1050,8 +1105,17 @@ void update_statusHandling(Boolean updateStatus, ApplicationStatus storedStatus, } if (Boolean.TRUE.equals(updateStatus)) { verify(applicationService, never()).findByIdWithoutDsl(APP_ID); + verify(resourcePermissionService).checkAndReturnMaxPermission(VISITOR_ID, APP_ID, ResourceAction.MANAGE_APPLICATIONS); + verify(resourcePermissionService, never()).checkAndReturnMaxPermission(VISITOR_ID, APP_ID, ResourceAction.EDIT_APPLICATIONS); + } else if (refused) { + // rows 3, 4: the stored-status check refuses before any permission check runs + verify(resourcePermissionService, never()).checkAndReturnMaxPermission(any(), any(), any()); + } else { + verify(resourcePermissionService).checkAndReturnMaxPermission(VISITOR_ID, APP_ID, ResourceAction.EDIT_APPLICATIONS); + verify(resourcePermissionService, never()).checkAndReturnMaxPermission(VISITOR_ID, APP_ID, ResourceAction.MANAGE_APPLICATIONS); } - say("update updateStatus=%s stored=%s -> refused=%s written status=%s", updateStatus, storedStatus, refused, writtenStatus); + say("update updateStatus=%s stored=%s requested=%s role=%s -> refused=%s written status=%s", + updateStatus, storedStatus, requestedStatus, role, refused, writtenStatus); } private Application requestWithDatasources(String... datasourceIds) { @@ -1129,6 +1193,69 @@ void update_datasourcePermissionMatrix(String label, String[] usedIds, Set allowed=%s", label, allowed); } + // ------------------------------------------------------------------ updateSlug + + private static final String NEW_SLUG = "the-new-slug"; + private final AtomicInteger slugWrites = new AtomicInteger(); + + private Mono counting(T value) { + return Mono.defer(() -> { + slugWrites.incrementAndGet(); + return Mono.just(value); + }); + } + + static Stream updateSlugCases() { + return Stream.of( + Arguments.of("editor (check passes)", (Supplier>) Mono::empty, null, null), + Arguments.of("no edit right (outsider, viewer)", + (Supplier>) () -> Mono.error(new BizException(BizError.NOT_AUTHORIZED, MSG_NOT_AUTHORIZED)), + BizError.NOT_AUTHORIZED, MSG_NOT_AUTHORIZED), + Arguments.of("id that names no application", + (Supplier>) () -> Mono.error(new BizException(BizError.NO_RESOURCE_FOUND, MSG_CANT_FIND_APPLICATION)), + BizError.NO_RESOURCE_FOUND, MSG_CANT_FIND_APPLICATION)); + } + + /** + * Catches the slug route writing before (or regardless of) checking the caller's right (D-37): the EDIT check must + * run, and nothing of the domain call may even be assembled, before it passes. A refused row proves two things + * together: {@code slugWrites} stays 0 (the domain {@code Mono} is never subscribed) and + * {@code verify(applicationService, never()).updateSlug(...)} holds (the mock method is never even called to build + * the chain). The allowed row additionally checks {@code InOrder}: the eager + * {@code .then(applicationService.updateSlug(...))} form would call the mock at assembly time, before the + * permission check is even subscribed, so {@code InOrder} would fail there even though the mock call itself is + * eventually recorded and the result is still correct. + */ + @ParameterizedTest(name = "{0}") + @MethodSource("updateSlugCases") + void updateSlug_needsEditBeforeTheDomainCallIsBuiltD37(String label, Supplier> check, BizError refusal, + String refusalKey) { + stubVisitor(); + Application written = app(dsl()); + lenient().when(applicationService.updateSlug(APP_ID, NEW_SLUG)).thenReturn(counting(written)); + when(resourcePermissionService.checkResourcePermissionWithError(VISITOR_ID, APP_ID, ResourceAction.EDIT_APPLICATIONS)) + .thenReturn(check.get()); + + Mono result = service.updateSlug(APP_ID, NEW_SLUG); + + if (refusal == null) { + StepVerifier.create(result).expectNext(written).verifyComplete(); + assertThat(slugWrites.get()).isEqualTo(1); + verify(applicationService).updateSlug(APP_ID, NEW_SLUG); + InOrder order = Mockito.inOrder(resourcePermissionService, applicationService); + order.verify(resourcePermissionService).checkResourcePermissionWithError(VISITOR_ID, APP_ID, ResourceAction.EDIT_APPLICATIONS); + order.verify(applicationService).updateSlug(APP_ID, NEW_SLUG); + } else { + StepVerifier.create(result) + .expectErrorSatisfies(error -> assertBizError(error, refusal, refusalKey)) + .verify(); + assertThat(slugWrites.get()).isEqualTo(0); + verify(applicationService, never()).updateSlug(any(), any()); + } + verify(resourcePermissionService).checkResourcePermissionWithError(VISITOR_ID, APP_ID, ResourceAction.EDIT_APPLICATIONS); + say("updateSlug: %s -> refusal=%s, domain subscriptions %d", label, refusal, slugWrites.get()); + } + // ------------------------------------------------------------------ grantPermission static Stream grantTargets() { diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationHistorySnapshotEndpointsTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationHistorySnapshotEndpointsTest.java index 7e1190e4e3..74177721c7 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationHistorySnapshotEndpointsTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationHistorySnapshotEndpointsTest.java @@ -18,6 +18,8 @@ import org.lowcoder.domain.permission.service.ResourcePermissionService; import org.lowcoder.domain.user.model.User; import org.lowcoder.domain.user.service.UserService; +import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; import org.mockito.Mockito; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -27,7 +29,12 @@ import java.util.List; import java.util.Map; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; class ApplicationHistorySnapshotEndpointsTest { @@ -39,12 +46,19 @@ class ApplicationHistorySnapshotEndpointsTest { private ApplicationService applicationService; private ApplicationRecordService applicationRecordService; private ApplicationHistorySnapshotController controller; + private Application pathApplication; private static final String TEST_APPLICATION_ID = "test-app-id"; + private static final String OTHER_APPLICATION_ID = "other-app-id"; + private static final String TEST_APPLICATION_GID = "test-app-gid"; + private static final String TEST_APPLICATION_SLUG = "test-app-slug"; private static final String TEST_SNAPSHOT_ID = "test-snapshot-id"; private static final String TEST_USER_ID = "test-user-id"; private static final String TEST_USER_NAME = "Test User"; private static final String TEST_USER_AVATAR = "https://example.com/avatar.jpg"; + private static final Instant SNAPSHOT_CREATED_AT = Instant.parse("2026-01-02T00:00:00Z"); + private static final Instant BEFORE_SNAPSHOT = SNAPSHOT_CREATED_AT.minusSeconds(60); + private static final Instant AFTER_SNAPSHOT = SNAPSHOT_CREATED_AT.plusSeconds(60); @BeforeEach void setUp() { @@ -60,6 +74,8 @@ void setUp() { when(sessionUserService.getVisitorId()).thenReturn(Mono.just(TEST_USER_ID)); when(resourcePermissionService.checkResourcePermissionWithError(anyString(), anyString(), any(ResourceAction.class))) .thenReturn(Mono.empty()); + pathApplication = createMockApplication(TEST_APPLICATION_ID); + when(applicationService.findByIdWithoutDsl(TEST_APPLICATION_ID)).thenReturn(Mono.just(pathApplication)); // Create controller with all required dependencies controller = new ApplicationHistorySnapshotController( @@ -168,7 +184,7 @@ void testCreate_serviceError() { // Verify the error is propagated StepVerifier.create(result) - .expectError(RuntimeException.class) + .expectErrorMessage("Service error") .verify(); } @@ -400,6 +416,9 @@ void testGetHistorySnapshotDsl_success() { return true; }) .verifyComplete(); + verify(applicationService, times(1)).findByIdWithoutDsl(anyString()); + verify(applicationService).findByIdWithoutDsl(TEST_APPLICATION_ID); + verify(resourcePermissionService).checkResourcePermissionWithError(TEST_USER_ID, TEST_APPLICATION_ID, ResourceAction.EDIT_APPLICATIONS); } @Test @@ -450,9 +469,9 @@ void testGetHistorySnapshotDsl_serviceError() { TEST_SNAPSHOT_ID ); - // Verify the error is propagated + // Verify the error is propagated (expectErrorMessage, not expectError: a wrong-typed refusal, e.g. BizException, must fail this test too) StepVerifier.create(result) - .expectError(RuntimeException.class) + .expectErrorMessage("Service error") .verify(); } @@ -488,6 +507,9 @@ void testGetHistorySnapshotDslArchived_success() { return true; }) .verifyComplete(); + verify(applicationService, times(1)).findByIdWithoutDsl(anyString()); + verify(applicationService).findByIdWithoutDsl(TEST_APPLICATION_ID); + verify(resourcePermissionService).checkResourcePermissionWithError(TEST_USER_ID, TEST_APPLICATION_ID, ResourceAction.EDIT_APPLICATIONS); } @Test @@ -501,9 +523,9 @@ void testGetHistorySnapshotDslArchived_serviceError() { TEST_SNAPSHOT_ID ); - // Verify the error is propagated + // Verify the error is propagated (expectErrorMessage, not expectError: a wrong-typed refusal, e.g. BizException, must fail this test too) StepVerifier.create(result) - .expectError(RuntimeException.class) + .expectErrorMessage("Service error") .verify(); } @@ -531,11 +553,319 @@ void testPermissionCheck_failure() { .verify(); } + // ---------------------------------------------------------------- D-31: served only through the app it was saved for + + @Test + void testGetHistorySnapshotDsl_snapshotOfAnotherApplication_isRefused() { + ApplicationHistorySnapshot snapshot = stubSnapshot(OTHER_APPLICATION_ID); + + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] snapshotOfAnotherApplication: path=" + TEST_APPLICATION_ID + + " stored=" + OTHER_APPLICATION_ID); + StepVerifier.create(result).expectErrorSatisfies(this::assertInvalidHistorySnapshot).verify(); + verify(resourcePermissionService).checkResourcePermissionWithError(TEST_USER_ID, TEST_APPLICATION_ID, ResourceAction.EDIT_APPLICATIONS); + verify(applicationService, times(1)).findByIdWithoutDsl(anyString()); + verify(applicationService, never()).findByIdWithoutDsl(OTHER_APPLICATION_ID); + verify(snapshot, never()).getDsl(); + verify(applicationService, never()).getAllDependentModulesFromDsl(any()); + verifyNoInteractions(applicationRecordService); + } + + @Test + void testGetHistorySnapshotDsl_snapshotStoredUnderGid_isRefused() { + when(pathApplication.getGid()).thenReturn(TEST_APPLICATION_GID); + when(pathApplication.getCreatedAt()).thenReturn(BEFORE_SNAPSHOT); + ApplicationHistorySnapshot snapshot = stubSnapshot(TEST_APPLICATION_GID); + when(snapshot.getApplicationIdResolved()).thenReturn(null); + when(applicationService.findByIdWithoutDsl(TEST_APPLICATION_GID)).thenReturn(Mono.just(pathApplication)); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] snapshotStoredUnderGid: path=" + TEST_APPLICATION_ID + + " stored=" + TEST_APPLICATION_GID + " marker=null createdAt(app)=" + BEFORE_SNAPSHOT + " createdAt(snapshot)=" + SNAPSHOT_CREATED_AT); + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result).expectErrorSatisfies(this::assertInvalidHistorySnapshot).verify(); + verify(applicationService, never()).findByIdWithoutDsl(TEST_APPLICATION_GID); + verify(snapshot, never()).getDsl(); + verify(applicationService, never()).getAllDependentModulesFromDsl(any()); + } + + @Test + void testGetHistorySnapshotDsl_snapshotStoredUnderSlug_isRefused() { + when(pathApplication.getSlug()).thenReturn(TEST_APPLICATION_SLUG); + when(pathApplication.getCreatedAt()).thenReturn(BEFORE_SNAPSHOT); + ApplicationHistorySnapshot snapshot = stubSnapshot(TEST_APPLICATION_SLUG); + when(snapshot.getApplicationIdResolved()).thenReturn(null); + when(applicationService.findByIdWithoutDsl(TEST_APPLICATION_SLUG)).thenReturn(Mono.just(pathApplication)); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] snapshotStoredUnderSlug: path=" + TEST_APPLICATION_ID + + " stored=" + TEST_APPLICATION_SLUG + " marker=null createdAt(app)=" + BEFORE_SNAPSHOT + " createdAt(snapshot)=" + SNAPSHOT_CREATED_AT); + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result).expectErrorSatisfies(this::assertInvalidHistorySnapshot).verify(); + verify(applicationService, never()).findByIdWithoutDsl(TEST_APPLICATION_SLUG); + verify(snapshot, never()).getDsl(); + verify(applicationService, never()).getAllDependentModulesFromDsl(any()); + } + + @Test + void testGetHistorySnapshotDsl_snapshotWithoutApplication_isRefused() { + ApplicationHistorySnapshot snapshot = stubSnapshot(null); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] snapshotWithoutApplication: path=" + TEST_APPLICATION_ID + " stored=null"); + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result).expectErrorSatisfies(this::assertInvalidHistorySnapshot).verify(); + verify(applicationService, times(1)).findByIdWithoutDsl(anyString()); + verify(applicationService, never()).findByIdWithoutDsl(isNull()); + verify(snapshot, never()).getDsl(); + verify(applicationService, never()).getAllDependentModulesFromDsl(any()); + } + + @Test + void testGetHistorySnapshotDsl_pathGivenAsSlug_isServed() { + when(applicationService.findByIdWithoutDsl(TEST_APPLICATION_SLUG)).thenReturn(Mono.just(pathApplication)); + stubSnapshot(TEST_APPLICATION_ID); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] pathGivenAsSlug: path=" + TEST_APPLICATION_SLUG + + " resolvedTo=" + TEST_APPLICATION_ID + " stored=" + TEST_APPLICATION_ID); + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_SLUG, TEST_SNAPSHOT_ID); + + StepVerifier.create(result) + .expectNextMatches(response -> response.isSuccess() && response.getData().getApplicationsDsl() != null + && response.getData().getModuleDSL() != null) + .verifyComplete(); + verify(resourcePermissionService).checkResourcePermissionWithError(TEST_USER_ID, TEST_APPLICATION_ID, ResourceAction.EDIT_APPLICATIONS); + verify(resourcePermissionService, never()).checkResourcePermissionWithError(anyString(), eq(TEST_APPLICATION_SLUG), any()); + verify(applicationService, times(1)).findByIdWithoutDsl(anyString()); + verify(applicationService, never()).findById(anyString()); + } + + @Test + void testGetHistorySnapshotDsl_pathApplicationNotFound_skipsCheckAndSnapshotRead() { + BizException notFound = new BizException(BizError.NO_RESOURCE_FOUND, "CANT_FIND_APPLICATION", TEST_APPLICATION_ID); + when(applicationService.findByIdWithoutDsl(TEST_APPLICATION_ID)).thenReturn(Mono.error(notFound)); + stubSnapshot(TEST_APPLICATION_ID); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] pathApplicationNotFound: path=" + TEST_APPLICATION_ID); + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result).expectErrorSatisfies(error -> assertThat(error).isSameAs(notFound)).verify(); + verify(resourcePermissionService, never()).checkResourcePermissionWithError(anyString(), anyString(), any()); + verify(applicationHistorySnapshotService, never()).getHistorySnapshotDetail(anyString()); + } + + @Test + void testGetHistorySnapshotDsl_editDenied_skipsSnapshotRead() { + BizException denied = new BizException(BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED"); + when(resourcePermissionService.checkResourcePermissionWithError(TEST_USER_ID, TEST_APPLICATION_ID, ResourceAction.EDIT_APPLICATIONS)) + .thenReturn(Mono.error(denied)); + stubSnapshot(TEST_APPLICATION_ID); + + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result).expectErrorSatisfies(error -> assertThat(error).isSameAs(denied)).verify(); + verify(applicationHistorySnapshotService, never()).getHistorySnapshotDetail(anyString()); + } + + @Test + void testGetHistorySnapshotDslArchived_snapshotOfAnotherApplication_isRefused() { + ApplicationHistorySnapshotTS snapshot = stubArchivedSnapshot(OTHER_APPLICATION_ID); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] archived snapshotOfAnotherApplication: path=" + TEST_APPLICATION_ID + + " stored=" + OTHER_APPLICATION_ID); + Mono> result = controller.getHistorySnapshotDslArchived(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result).expectErrorSatisfies(this::assertInvalidHistorySnapshot).verify(); + verify(resourcePermissionService).checkResourcePermissionWithError(TEST_USER_ID, TEST_APPLICATION_ID, ResourceAction.EDIT_APPLICATIONS); + verify(applicationService, times(1)).findByIdWithoutDsl(anyString()); + verify(applicationService, never()).findByIdWithoutDsl(OTHER_APPLICATION_ID); + verify(snapshot, never()).getDsl(); + verify(applicationService, never()).getAllDependentModulesFromDsl(any()); + verifyNoInteractions(applicationRecordService); + } + + @Test + void testGetHistorySnapshotDslArchived_pathGivenAsSlug_isServed() { + when(applicationService.findByIdWithoutDsl(TEST_APPLICATION_SLUG)).thenReturn(Mono.just(pathApplication)); + stubArchivedSnapshot(TEST_APPLICATION_ID); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] archived pathGivenAsSlug: path=" + TEST_APPLICATION_SLUG + + " resolvedTo=" + TEST_APPLICATION_ID + " stored=" + TEST_APPLICATION_ID); + Mono> result = controller.getHistorySnapshotDslArchived(TEST_APPLICATION_SLUG, TEST_SNAPSHOT_ID); + + StepVerifier.create(result) + .expectNextMatches(response -> response.isSuccess() && response.getData().getApplicationsDsl() != null + && response.getData().getModuleDSL() != null) + .verifyComplete(); + verify(resourcePermissionService).checkResourcePermissionWithError(TEST_USER_ID, TEST_APPLICATION_ID, ResourceAction.EDIT_APPLICATIONS); + verify(resourcePermissionService, never()).checkResourcePermissionWithError(anyString(), eq(TEST_APPLICATION_SLUG), any()); + verify(applicationService, times(1)).findByIdWithoutDsl(anyString()); + verify(applicationService, never()).findById(anyString()); + } + + @Test + void testGetHistorySnapshotDsl_legacySnapshotOfOlderApplication_isServed() { + stubSnapshot(TEST_APPLICATION_ID); + when(pathApplication.getCreatedAt()).thenReturn(BEFORE_SNAPSHOT); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] legacySnapshotOfOlderApplication: createdAt(app)=" + + BEFORE_SNAPSHOT + " createdAt(snapshot)=" + SNAPSHOT_CREATED_AT); + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result) + .expectNextMatches(response -> response.isSuccess() && response.getData().getApplicationsDsl() != null + && response.getData().getModuleDSL() != null) + .verifyComplete(); + } + + @Test + void testGetHistorySnapshotDsl_legacySnapshotOfNewerApplication_isRefused() { + ApplicationHistorySnapshot snapshot = stubSnapshot(TEST_APPLICATION_ID); + when(snapshot.getApplicationIdResolved()).thenReturn(null); + when(pathApplication.getCreatedAt()).thenReturn(AFTER_SNAPSHOT); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] legacySnapshotOfNewerApplication: createdAt(app)=" + + AFTER_SNAPSHOT + " createdAt(snapshot)=" + SNAPSHOT_CREATED_AT); + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result).expectErrorSatisfies(this::assertInvalidHistorySnapshot).verify(); + verify(snapshot, never()).getDsl(); + verify(applicationService, never()).getAllDependentModulesFromDsl(any()); + } + + @Test + void testGetHistorySnapshotDsl_legacySnapshotOfEquallyTimedApplication_isRefused() { + ApplicationHistorySnapshot snapshot = stubSnapshot(TEST_APPLICATION_ID); + when(snapshot.getApplicationIdResolved()).thenReturn(null); + when(pathApplication.getCreatedAt()).thenReturn(SNAPSHOT_CREATED_AT); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] legacySnapshotOfEquallyTimedApplication: createdAt(app)=" + + SNAPSHOT_CREATED_AT + " createdAt(snapshot)=" + SNAPSHOT_CREATED_AT); + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result).expectErrorSatisfies(this::assertInvalidHistorySnapshot).verify(); + verify(snapshot, never()).getDsl(); + verify(applicationService, never()).getAllDependentModulesFromDsl(any()); + } + + @Test + void testGetHistorySnapshotDsl_legacySnapshot_applicationWithoutCreationTime_isRefused() { + ApplicationHistorySnapshot snapshot = stubSnapshot(TEST_APPLICATION_ID); + when(snapshot.getApplicationIdResolved()).thenReturn(null); + // pathApplication.getCreatedAt() left unstubbed: null. + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] legacySnapshot_applicationWithoutCreationTime: createdAt(app)=null" + + " createdAt(snapshot)=" + SNAPSHOT_CREATED_AT); + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result).expectErrorSatisfies(this::assertInvalidHistorySnapshot).verify(); + verify(snapshot, never()).getDsl(); + } + + @Test + void testGetHistorySnapshotDsl_legacySnapshotWithoutCreationTime_isRefused() { + ApplicationHistorySnapshot snapshot = stubSnapshot(TEST_APPLICATION_ID); + when(snapshot.getApplicationIdResolved()).thenReturn(null); + when(snapshot.getCreatedAt()).thenReturn(null); + when(pathApplication.getCreatedAt()).thenReturn(BEFORE_SNAPSHOT); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] legacySnapshotWithoutCreationTime: createdAt(app)=" + + BEFORE_SNAPSHOT + " createdAt(snapshot)=null"); + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result).expectErrorSatisfies(this::assertInvalidHistorySnapshot).verify(); + verify(snapshot, never()).getDsl(); + } + + @Test + void testGetHistorySnapshotDsl_resolvedSnapshot_applicationWithoutCreationTime_isServed() { + stubSnapshot(TEST_APPLICATION_ID); + // marker stays TRUE (stubSnapshot/createMockApplicationHistorySnapshot default); pathApplication.getCreatedAt() left unstubbed: null. + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] resolvedSnapshot_applicationWithoutCreationTime: marker=TRUE createdAt(app)=null"); + Mono> result = controller.getHistorySnapshotDsl(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result) + .expectNextMatches(response -> response.isSuccess() && response.getData().getApplicationsDsl() != null + && response.getData().getModuleDSL() != null) + .verifyComplete(); + } + + @Test + void testGetHistorySnapshotDslArchived_legacySnapshotOfNewerApplication_isRefused() { + ApplicationHistorySnapshotTS snapshot = stubArchivedSnapshot(TEST_APPLICATION_ID); + when(snapshot.getApplicationIdResolved()).thenReturn(null); + when(pathApplication.getCreatedAt()).thenReturn(AFTER_SNAPSHOT); + + System.out.println("[ApplicationHistorySnapshotEndpointsTest] archived legacySnapshotOfNewerApplication: createdAt(app)=" + + AFTER_SNAPSHOT + " createdAt(snapshot)=" + SNAPSHOT_CREATED_AT); + Mono> result = controller.getHistorySnapshotDslArchived(TEST_APPLICATION_ID, TEST_SNAPSHOT_ID); + + StepVerifier.create(result).expectErrorSatisfies(this::assertInvalidHistorySnapshot).verify(); + verify(snapshot, never()).getDsl(); + } + + @Test + void testCreate_requestGivenAsSlug_storesObjectId() { + Map dsl = new HashMap<>(); + dsl.put("components", new HashMap<>()); + dsl.put("layout", new HashMap<>()); + Map context = new HashMap<>(); + context.put("action", "save"); + context.put("timestamp", Instant.now().toEpochMilli()); + ApplicationHistorySnapshotRequest request = new ApplicationHistorySnapshotRequest(TEST_APPLICATION_SLUG, dsl, context); + when(applicationService.findByIdWithoutDsl(TEST_APPLICATION_SLUG)).thenReturn(Mono.just(pathApplication)); + stubCreateSucceeds(); + + Mono> result = controller.create(request); + + StepVerifier.create(result) + .expectNextMatches(response -> response.isSuccess() && Boolean.TRUE.equals(response.getData())) + .verifyComplete(); + verify(applicationHistorySnapshotService).createHistorySnapshot(eq(TEST_APPLICATION_ID), eq(dsl), eq(context), eq(TEST_USER_ID)); + verify(applicationHistorySnapshotService, never()).createHistorySnapshot(eq(TEST_APPLICATION_SLUG), any(), any(), any()); + verify(resourcePermissionService).checkResourcePermissionWithError(TEST_USER_ID, TEST_APPLICATION_ID, ResourceAction.EDIT_APPLICATIONS); + verify(resourcePermissionService, never()).checkResourcePermissionWithError(anyString(), eq(TEST_APPLICATION_SLUG), any()); + verify(applicationService).updateLastEditedAt(eq(TEST_APPLICATION_ID), any(Instant.class), eq(TEST_USER_ID)); + verify(applicationService, times(1)).findByIdWithoutDsl(anyString()); + } + + @Test + void testCreate_applicationNotFound_storesNothing() { + BizException notFound = new BizException(BizError.NO_RESOURCE_FOUND, "CANT_FIND_APPLICATION", TEST_APPLICATION_ID); + when(applicationService.findByIdWithoutDsl(TEST_APPLICATION_ID)).thenReturn(Mono.error(notFound)); + stubCreateSucceeds(); + ApplicationHistorySnapshotRequest request = new ApplicationHistorySnapshotRequest(TEST_APPLICATION_ID, new HashMap<>(), new HashMap<>()); + + Mono> result = controller.create(request); + + StepVerifier.create(result).expectErrorSatisfies(error -> assertThat(error).isSameAs(notFound)).verify(); + verify(resourcePermissionService, never()).checkResourcePermissionWithError(anyString(), anyString(), any()); + verify(applicationHistorySnapshotService, never()).createHistorySnapshot(anyString(), any(), any(), any()); + verify(applicationService, never()).updateLastEditedAt(anyString(), any(), anyString()); + } + + @Test + void testCreate_editDenied_storesNothing() { + BizException denied = new BizException(BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED"); + when(resourcePermissionService.checkResourcePermissionWithError(TEST_USER_ID, TEST_APPLICATION_ID, ResourceAction.EDIT_APPLICATIONS)) + .thenReturn(Mono.error(denied)); + stubCreateSucceeds(); + ApplicationHistorySnapshotRequest request = new ApplicationHistorySnapshotRequest(TEST_APPLICATION_ID, new HashMap<>(), new HashMap<>()); + + Mono> result = controller.create(request); + + StepVerifier.create(result).expectErrorSatisfies(error -> assertThat(error).isSameAs(denied)).verify(); + verify(applicationHistorySnapshotService, never()).createHistorySnapshot(anyString(), any(), any(), any()); + } + // Helper methods to create mock objects private ApplicationHistorySnapshot createMockApplicationHistorySnapshot(String snapshotId, String userId) { ApplicationHistorySnapshot snapshot = Mockito.mock(ApplicationHistorySnapshot.class); when(snapshot.getId()).thenReturn(snapshotId); when(snapshot.getApplicationId()).thenReturn(TEST_APPLICATION_ID); + when(snapshot.getApplicationIdResolved()).thenReturn(Boolean.TRUE); when(snapshot.getCreatedBy()).thenReturn(userId); when(snapshot.getCreatedAt()).thenReturn(Instant.now()); when(snapshot.getDsl()).thenReturn(new HashMap<>()); @@ -547,6 +877,7 @@ private ApplicationHistorySnapshotTS createMockApplicationHistorySnapshotTS(Stri ApplicationHistorySnapshotTS snapshot = Mockito.mock(ApplicationHistorySnapshotTS.class); when(snapshot.getId()).thenReturn(snapshotId); when(snapshot.getApplicationId()).thenReturn(TEST_APPLICATION_ID); + when(snapshot.getApplicationIdResolved()).thenReturn(Boolean.TRUE); when(snapshot.getCreatedBy()).thenReturn(userId); when(snapshot.getCreatedAt()).thenReturn(Instant.now()); when(snapshot.getDsl()).thenReturn(new HashMap<>()); @@ -554,6 +885,43 @@ private ApplicationHistorySnapshotTS createMockApplicationHistorySnapshotTS(Stri return snapshot; } + /** Refused by {@code savedFor} (the create route's style of INVALID_HISTORY_SNAPSHOT, D-31): verbose and exact. */ + private void assertInvalidHistorySnapshot(Throwable error) { + System.out.println("[ApplicationHistorySnapshotEndpointsTest] refused: " + error); + assertThat(error).isInstanceOf(BizException.class); + BizException bizException = (BizException) error; + assertThat(bizException.getError()).isEqualTo(BizError.INVALID_HISTORY_SNAPSHOT); + assertThat(bizException.getMessageKey()).isEqualTo("INVALID_HISTORY_SNAPSHOT"); + assertThat(bizException.getArgs()).containsExactly(TEST_SNAPSHOT_ID); + } + + /** Stubs the whole read side of an active-snapshot DSL test, so no row leaves a {@code null}; marker stays TRUE. */ + private ApplicationHistorySnapshot stubSnapshot(String storedApplicationKey) { + ApplicationHistorySnapshot snapshot = createMockApplicationHistorySnapshot(TEST_SNAPSHOT_ID, TEST_USER_ID); + when(snapshot.getApplicationId()).thenReturn(storedApplicationKey); + when(snapshot.getCreatedAt()).thenReturn(SNAPSHOT_CREATED_AT); + when(applicationHistorySnapshotService.getHistorySnapshotDetail(TEST_SNAPSHOT_ID)).thenReturn(Mono.just(snapshot)); + when(applicationService.getAllDependentModulesFromDsl(any(Map.class))).thenReturn(Mono.just(List.of())); + return snapshot; + } + + /** As {@link #stubSnapshot}, for the archive route. */ + private ApplicationHistorySnapshotTS stubArchivedSnapshot(String storedApplicationKey) { + ApplicationHistorySnapshotTS snapshot = createMockApplicationHistorySnapshotTS(TEST_SNAPSHOT_ID, TEST_USER_ID); + when(snapshot.getApplicationId()).thenReturn(storedApplicationKey); + when(snapshot.getCreatedAt()).thenReturn(SNAPSHOT_CREATED_AT); + when(applicationHistorySnapshotService.getHistorySnapshotDetailArchived(TEST_SNAPSHOT_ID)).thenReturn(Mono.just(snapshot)); + when(applicationService.getAllDependentModulesFromDsl(any(Map.class))).thenReturn(Mono.just(List.of())); + return snapshot; + } + + /** Stubs the two writes of the create route for any key, so an unfixed controller is answered too. */ + private void stubCreateSucceeds() { + when(applicationHistorySnapshotService.createHistorySnapshot(anyString(), any(Map.class), any(Map.class), anyString())) + .thenReturn(Mono.just(true)); + when(applicationService.updateLastEditedAt(anyString(), any(Instant.class), anyString())).thenReturn(Mono.just(true)); + } + private User createMockUser(String userId, String userName, String avatarUrl) { User user = Mockito.mock(User.class); when(user.getId()).thenReturn(userId); diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationRecordApiServiceImplTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationRecordApiServiceImplTest.java index 7d4706e16e..e5ee0902a5 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationRecordApiServiceImplTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/application/ApplicationRecordApiServiceImplTest.java @@ -33,6 +33,7 @@ import org.lowcoder.domain.application.service.ApplicationService; import org.lowcoder.domain.organization.model.MemberRole; import org.lowcoder.domain.organization.model.OrgMember; +import org.lowcoder.domain.permission.service.ResourcePermissionService; import org.lowcoder.domain.user.model.User; import org.lowcoder.domain.user.service.UserService; import org.lowcoder.infra.constant.NewUrl; @@ -42,18 +43,25 @@ import reactor.core.publisher.Mono; +import static org.lowcoder.domain.permission.model.ResourceAction.EDIT_APPLICATIONS; +import static org.mockito.Mockito.verifyNoMoreInteractions; + /** * Tests of {@link ApplicationRecordApiServiceImpl} (the versions of an application) with Mockito. The mocks follow the * real services: {@code ApplicationServiceImpl.findById} and {@code ApplicationRecordServiceImpl.getById} fail when the * row is missing (they do not complete empty), so a missing record or application is an error here as it is in production. * *

BF-012 (was pinned under D-6 as plan §9 row "application version list readable for any application id by any - * signed-in user"): {@code getByApplicationId} (ApplicationRecordApiServiceImpl:59-67) now checks, like the record DSL and the + * signed-in user"): {@code getByApplicationId} (ApplicationRecordApiServiceImpl:64-72) now checks, like the record DSL and the * delete, that the application belongs to the visitor's organization * ({@link #getByApplicationId_otherOrgsApplication_failsWithApplicationAndOrgNotMatch_andReadsNoVersions}). It is reached from * {@code ApplicationRecordController.getByApplicationId} (:28-30) at {@code /api/application-records/listByApplicationId}, * which has no matcher of its own in SecurityConfig and falls under {@code .pathMatchers("/api/**")} / * {@code .authenticated()} (SecurityConfig:156-157), so any signed-in user reaches the check. + * + *

D-32: the record DSL ({@code getRecordDSLFromApplicationCombineId}) now also needs EDIT_APPLICATIONS on the + * record's own application, checked in {@code checkApplicationRecordViewPermission} after the workspace match; an + * empty visitor id is NOT_AUTHORIZED. {@code getByApplicationId} and {@code delete} are unchanged by D-32. */ class ApplicationRecordApiServiceImplTest { @@ -63,9 +71,11 @@ class ApplicationRecordApiServiceImplTest { private static final String OTHER_ORG = "org-2"; private static final String APP = "app-1"; private static final String OTHER_APP = "app-2"; + private static final String UNEDITABLE_APP = "app-3"; private static final String RECORD = "record-1"; private static final String LATEST = "latest"; private static final String EDITING = "editing"; + private static final String VISITOR = "user-1"; private static final Map LIVE_DSL = Map.of("src", "live"); private static final Map RECORD_DSL = Map.of("src", "record"); @@ -74,10 +84,12 @@ class ApplicationRecordApiServiceImplTest { private SessionUserService sessionUserService; private OrgDevChecker orgDevChecker; private UserService userService; + private ResourcePermissionService resourcePermissionService; private ApplicationRecordApiServiceImpl service; private final AtomicInteger dslSubscriptions = new AtomicInteger(); private final AtomicInteger deletions = new AtomicInteger(); + private final AtomicInteger recordReads = new AtomicInteger(); @BeforeEach void setUp() { @@ -86,13 +98,15 @@ void setUp() { sessionUserService = mock(SessionUserService.class); orgDevChecker = mock(OrgDevChecker.class); userService = mock(UserService.class); + resourcePermissionService = mock(ResourcePermissionService.class); service = new ApplicationRecordApiServiceImpl(applicationService, recordService, mock(ApplicationApiServiceImpl.class), - sessionUserService, orgDevChecker, userService); + sessionUserService, orgDevChecker, userService, resourcePermissionService); when(sessionUserService.getVisitorOrgMemberCache()).thenReturn(Mono.just(member(ORG))); when(orgDevChecker.checkCurrentOrgDev()).thenReturn(Mono.empty()); when(recordService.deleteById(anyString())).thenReturn(Mono.fromRunnable(deletions::incrementAndGet)); dslSubscriptions.set(0); deletions.set(0); + recordReads.set(0); } // ---------------------------------------------------------------- fixtures @@ -118,6 +132,14 @@ private void recordExists(String id, String applicationId) { when(recordService.getById(id)).thenReturn(Mono.just(version(id, applicationId, "creator", 1L))); } + /** Like {@link #recordExists}, but counts every subscription so a test can prove how many times the record was read. */ + private void countedRecord(String id, String applicationId) { + when(recordService.getById(id)).thenReturn(Mono.defer(() -> { + recordReads.incrementAndGet(); + return Mono.just(version(id, applicationId, "creator", 1L)); + })); + } + private void liveDsl(String applicationId) { when(applicationService.getLiveDSLByApplicationId(applicationId)) .thenReturn(Mono.defer(() -> { @@ -126,6 +148,19 @@ private void liveDsl(String applicationId) { })); } + /** The visitor may EDIT_APPLICATIONS on {@code appId}: stubs the visitor id and the exact-argument permission check. */ + private void visitorMayEdit(String appId) { + when(sessionUserService.getVisitorId()).thenReturn(Mono.just(VISITOR)); + when(resourcePermissionService.checkResourcePermissionWithError(VISITOR, appId, EDIT_APPLICATIONS)).thenReturn(Mono.empty()); + } + + /** The visitor may NOT EDIT_APPLICATIONS on {@code appId}: stubs the visitor id and the exact-argument permission check. */ + private void visitorMayNotEdit(String appId) { + when(sessionUserService.getVisitorId()).thenReturn(Mono.just(VISITOR)); + when(resourcePermissionService.checkResourcePermissionWithError(VISITOR, appId, EDIT_APPLICATIONS)) + .thenReturn(Mono.error(new BizException(BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED"))); + } + private static BizException failure(Mono mono) { Throwable error = mono.then().materialize().block(WAIT).getThrowable(); assertThat(error).as("the Mono must fail with a BizException").isInstanceOf(BizException.class); @@ -141,15 +176,33 @@ private static void assertCode(BizException error, BizError expected) { /** Catches the live branch reading a stored record, or the DSL being read for another application. */ @Test - void getDsl_liveRecord_returnsTheLiveDsl_afterTheOrgCheck() { + void getDsl_liveRecord_returnsTheLiveDsl_afterTheOrgAndEditChecks() { applicationExists(APP, ORG); liveDsl(APP); + visitorMayEdit(APP); Map dsl = service.getRecordDSLFromApplicationCombineId(new ApplicationCombineId(APP, LATEST)).block(WAIT); assertThat(dsl).isEqualTo(LIVE_DSL); verify(applicationService).findById(APP); verify(recordService, never()).getById(any()); + assertThat(dslSubscriptions).hasValue(1); + verify(resourcePermissionService).checkResourcePermissionWithError(VISITOR, APP, EDIT_APPLICATIONS); + verifyNoMoreInteractions(resourcePermissionService); + } + + /** Catches a workspace member without EDIT on the application reaching the DSL (D-32): the DSL must not be read. */ + @Test + void getDsl_liveRecord_sameOrgWithoutEdit_failsNotAuthorized_andNeverReadsTheLiveDsl() { + applicationExists(APP, ORG); + liveDsl(APP); + visitorMayNotEdit(APP); + + BizException error = failure(service.getRecordDSLFromApplicationCombineId(new ApplicationCombineId(APP, LATEST))); + + assertCode(error, BizError.NOT_AUTHORIZED); + assertThat(dslSubscriptions).hasValue(0); + verify(applicationService, never()).getLiveDSLByApplicationId(any()); } /** Catches the org check being skipped or inverted for the live branch: the DSL must not even be asked for. */ @@ -162,19 +215,38 @@ void getDsl_liveRecord_otherOrg_failsWithApplicationAndOrgNotMatch_andNeverReads assertCode(error, BizError.APPLICATION_AND_ORG_NOT_MATCH); assertThat(dslSubscriptions).hasValue(0); + verifyNoInteractions(resourcePermissionService); + verify(sessionUserService, never()).getVisitorId(); } /** Catches the named branch returning the live DSL, or checking the org against the wrong application. */ @Test void getDsl_namedRecord_returnsTheRecordsDsl_checkedOnTheRecordsApplication() { - recordExists(RECORD, APP); + countedRecord(RECORD, APP); applicationExists(APP, ORG); + visitorMayEdit(APP); Map dsl = service.getRecordDSLFromApplicationCombineId(new ApplicationCombineId(APP, RECORD)).block(WAIT); assertThat(dsl).isEqualTo(RECORD_DSL); verify(applicationService).findById(APP); verify(applicationService, never()).getLiveDSLByApplicationId(any()); + assertThat(recordReads).hasValue(2); + verify(resourcePermissionService).checkResourcePermissionWithError(VISITOR, APP, EDIT_APPLICATIONS); + } + + /** Catches a workspace member without EDIT on the record's application reaching the named record's DSL (D-32). */ + @Test + void getDsl_namedRecord_sameOrgWithoutEdit_failsNotAuthorized_andNeverReadsTheRecordDsl() { + countedRecord(RECORD, APP); + applicationExists(APP, ORG); + visitorMayNotEdit(APP); + + BizException error = failure(service.getRecordDSLFromApplicationCombineId(new ApplicationCombineId(APP, RECORD))); + + assertCode(error, BizError.NOT_AUTHORIZED); + assertThat(recordReads).hasValue(1); + verify(recordService, org.mockito.Mockito.times(1)).getById(RECORD); } /** @@ -188,15 +260,56 @@ void getDsl_namedRecord_theRequestedApplicationIdIsIgnored_theRecordsApplication recordExists(RECORD, APP); applicationExists(APP, ORG); applicationExists(OTHER_APP, OTHER_ORG); + visitorMayEdit(APP); Map dsl = service.getRecordDSLFromApplicationCombineId(new ApplicationCombineId(OTHER_APP, RECORD)).block(WAIT); System.out.println(TAG + "record of the caller's org, requested id of another org -> " + dsl); assertThat(dsl).isEqualTo(RECORD_DSL); verify(applicationService, never()).findById(OTHER_APP); + verify(resourcePermissionService, never()).checkResourcePermissionWithError(VISITOR, OTHER_APP, EDIT_APPLICATIONS); recordExists("record-2", OTHER_APP); BizException error = failure(service.getRecordDSLFromApplicationCombineId(new ApplicationCombineId(APP, "record-2"))); assertCode(error, BizError.APPLICATION_AND_ORG_NOT_MATCH); + verify(resourcePermissionService, never()).checkResourcePermissionWithError(VISITOR, OTHER_APP, EDIT_APPLICATIONS); + } + + /** D-32: the EDIT check follows the record's own application, never the requested one, in both directions. */ + @Test + void getDsl_namedRecord_editPermissionFollowsTheRecordsApplication_notTheRequestedOne() { + applicationExists(APP, ORG); + applicationExists(UNEDITABLE_APP, ORG); + visitorMayEdit(APP); + visitorMayNotEdit(UNEDITABLE_APP); + + countedRecord(RECORD, UNEDITABLE_APP); + BizException error = failure(service.getRecordDSLFromApplicationCombineId(new ApplicationCombineId(APP, RECORD))); + assertCode(error, BizError.NOT_AUTHORIZED); + assertThat(recordReads).as("the record of the uneditable app is read once, for the check only").hasValue(1); + verify(resourcePermissionService, org.mockito.Mockito.times(1)).checkResourcePermissionWithError(VISITOR, UNEDITABLE_APP, EDIT_APPLICATIONS); + verify(resourcePermissionService, never()).checkResourcePermissionWithError(VISITOR, APP, EDIT_APPLICATIONS); + + recordReads.set(0); + countedRecord("record-2", APP); + Map dsl = service.getRecordDSLFromApplicationCombineId(new ApplicationCombineId(UNEDITABLE_APP, "record-2")).block(WAIT); + assertThat(dsl).isEqualTo(RECORD_DSL); + verify(resourcePermissionService, org.mockito.Mockito.times(1)).checkResourcePermissionWithError(VISITOR, APP, EDIT_APPLICATIONS); + verify(resourcePermissionService, org.mockito.Mockito.times(1)) + .checkResourcePermissionWithError(VISITOR, UNEDITABLE_APP, EDIT_APPLICATIONS); + } + + /** D-32: an empty visitor id (no security context) is NOT_AUTHORIZED, and the DSL is never read. */ + @Test + void getDsl_noVisitorId_failsNotAuthorized_andNeverReadsTheDsl() { + applicationExists(APP, ORG); + liveDsl(APP); + when(sessionUserService.getVisitorId()).thenReturn(Mono.empty()); + + BizException error = failure(service.getRecordDSLFromApplicationCombineId(new ApplicationCombineId(APP, LATEST))); + + assertCode(error, BizError.NOT_AUTHORIZED); + assertThat(dslSubscriptions).hasValue(0); + verifyNoInteractions(resourcePermissionService); } /** Catches an unknown record being swallowed into an empty answer: the not-found error must reach the caller. */ @@ -208,6 +321,7 @@ void getDsl_unknownRecord_propagatesNotFound() { assertCode(error, BizError.APPLICATION_NOT_FOUND); verify(applicationService, never()).getLiveDSLByApplicationId(any()); + verifyNoInteractions(resourcePermissionService); } /** @@ -222,7 +336,8 @@ void getDsl_editingOrBlankRecordId_isNotSpecialCased_observedBehaviour() { ApplicationRecordRepository repository = mock(ApplicationRecordRepository.class); when(repository.findById(anyString())).thenReturn(Mono.empty()); ApplicationRecordApiServiceImpl withRealRecordService = new ApplicationRecordApiServiceImpl(applicationService, - new ApplicationRecordServiceImpl(repository), mock(ApplicationApiServiceImpl.class), sessionUserService, orgDevChecker, userService); + new ApplicationRecordServiceImpl(repository), mock(ApplicationApiServiceImpl.class), sessionUserService, orgDevChecker, + userService, resourcePermissionService); for (String id : new String[] {EDITING, ""}) { BizException error = failure(withRealRecordService.getRecordDSLFromApplicationCombineId(new ApplicationCombineId(APP, id))); @@ -230,6 +345,7 @@ void getDsl_editingOrBlankRecordId_isNotSpecialCased_observedBehaviour() { verify(repository).findById(id); } verify(applicationService, never()).getLiveDSLByApplicationId(any()); + verifyNoInteractions(resourcePermissionService); } // ---------------------------------------------------------------- delete @@ -260,6 +376,7 @@ void delete_otherOrg_failsWithApplicationAndOrgNotMatch_ownOrg_deletes() { service.delete(RECORD).block(WAIT); assertThat(deletions).as("own org's record is deleted").hasValue(1); verify(recordService, org.mockito.Mockito.atLeastOnce()).deleteById(RECORD); + verifyNoInteractions(resourcePermissionService); } /** Catches an unknown record turning into a successful no-op delete, or the deletion being attempted. */ @@ -308,6 +425,7 @@ void getByApplicationId_buildsViewsWithTheCreatorName_inTheServiceOrder() { assertThat(views).containsExactly( new ApplicationRecordMetaView("r2", APP, "tag-r2", "msg-r2", 2_000L, "Grace"), new ApplicationRecordMetaView("r1", APP, "tag-r1", "msg-r1", 1_000L, "Ada")); + verifyNoInteractions(resourcePermissionService); } /** @@ -401,8 +519,9 @@ void getByApplicationId_throughTheControllerAndTheRealService_refusesAnotherOrgs when(records.getByApplicationId("foreign-app-of-another-org")) .thenReturn(Mono.just(List.of(version("r1", "foreign-app-of-another-org", "u1", 1_000L)))); when(users.getByIds(anyCollection())).thenReturn(Mono.just(Map.of("u1", user("u1", "Ada")))); + ResourcePermissionService permissions = builder.mock(ResourcePermissionService.class); builder.singleton("applicationRecordApiServiceImpl", new ApplicationRecordApiServiceImpl(applications, records, - mock(ApplicationApiServiceImpl.class), sessions, builder.mock(OrgDevChecker.class), users)); + mock(ApplicationApiServiceImpl.class), sessions, builder.mock(OrgDevChecker.class), users, permissions)); builder.controller(ApplicationRecordController.class); try (ContractTestClient client = builder.build()) { @@ -414,6 +533,7 @@ void getByApplicationId_throughTheControllerAndTheRealService_refusesAnotherOrgs + new String(result.getResponseBodyContent(), java.nio.charset.StandardCharsets.UTF_8)); EndpointContract.assertBizError(result, BizError.APPLICATION_AND_ORG_NOT_MATCH, "APPLICATION_AND_ORG_NOT_MATCH"); verifyNoInteractions(users); + verifyNoInteractions(permissions); } } } diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/AuthenticationControllerTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/AuthenticationControllerTest.java index b8f3afb6bc..b7d87fd921 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/AuthenticationControllerTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/AuthenticationControllerTest.java @@ -55,7 +55,7 @@ public class AuthenticationControllerTest { @Test public void testFormRegisterSuccess() { String email = "test_register@ob.dev"; - String password = "lowcoder"; + String password = "lowcoder1"; String source = AuthSourceConstants.EMAIL; String authId = getEmailAuthConfigId(); @@ -101,7 +101,7 @@ public void testFormRegisterSuccess() { @Test public void testFormLoginSuccess() { String email = "test_login@ob.dev"; - String password = "lowcoder"; + String password = "lowcoder1"; String source = AuthSourceConstants.EMAIL; String authId = getEmailAuthConfigId(); @@ -155,7 +155,7 @@ public void testFormLoginSuccess() { public void testRegisterFailByLoginIdExist() { String email = "test_register_fail@ob.dev"; - String password = "lowcoder"; + String password = "lowcoder1"; String source = AuthSourceConstants.EMAIL; FormLoginRequest formLoginRequest = new FormLoginRequest(email, password, true, source, getEmailAuthConfigId()); @@ -207,7 +207,7 @@ private String getEmailAuthConfigId() { @Test public void logout() { String email = "test_logout@ob.dev"; - String password = "lowcoder"; + String password = "lowcoder1"; String source = AuthSourceConstants.EMAIL; FormLoginRequest registerRequest = new FormLoginRequest(email, password, true, source, getEmailAuthConfigId()); @@ -245,4 +245,43 @@ public void logout() { // ...and the session really is gone, so replaying the old value cannot authenticate assertEquals(Boolean.FALSE, sessionUserService.tokenExist(token).block()); } + + /** + * D-48: the password rule is confined to the register branch. A user whose password was stored + * before the rule existed -- {@code "lowcoder"}, which the rule now refuses on sign-up -- must still be + * able to sign in with it. + */ + @Test + public void testFormLoginWithAStoredWeakPasswordSucceeds() { + String email = "test_weak_login@ob.dev"; + String weakPassword = "lowcoder"; + String source = AuthSourceConstants.EMAIL; + + User seeded = userRepository.save(User.builder() + .name(email) + .email(email) + .password(encryptionService.encryptPassword(weakPassword)) + .state(UserState.ACTIVATED) + .isEnabled(true) + .connections(java.util.Set.of(Connection.builder() + .source(source) + .name(email) + .rawId(email) + .email(email) + .build())) + .build()) + .block(); + assertNotNull(seeded); + + FormLoginRequest formLoginRequest = new FormLoginRequest(email, weakPassword, false, source, getEmailAuthConfigId()); + MockServerHttpRequest request = MockServerHttpRequest.post("").build(); + MockServerWebExchange exchange = MockServerWebExchange.builder(request).build(); + + StepVerifier.create(authenticationController.formLogin(formLoginRequest, null, null, exchange)) + .assertNext(response -> assertTrue(response.isSuccess())) + .verifyComplete(); + + MultiValueMap cookies = exchange.getResponse().getCookies(); + assertTrue(cookies.containsKey(SESSION_COOKIE_NAME)); + } } diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/EmailBackfillEndToEndTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/EmailBackfillEndToEndTest.java index 6a48e72c9b..0f36acf4df 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/EmailBackfillEndToEndTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/EmailBackfillEndToEndTest.java @@ -169,9 +169,9 @@ public void passwordRecoveryResolvesAnAccountWhateverCaseIsTyped() { runBackfill(); - Boolean reset = userService.resetLostPassword("RECOVER.LEGACY@EXAMPLE.COM", token, "new-password") + String reset = userService.resetLostPassword("RECOVER.LEGACY@EXAMPLE.COM", token, "new-password") .block(); - assertEquals(Boolean.TRUE, reset, "recovery must resolve the account regardless of typed case"); + assertEquals(seeded.getId(), reset, "recovery must resolve the account regardless of typed case"); User after = userRepository.findById(seeded.getId()).block(); assertNotNull(after); @@ -214,7 +214,7 @@ public void passwordRecoveryIgnoresASoftDeletedAccount() { runBackfill(); - Boolean reset = userService.resetLostPassword(address, token, "new-password").block(); + String reset = userService.resetLostPassword(address, token, "new-password").block(); log.info("reset against a soft-deleted account returned {}", reset); assertNull(reset, "a deleted account must not be a password-reset target"); } @@ -249,7 +249,7 @@ public void anAccountInNoOrgIsStillConvergedByTheBackfill() { reloaded.setPasswordResetTokenExpiry(Instant.now().plus(1, ChronoUnit.HOURS)); userRepository.save(reloaded).block(); - assertEquals(Boolean.TRUE, userService.resetLostPassword(typed, token, "new-password").block(), + assertEquals(seeded.getId(), userService.resetLostPassword(typed, token, "new-password").block(), "resetting must work for an account that belongs to no workspace"); } diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/EmailNormalizationTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/EmailNormalizationTest.java index 84d349b284..c494487209 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/EmailNormalizationTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/EmailNormalizationTest.java @@ -57,7 +57,7 @@ public class EmailNormalizationTest { private static final String SOURCE = AuthSourceConstants.EMAIL; - private static final String PASSWORD = "lowcoder"; + private static final String PASSWORD = "lowcoder1"; @Autowired private AuthenticationController authenticationController; diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/GenericAuthenticateTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/GenericAuthenticateTest.java index 11dd197ee4..b5d8680caa 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/GenericAuthenticateTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/GenericAuthenticateTest.java @@ -153,7 +153,7 @@ public void testGoogleLoginSuccess(WireMockRuntimeInfo wmRuntimeInfo) { .verifyComplete(); String email = "test_register@ob.dev"; - String password = "lowcoder"; + String password = "lowcoder1"; String source1 = AuthSourceConstants.EMAIL; var authConfig1 = new EmailAuthConfig(AuthSourceConstants.EMAIL, true, true); diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/request/form/FormAuthRequestTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/request/form/FormAuthRequestTest.java index 06e5071571..e1af609005 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/request/form/FormAuthRequestTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/authentication/request/form/FormAuthRequestTest.java @@ -5,6 +5,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import org.junit.jupiter.api.BeforeEach; @@ -40,6 +41,8 @@ class FormAuthRequestTest { private static final String PASSWORD = "pw-1"; private static final String ENCODED = "encoded-pw"; private static final String INVALID_EMAIL_OR_PASSWORD = "INVALID_EMAIL_OR_PASSWORD"; + private static final String WEAK_PASSWORD = "a"; + private static final String ACCEPTABLE_PASSWORD = "Passw0rd-1"; @Mock private UserService userService; @Mock private EncryptionService encryptionService; @@ -54,7 +57,15 @@ void setUp() { } private static FormAuthRequestContext context(boolean register, AbstractAuthConfig authConfig) { - FormAuthRequestContext context = new FormAuthRequestContext(LOGIN_ID, PASSWORD, register, "org-1"); + return context(register, authConfig, PASSWORD); + } + + private static FormAuthRequestContext context(boolean register, AbstractAuthConfig authConfig, String password) { + return context(LOGIN_ID, register, authConfig, password); + } + + private static FormAuthRequestContext context(String loginId, boolean register, AbstractAuthConfig authConfig, String password) { + FormAuthRequestContext context = new FormAuthRequestContext(loginId, password, register, "org-1"); context.setAuthConfig(authConfig); return context; } @@ -64,9 +75,17 @@ private static void assertBizError(Throwable throwable, BizError expected) { assertThat(((BizException) throwable).getError()).isEqualTo(expected); } + private static void assertBizError(Throwable throwable, BizError expected, String messageKey) { + assertBizError(throwable, expected); + assertThat(((BizException) throwable).getMessageKey()).isEqualTo(messageKey); + } + // -------------------------------------------------------------------- login - /** Catches a login with the right password failing, or the user being built from something other than the login id. */ + /** + * Catches a login with the right password failing, or the user being built from something other than the + * login id. {@code pw-1} breaks the sign-up rule on purpose: sign-in never applies it (D-48). + */ @Test void login_rightPassword_returnsTheAuthUserOfTheLoginId() { when(userService.findBySourceAndId(AuthSourceConstants.EMAIL, LOGIN_ID)).thenReturn(Mono.just(User.builder().password(ENCODED).build())); @@ -140,6 +159,57 @@ void register_withANonEmailConfigOfTheEmailSource_isUnsupported() { .enableRegister(true).clientId("c").authType("GITHUB").build(), "not an EmailAuthConfig"); } + /** D-48: a weak password refuses registration before the duplicate-address lookup or any encryption call. */ + @Test + void register_weakPassword_failsPasswordTooWeakAndLooksNothingUp() { + EmailAuthConfig config = new EmailAuthConfig("cfg", true, true); + + StepVerifier.create(request.auth(context(true, config, WEAK_PASSWORD))) + .expectErrorSatisfies(e -> assertBizError(e, BizError.INVALID_PASSWORD, "PASSWORD_TOO_WEAK")) + .verify(); + verify(userService, never()).findBySourceAndId(anyString(), anyString()); + verifyNoInteractions(encryptionService); + System.out.println("[FormAuthRequestTest] register weak password -> INVALID_PASSWORD / PASSWORD_TOO_WEAK, no lookup, no encryption call"); + } + + /** D-48 ordering: a malformed address is refused before the weak-password check runs. */ + @Test + void register_weakPasswordAndMalformedAddress_failsInvalidEmailFormatFirst() { + EmailAuthConfig config = new EmailAuthConfig("cfg", true, true); + FormAuthRequestContext context = context("not-an-address", true, config, WEAK_PASSWORD); + + StepVerifier.create(request.auth(context)) + .expectErrorSatisfies(e -> assertBizError(e, BizError.INVALID_EMAIL_FORMAT, "INVALID_EMAIL_FORMAT")) + .verify(); + verify(userService, never()).findBySourceAndId(anyString(), anyString()); + System.out.println("[FormAuthRequestTest] register malformed address + weak password -> INVALID_EMAIL_FORMAT first"); + } + + /** D-48: a password that meets the rule is let through to the duplicate-address lookup. */ + @Test + void register_acceptablePassword_looksUpTheAddressAndAnswersTheAuthUser() { + EmailAuthConfig config = new EmailAuthConfig("cfg", true, true); + when(userService.findBySourceAndId(AuthSourceConstants.EMAIL, LOGIN_ID)).thenReturn(Mono.empty()); + + AuthUser authUser = request.auth(context(true, config, ACCEPTABLE_PASSWORD)).block(); + + assertThat(authUser.getUid()).isEqualTo(LOGIN_ID); + verify(userService).findBySourceAndId(AuthSourceConstants.EMAIL, LOGIN_ID); + System.out.println("[FormAuthRequestTest] register acceptable password -> looked up, authUser=" + authUser.getUid()); + } + + /** D-48 + the duplicate check: an acceptable password of an already-registered address still fails as a duplicate. */ + @Test + void register_acceptablePasswordOfARegisteredAddress_failsUserLoginIdExist() { + EmailAuthConfig config = new EmailAuthConfig("cfg", true, true); + when(userService.findBySourceAndId(AuthSourceConstants.EMAIL, LOGIN_ID)).thenReturn(Mono.just(User.builder().build())); + + StepVerifier.create(request.auth(context(true, config, ACCEPTABLE_PASSWORD))) + .expectErrorSatisfies(e -> assertBizError(e, BizError.USER_LOGIN_ID_EXIST, "USER_LOGIN_ID_EXIST")) + .verify(); + System.out.println("[FormAuthRequestTest] register acceptable password of a registered address -> USER_LOGIN_ID_EXIST"); + } + @Test void refresh_isNotSupported() { StepVerifier.create(request.refresh("any-refresh-token")).expectError(UnsupportedOperationException.class).verify(); diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/bundle/BundleApiServiceImplPermissionsTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/bundle/BundleApiServiceImplPermissionsTest.java index 8f75bfab10..d45bb6bc5f 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/bundle/BundleApiServiceImplPermissionsTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/bundle/BundleApiServiceImplPermissionsTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; @@ -9,6 +10,7 @@ import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -80,6 +82,7 @@ import org.lowcoder.sdk.config.CommonConfig; import org.lowcoder.sdk.exception.BizError; import org.lowcoder.sdk.exception.BizException; +import org.lowcoder.sdk.util.JsonUtils; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -538,7 +541,7 @@ private CreateBundleRequest createRequest(String name, String gid, String folder private void stubCreateFlow(Bundle created) { lenient().when(orgMemberService.getOrgMember(ORG, VISITOR)).thenReturn(Mono.just(member())); - lenient().when(orgDevChecker.checkCurrentOrgDev()).thenAnswer(invocation -> loggedVoid("dev")); + lenient().when(orgDevChecker.checkOrgDev(any())).thenAnswer(invocation -> loggedVoid("dev")); lenient().when(bundleService.findByUserId(VISITOR)).thenReturn(Flux.just(bundle)); lenient().when(bundleService.create(any(Bundle.class), eq(VISITOR))).thenAnswer(invocation -> logged("create", created)); lenient().when(folderApiService.checkFolderExist("folder-1")).thenAnswer(invocation -> logged("folderExist", new Folder())); @@ -588,7 +591,7 @@ void create_refusals_createNothing() { .expectErrorSatisfies(error -> assertBizError(error, BizError.BUNDLE_NAME_CONFLICT, "BUNDLE_NAME_CONFLICT")).verify(); BizException devDenied = new BizException(BizError.NEED_DEV_TO_CREATE_RESOURCE, "NEED_DEV_TO_CREATE_RESOURCE"); - when(orgDevChecker.checkCurrentOrgDev()).thenReturn(Mono.error(devDenied)); + when(orgDevChecker.checkOrgDev(any())).thenReturn(Mono.error(devDenied)); StepVerifier.create(service.create(createRequest("Fresh", null, "folder-1"))) .expectErrorSatisfies(error -> assertThat(error).isSameAs(devDenied)).verify(); @@ -596,6 +599,32 @@ void create_refusals_createNothing() { say("create refusals -> nothing created"); } + /** + * D-11/D-41: the developer check runs on the TARGET workspace (the request's {@code orgId}), not the visitor's + * current one. An admin of its own, current workspace who is a plain member of the target still needs the real + * {@link org.lowcoder.api.usermanagement.OrgDevChecker#checkOrgDev} to refuse, so the call must carry the target + * membership; the current-workspace cache is never even read in {@code create}. + */ + @Test + void create_developerOfTheCurrentWorkspace_butNotOfTheTargetWorkspace_isRefused() { + OrgMember targetMember = member(); + stubCreateFlow(createdBundle()); + when(orgMemberService.getOrgMember(ORG, VISITOR)).thenReturn(Mono.just(targetMember)); + when(orgDevChecker.checkOrgDev(targetMember)).thenReturn(Mono.error( + new BizException(BizError.NEED_DEV_TO_CREATE_RESOURCE, "NEED_DEV_TO_CREATE_RESOURCE"))); + lenient().when(sessionUserService.getVisitorOrgMemberCache()) + .thenReturn(Mono.just(new OrgMember("other-org", VISITOR, MemberRole.ADMIN, "normal", 0L))); + + StepVerifier.create(service.create(createRequest("Fresh", null, null))) + .expectErrorSatisfies(error -> assertBizError(error, BizError.NEED_DEV_TO_CREATE_RESOURCE, "NEED_DEV_TO_CREATE_RESOURCE")) + .verify(); + + verify(orgDevChecker).checkOrgDev(targetMember); + verify(sessionUserService, never()).getVisitorOrgMemberCache(); + assertThat(events).doesNotContain("create"); + say("create: admin of the current workspace, plain member of the target -> refused, target checked"); + } + /** * Catches a wrong creation: the gid is generated when empty and kept when given; the bundle is created NORMAL with all * flags false for the organization of the request, created by the member; without a folder no folder check, no default @@ -919,6 +948,57 @@ private Application app() { return application; } + private static final String UI_SECRET = "ui-secret-7f3a"; + private static final String QUERY_SECRET = "query-secret-91c2"; + private static final String MODULE_SECRET = "module-secret-5d0e"; + private static final Set DSL_DERIVED = Set.of("editingApplicationDSL", "editingApplicationDSLOrNull", "editingQueries", "editingModules"); + + /** A real {@link Application}, every field set, its editing DSL carrying the three secrets (D-42). */ + private Application realAppWithSecrets(String id) { + Map moduleComp = new HashMap<>(); + moduleComp.put("appId", MODULE_SECRET); + Map module = new HashMap<>(); + module.put("compType", "module"); + module.put("comp", moduleComp); + + Map uiComp = new HashMap<>(); + uiComp.put("text", UI_SECRET); + Map ui = new HashMap<>(); + ui.put("compType", "normal"); + ui.put("comp", uiComp); + ui.put("items", List.of(module)); + + Map queryComp = new HashMap<>(); + queryComp.put("body", QUERY_SECRET); + Map query = new HashMap<>(); + query.put("id", "q-" + id); + query.put("name", "query-" + id); + query.put("comp", queryComp); + query.put("compType", "restApi"); + + Map dsl = new HashMap<>(); + dsl.put("ui", ui); + dsl.put("queries", List.of(query)); + + return Application.builder() + .id(id) + .gid("gid-" + id) + .slug("slug-" + id) + .organizationId(ORG) + .name("App " + id) + .applicationType(org.lowcoder.domain.application.model.ApplicationType.APPLICATION.getValue()) + .applicationStatus(org.lowcoder.domain.application.model.ApplicationStatus.NORMAL) + .editingApplicationDSL(dsl) + .publicToAll(true) + .publicToMarketplace(true) + .agencyProfile(true) + .editingUserId("editing-user") + .lastEditedAt(CREATED_AT) + .createdBy("creator") + .createdAt(CREATED_AT) + .build(); + } + private Bundle bundleWithApps(String id, List applications) { Bundle value = bundle(id, BundleStatus.NORMAL); Map dsl = new HashMap<>(); @@ -965,7 +1045,7 @@ void moveApp_andAddApp_changeTheBundlesAfterTheApplicationPermission() { "perm:" + ResourceAction.MANAGE_BUNDLES + "@to-bundle", "findFrom", "findTo", "deleteRelation:from-bundle", "findFrom", "save:from-bundle", "repoFindTo", "save:to-bundle", "createRelation:to-bundle"); assertThat(applicationsOf(from)).isEmpty(); - assertThat(applicationsOf(to)).containsExactly(application); + assertThat(applicationsOf(to)).extracting(Application::getId).containsExactly(APP_ID); events.clear(); Bundle target = bundleWithApps("to-bundle", List.of()); @@ -973,7 +1053,7 @@ void moveApp_andAddApp_changeTheBundlesAfterTheApplicationPermission() { StepVerifier.create(service.addApp(APP_ID, "to-bundle")).verifyComplete(); assertThat(events).containsExactly("perm:" + ResourceAction.MANAGE_APPLICATIONS, "perm:" + ResourceAction.MANAGE_BUNDLES + "@to-bundle", "findTo", "deleteRelation:to-bundle", "findTo", "save:to-bundle", "createRelation:to-bundle"); - assertThat(applicationsOf(target)).containsExactly(application); + assertThat(applicationsOf(target)).extracting(Application::getId).containsExactly(APP_ID); events.clear(); StepVerifier.create(service.moveApp(APP_ID, "from-bundle", "")).verifyComplete(); @@ -997,10 +1077,58 @@ void moveApp_sourceBundleWithoutDsl_getsAnEmptyApplicationList() { StepVerifier.create(service.moveApp(APP_ID, "from-bundle", "to-bundle")).verifyComplete(); assertThat(applicationsOf(from)).isEmpty(); - assertThat(applicationsOf(to)).containsExactly(application); + assertThat(applicationsOf(to)).extracting(Application::getId).containsExactly(APP_ID); say("move from a bundle without DSL -> empty application list created"); } + /** + * D-42 change B: {@code addApp} and {@code moveApp} store a detached copy of the application, without its editing DSL, + * in the target bundle's editing DSL, whatever the adder may do; the repository instance is not mutated. + */ + @Test + void addApp_andMoveApp_storeADetachedCopyWithoutTheEditingDsl() throws Exception { + Application real = realAppWithSecrets(APP_ID); + Bundle from = bundleWithApps("from-bundle", List.of(real)); + Bundle to = bundleWithApps("to-bundle", List.of()); + stubRelations(from, to, real); + when(applicationRepository.findById(APP_ID)).thenReturn(Mono.just(real)); + ArgumentCaptor savedBundle = ArgumentCaptor.forClass(Bundle.class); + + StepVerifier.create(service.addApp(APP_ID, "to-bundle")).verifyComplete(); + + verify(bundleRepository, org.mockito.Mockito.atLeastOnce()).save(savedBundle.capture()); + Bundle toSaved = savedBundle.getAllValues().stream().filter(b -> "to-bundle".equals(b.getId())).findFirst().orElseThrow(); + List toApps = applicationsOf(toSaved); + assertThat(toApps).hasSize(1); + Application storedCopy = toApps.get(0); + assertThat(storedCopy).isNotSameAs(real); + assertThat(storedCopy.getId()).isEqualTo(APP_ID); + assertThat(storedCopy.getEditingApplicationDSL()).isEmpty(); + assertThat(storedCopy.getEditingQueries()).isEmpty(); + assertThat(storedCopy.getEditingModules()).isEmpty(); + String dslJson = JsonUtils.getObjectMapper().writeValueAsString(toSaved.getEditingBundleDSL()); + say("addApp stored bundle DSL: %s", dslJson); + assertThat(dslJson).contains(APP_ID).doesNotContain(UI_SECRET).doesNotContain(QUERY_SECRET).doesNotContain(MODULE_SECRET); + assertThat(real.getEditingApplicationDSL()).as("the repository instance is not mutated").isNotEmpty(); + + events.clear(); + savedBundle = ArgumentCaptor.forClass(Bundle.class); + Bundle moveTo = bundleWithApps("to-bundle", List.of()); + stubRelations(from, moveTo, real); + when(applicationRepository.findById(APP_ID)).thenReturn(Mono.just(real)); + + StepVerifier.create(service.moveApp(APP_ID, "from-bundle", "to-bundle")).verifyComplete(); + + assertThat(applicationsOf(from)).as("from loses the app").isEmpty(); + verify(bundleRepository, org.mockito.Mockito.atLeastOnce()).save(savedBundle.capture()); + Bundle moveToSaved = savedBundle.getAllValues().stream().filter(b -> "to-bundle".equals(b.getId())).reduce((first, second) -> second).orElseThrow(); + List moveToApps = applicationsOf(moveToSaved); + assertThat(moveToApps).hasSize(1); + assertThat(moveToApps.get(0)).isNotSameAs(real); + assertThat(moveToApps.get(0).getEditingApplicationDSL()).isEmpty(); + say("addApp/moveApp store a detached copy without the editing DSL"); + } + /** Catches a move or add by a visitor without the application permission: the denial is the result and nothing is changed. */ @Test void moveApp_andAddApp_deniedApplicationPermission_changeNothing() { @@ -1133,6 +1261,10 @@ void getElements_sortsByPosition_andIndexesTheApplications() { when(applicationServiceImpl.findById("t0")).thenReturn(Mono.just(a0)); when(applicationServiceImpl.findById("t1")).thenReturn(Mono.just(a1)); when(applicationServiceImpl.findById("t2")).thenReturn(Mono.just(a2)); + for (String target : new String[] {"t0", "t1", "t2"}) { + when(resourcePermissionService.checkUserPermissionStatusOnResource(VISITOR, target, ResourceAction.EDIT_APPLICATIONS)) + .thenReturn(Mono.just(status(Status.OK))); + } StepVerifier.create(service.getElements(BUNDLE_ID, null).cast(BundleApplication.class).collectList()).assertNext(elements -> { assertThat(elements).extracting(BundleApplication::application).containsExactly(a0, a1, a2); @@ -1178,6 +1310,7 @@ void getElements_withoutReadPermission_isRefused_andReadsNoElements(Status denia assertThat(bundleReads).as("the bundle is not read").hasValue(0); assertThat(relationReads).as("the element relations are not read").hasValue(0); verify(applicationServiceImpl, never()).findById(anyString()); + verify(resourcePermissionService, never()).checkUserPermissionStatusOnResource(anyString(), anyString(), eq(ResourceAction.EDIT_APPLICATIONS)); say("getElements %s -> %s, nothing read", denial, messageKey); } @@ -1199,9 +1332,101 @@ void getElements_ofABundleThatIsNotNormal_isBadRequest_andReadsNoElements(Bundle assertThat(relationReads).hasValue(0); verify(applicationServiceImpl, never()).findById(anyString()); + verify(resourcePermissionService, never()).checkUserPermissionStatusOnResource(anyString(), anyString(), eq(ResourceAction.EDIT_APPLICATIONS)); say("getElements of a %s bundle -> BAD_REQUEST, nothing read", status); } + /** + * D-42: an element the visitor may edit (EDIT_APPLICATIONS) is the loaded instance itself, DSL included; one it may not + * edit is a detached copy without it (every other property equal, position and order kept), and exactly one single-id + * permission check is made per element, never a batched one. + */ + @Test + void getElements_keepsTheEditingDslForAnEditor_andAnswersADetachedCopyOtherwise() throws Exception { + readGranted(BUNDLE_ID); + when(biRelationService.getBySourceId(BiRelationBizType.BUNDLE_ELEMENT, BUNDLE_ID)) + .thenReturn(Flux.just(relation("locked-app", "2"), relation("editable-app", "1"))); + Application editable = realAppWithSecrets("editable-app"); + Application locked = realAppWithSecrets("locked-app"); + when(applicationServiceImpl.findById("editable-app")).thenReturn(Mono.just(editable)); + when(applicationServiceImpl.findById("locked-app")).thenReturn(Mono.just(locked)); + when(resourcePermissionService.checkUserPermissionStatusOnResource(VISITOR, "editable-app", ResourceAction.EDIT_APPLICATIONS)) + .thenReturn(Mono.just(status(Status.OK))); + when(resourcePermissionService.checkUserPermissionStatusOnResource(VISITOR, "locked-app", ResourceAction.EDIT_APPLICATIONS)) + .thenReturn(Mono.just(status(Status.NOT_ENOUGH))); + assertThat(locked.getEditingQueries()).as("precondition: locked has queries").isNotEmpty(); + assertThat(locked.getEditingModules()).as("precondition: locked has modules").contains(MODULE_SECRET); + assertThat(JsonUtils.getObjectMapper().writeValueAsString(locked)).as("precondition: fixture is detectable") + .contains(UI_SECRET).contains(QUERY_SECRET).contains(MODULE_SECRET); + + List elements = service.getElements(BUNDLE_ID, null).cast(BundleApplication.class).collectList().block(); + + assertThat(elements).extracting(BundleApplication::position).containsExactly(0L, 1L); + assertThat(elements).extracting(e -> e.application().getId()).containsExactly("editable-app", "locked-app"); + Application editableElement = elements.get(0).application(); + Application lockedElement = elements.get(1).application(); + assertThat(editableElement).isSameAs(editable); + assertThat(JsonUtils.getObjectMapper().writeValueAsString(editableElement)).contains(UI_SECRET).contains(QUERY_SECRET).contains(MODULE_SECRET); + + assertThat(lockedElement).isNotSameAs(locked); + assertThat(lockedElement.getEditingApplicationDSLOrNull()).isEmpty(); + assertThat(lockedElement.getEditingApplicationDSL()).isEmpty(); + assertThat(lockedElement.getEditingQueries()).isEmpty(); + assertThat(lockedElement.getEditingModules()).isEmpty(); + String lockedJson = JsonUtils.getObjectMapper().writeValueAsString(lockedElement); + say("locked element JSON: %s", lockedJson); + assertThat(lockedJson).doesNotContain(UI_SECRET).doesNotContain(QUERY_SECRET).doesNotContain(MODULE_SECRET) + .contains("locked-app").contains(locked.getName()); + // The whole BundleApplication list also carries the editable element's secrets: that element is the loaded + // instance itself, unfiltered (the editor may see its own draft); only the locked element's copy is sanitized. + String wholeListJson = JsonUtils.getObjectMapper().writeValueAsString(elements); + assertThat(wholeListJson).contains(UI_SECRET).contains("editable-app").contains("locked-app"); + + var originalTree = JsonUtils.getObjectMapper().valueToTree(locked); + var copyTree = JsonUtils.getObjectMapper().valueToTree(lockedElement); + assertThat(copyTree.fieldNames()).toIterable().containsExactlyInAnyOrderElementsOf(() -> originalTree.fieldNames()); + originalTree.fieldNames().forEachRemaining(field -> { + if (DSL_DERIVED.contains(field)) { + return; + } + assertThat(copyTree.get(field)).as("property " + field).isEqualTo(originalTree.get(field)); + }); + assertThat(copyTree.get("editingApplicationDSL").size()).isZero(); + assertThat(copyTree.get("editingApplicationDSLOrNull").size()).isZero(); + assertThat(copyTree.get("editingQueries").size()).isZero(); + assertThat(copyTree.get("editingModules").size()).isZero(); + + assertThat(locked.getEditingApplicationDSL()).as("the loaded locked instance is not mutated").isNotEmpty(); + assertThat(locked.getEditingModules()).contains(MODULE_SECRET); + + verify(resourcePermissionService, times(1)).checkUserPermissionStatusOnResource(VISITOR, "editable-app", ResourceAction.EDIT_APPLICATIONS); + verify(resourcePermissionService, times(1)).checkUserPermissionStatusOnResource(VISITOR, "locked-app", ResourceAction.EDIT_APPLICATIONS); + verify(resourcePermissionService, times(2)).checkUserPermissionStatusOnResource(anyString(), anyString(), eq(ResourceAction.EDIT_APPLICATIONS)); + verify(resourcePermissionService, never()).getMaxMatchingPermission(anyString(), anyCollection(), any()); + verify(resourcePermissionService, never()).filterResourceWithPermission(anyString(), anyCollection(), any()); + verify(resourcePermissionService, never()).haveAllEnoughPermissions(anyString(), anyCollection(), any()); + say("editable element unchanged, locked element a sanitized copy; exactly one single-id check per element"); + } + + /** D-42: an empty permission answer (no matching row) counts as no permission; the element is the sanitized copy. */ + @Test + void getElements_withAnEmptyPermissionAnswer_answersTheCopy() { + readGranted(BUNDLE_ID); + when(biRelationService.getBySourceId(BiRelationBizType.BUNDLE_ELEMENT, BUNDLE_ID)).thenReturn(Flux.just(relation("app-x", "0"))); + Application real = realAppWithSecrets("app-x"); + when(applicationServiceImpl.findById("app-x")).thenReturn(Mono.just(real)); + when(resourcePermissionService.checkUserPermissionStatusOnResource(VISITOR, "app-x", ResourceAction.EDIT_APPLICATIONS)) + .thenReturn(Mono.empty()); + + StepVerifier.create(service.getElements(BUNDLE_ID, null).cast(BundleApplication.class).collectList()).assertNext(elements -> { + assertThat(elements).hasSize(1); + Application element = elements.get(0).application(); + assertThat(element).isNotSameAs(real); + assertThat(element.getEditingApplicationDSL()).isEmpty(); + }).verifyComplete(); + say("empty permission answer -> fail closed, the copy is answered"); + } + // ------------------------------------------------------------------ small ones /** Catches a wrong info view: creator name from the user service, flags, folder id, visibility; a missing creation time gives 0. */ diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/ApplicationEndpointsContractTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/ApplicationEndpointsContractTest.java index 0ddc173189..7f9d323986 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/ApplicationEndpointsContractTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/ApplicationEndpointsContractTest.java @@ -41,6 +41,7 @@ import org.lowcoder.domain.permission.model.ResourceRole; import org.lowcoder.infra.constant.NewUrl; import org.lowcoder.infra.constant.Url; +import org.lowcoder.sdk.config.JsonViews; import org.lowcoder.sdk.contract.CanonicalJson; import org.lowcoder.sdk.exception.BizError; import org.lowcoder.sdk.exception.BizException; @@ -348,14 +349,15 @@ void updateSlug() { } } - /** {@code @JsonView(Public)}: the body is the {@code S1Public} golden, without the auth configs' secrets. */ + /** {@code @JsonView(Public)}: the body is the {@code Public} output of the sample, which equals its S1 golden since the + * organization carries no auth configs (D-14). */ @Test void getUserHomePage() { Mockito.when(userHomeApiService.getUserHomePageView(ApplicationType.APPLICATION)).thenReturn(Mono.just(ApplicationSamples.userHomepageView())); try (ContractTestClient client = client()) { EntityExchangeResult result = CONTRACT.exchange(client, "getUserHomePage", Map.of("applicationType", APPLICATION_TYPE), null); EndpointContract.assertResponse(result, HttpStatus.OK, - EndpointContract.success(EndpointContract.fixture(UserHomepageView.class, "S1Public"))); + EndpointContract.success(EndpointContract.s1(UserHomepageView.class, JsonViews.Public.class))); } } diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/ApplicationHistorySnapshotEndpointsContractTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/ApplicationHistorySnapshotEndpointsContractTest.java index 91557caf04..1f62804737 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/ApplicationHistorySnapshotEndpointsContractTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/ApplicationHistorySnapshotEndpointsContractTest.java @@ -24,6 +24,7 @@ import org.lowcoder.domain.user.service.UserService; import org.lowcoder.sdk.constants.Authentication; import org.lowcoder.sdk.contract.CanonicalJson; +import org.lowcoder.sdk.exception.BizError; import org.lowcoder.sdk.models.HasIdAndAuditing; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; @@ -67,6 +68,7 @@ class ApplicationHistorySnapshotEndpointsContractTest { static final EndpointContract CONTRACT = new EndpointContract(ApplicationHistorySnapshotEndpoints.class); static final String APPLICATION_ID = "ApplicationHistorySnapshotEndpointsContractTest.applicationId"; + static final String OTHER_APPLICATION_ID = "ApplicationHistorySnapshotEndpointsContractTest.otherApplicationId"; static final String SNAPSHOT_ID = "ApplicationHistorySnapshotEndpointsContractTest.snapshotId"; static final String COMP_NAME = "ApplicationHistorySnapshotEndpointsContractTest.compName"; static final String THEME = "ApplicationHistorySnapshotEndpointsContractTest.theme"; @@ -97,6 +99,8 @@ void mocks() { applicationRecordService = builder.mock(ApplicationRecordService.class); Mockito.when(builder.mock(ResourcePermissionService.class).checkResourcePermissionWithError(anyString(), anyString(), eq(ResourceAction.EDIT_APPLICATIONS))).thenReturn(Mono.empty()); + Mockito.when(applicationService.findByIdWithoutDsl(APPLICATION_ID)) + .thenReturn(Mono.just(Application.builder().id(APPLICATION_ID).build())); } @AfterAll @@ -104,24 +108,31 @@ static void everyEndpointAndBranchHasATest() { CONTRACT.assertComplete(ApplicationHistorySnapshotEndpointsContractTest.class); } - /** The controller passes the body's parts on: the application id, the DSL and the context, compared by D1's rules. */ + /** + * The controller stores the snapshot under the object id the body's application key resolves to (D-31), with the + * body's DSL and context, compared by D1's rules. + */ @Test @SuppressWarnings("unchecked") void create() { ApplicationHistorySnapshotRequest expected = (ApplicationHistorySnapshotRequest) PayloadSamples.of(ApplicationHistorySnapshotRequest.class).value(); - Mockito.when(snapshotService.createHistorySnapshot(eq(expected.applicationId()), any(), any(), eq(Authentication.ANONYMOUS_USER_ID))) + assertThat(expected.applicationId()).isNotEqualTo(APPLICATION_ID); + Mockito.when(applicationService.findByIdWithoutDsl(expected.applicationId())) + .thenReturn(Mono.just(Application.builder().id(APPLICATION_ID).build())); + Mockito.when(snapshotService.createHistorySnapshot(any(), any(), any(), eq(Authentication.ANONYMOUS_USER_ID))) .thenReturn(Mono.just(Boolean.TRUE)); - Mockito.when(applicationService.updateLastEditedAt(eq(expected.applicationId()), any(), eq(Authentication.ANONYMOUS_USER_ID))) + Mockito.when(applicationService.updateLastEditedAt(any(), any(), eq(Authentication.ANONYMOUS_USER_ID))) .thenReturn(Mono.just(Boolean.TRUE)); try (ContractTestClient client = client()) { EntityExchangeResult result = CONTRACT.exchange(client, "create", Map.of(), EndpointContract.d1(ApplicationHistorySnapshotRequest.class)); EndpointContract.assertResponse(result, HttpStatus.OK, EndpointContract.success(TRUE)); ArgumentCaptor> dsl = ArgumentCaptor.forClass(Map.class); ArgumentCaptor> context = ArgumentCaptor.forClass(Map.class); - Mockito.verify(snapshotService).createHistorySnapshot(eq(expected.applicationId()), dsl.capture(), context.capture(), + Mockito.verify(snapshotService).createHistorySnapshot(eq(APPLICATION_ID), dsl.capture(), context.capture(), eq(Authentication.ANONYMOUS_USER_ID)); CanonicalJson.assertSameJava(expected.dsl(), dsl.getValue()); CanonicalJson.assertSameJava(expected.context(), context.getValue()); + Mockito.verify(applicationService).updateLastEditedAt(eq(APPLICATION_ID), any(), eq(Authentication.ANONYMOUS_USER_ID)); } } @@ -175,6 +186,8 @@ void getHistorySnapshotDsl() { HistorySnapshotDslView view = ApplicationSamples.historySnapshotDslView(); ApplicationHistorySnapshot snapshot = new ApplicationHistorySnapshot(); snapshot.setDsl(view.getApplicationsDsl()); + snapshot.setApplicationId(APPLICATION_ID); + snapshot.setApplicationIdResolved(true); Mockito.when(snapshotService.getHistorySnapshotDetail(SNAPSHOT_ID)).thenReturn(Mono.just(snapshot)); stubModules(view); assertDslView("getHistorySnapshotDsl"); @@ -185,11 +198,49 @@ void getHistorySnapshotDslArchived() { HistorySnapshotDslView view = ApplicationSamples.historySnapshotDslView(); ApplicationHistorySnapshotTS snapshot = new ApplicationHistorySnapshotTS(); snapshot.setDsl(view.getApplicationsDsl()); + snapshot.setApplicationId(APPLICATION_ID); + snapshot.setApplicationIdResolved(true); Mockito.when(snapshotService.getHistorySnapshotDetailArchived(SNAPSHOT_ID)).thenReturn(Mono.just(snapshot)); stubModules(view); assertDslView("getHistorySnapshotDslArchived"); } + /** D-31: a snapshot of another application gets the answer of an unknown snapshot id (same status, code and message). */ + @Test + void getHistorySnapshotDslOfAnotherApplication() { + HistorySnapshotDslView view = ApplicationSamples.historySnapshotDslView(); + ApplicationHistorySnapshot snapshot = new ApplicationHistorySnapshot(); + snapshot.setDsl(view.getApplicationsDsl()); + snapshot.setApplicationId(OTHER_APPLICATION_ID); + snapshot.setApplicationIdResolved(true); + Mockito.when(snapshotService.getHistorySnapshotDetail(SNAPSHOT_ID)).thenReturn(Mono.just(snapshot)); + stubModules(view); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "getHistorySnapshotDsl", Map.of(), null, APPLICATION_ID, SNAPSHOT_ID); + EndpointContract.assertBizError(result, BizError.INVALID_HISTORY_SNAPSHOT, "INVALID_HISTORY_SNAPSHOT", SNAPSHOT_ID); + Mockito.verify(applicationService, Mockito.never()).findByIdWithoutDsl(OTHER_APPLICATION_ID); + Mockito.verify(applicationService, Mockito.never()).getAllDependentModulesFromDsl(any()); + } + } + + /** As {@link #getHistorySnapshotDslOfAnotherApplication}, for the archive route. */ + @Test + void getHistorySnapshotDslArchivedOfAnotherApplication() { + HistorySnapshotDslView view = ApplicationSamples.historySnapshotDslView(); + ApplicationHistorySnapshotTS snapshot = new ApplicationHistorySnapshotTS(); + snapshot.setDsl(view.getApplicationsDsl()); + snapshot.setApplicationId(OTHER_APPLICATION_ID); + snapshot.setApplicationIdResolved(true); + Mockito.when(snapshotService.getHistorySnapshotDetailArchived(SNAPSHOT_ID)).thenReturn(Mono.just(snapshot)); + stubModules(view); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "getHistorySnapshotDslArchived", Map.of(), null, APPLICATION_ID, SNAPSHOT_ID); + EndpointContract.assertBizError(result, BizError.INVALID_HISTORY_SNAPSHOT, "INVALID_HISTORY_SNAPSHOT", SNAPSHOT_ID); + Mockito.verify(applicationService, Mockito.never()).findByIdWithoutDsl(OTHER_APPLICATION_ID); + Mockito.verify(applicationService, Mockito.never()).getAllDependentModulesFromDsl(any()); + } + } + private ContractTestClient client() { return builder.controllerWithMockedDependencies(ApplicationHistorySnapshotController.class).build(); } diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/InvitationEndpointsContractTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/InvitationEndpointsContractTest.java index 30cac8261e..663504073a 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/InvitationEndpointsContractTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/InvitationEndpointsContractTest.java @@ -3,6 +3,8 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.lowcoder.api.contract.support.ContractTestClient; import org.lowcoder.api.contract.support.EndpointContract; import org.lowcoder.api.contract.support.PayloadSamples; @@ -141,6 +143,27 @@ void sendInvitationEmails() { } } + /** + * D-54: the invitation link has exactly one slash before {@code invite/} whether the configured public URL + * ends in none, one or several slashes. The double-slash case is the one {@code StringUtils.removeEnd} would fail + * (it removes one slash only). + */ + @ParameterizedTest(name = "public URL \"{0}\"") + @ValueSource(strings = {PUBLIC_URL, PUBLIC_URL + "/", PUBLIC_URL + "//"}) + void sendInvitationEmailsLinkHasOneSlash(String publicUrl) { + InviteEmailRequest sample = (InviteEmailRequest) PayloadSamples.of(InviteEmailRequest.class).value(); + InvitationVO invitation = UserManagementSamples.invitationVO(); + Mockito.when(builder.mock(CommonConfig.class).getLowcoderPublicUrl()).thenReturn(publicUrl); + Mockito.when(invitationApiService.create(sample.orgId())).thenReturn(Mono.just(invitation)); + EmailCommunicationService mail = builder.mock(EmailCommunicationService.class); + Mockito.when(mail.sendInvitationEmails(any(), anyString(), anyString())).thenReturn(true); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "sendInvitationEmails", Map.of(), EndpointContract.d1(InviteEmailRequest.class)); + EndpointContract.assertResponse(result, HttpStatus.OK, EndpointContract.success(TRUE)); + Mockito.verify(mail).sendInvitationEmails(any(), eq(PUBLIC_URL + INVITE_PATH + invitation.getInviteCode()), eq(INVITATION_MESSAGE)); + } + } + /** * BF-139: a body with no addresses (an empty array, none at all, null) or with a blank one is INVALID_PARAMETER * "emails", and neither an invitation is created nor a mail sent (an empty array stored an invitation and answered diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/OrganizationEndpointsContractTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/OrganizationEndpointsContractTest.java index 84ef640963..6bfb6488b6 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/OrganizationEndpointsContractTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/OrganizationEndpointsContractTest.java @@ -75,8 +75,8 @@ * {@link OrgView}s, {@code getOrgCommonSettings} answers the {@code HashMap} subclass {@link OrganizationCommonSettings}, * and {@code setCurrentOrganization} a {@code Boolean} or the redirect envelope around a {@link RedirectView} (its bind * branch is the {@code NEED_BIND_THIRD_PARTY_CONNECTION} error). - * {@code getOrganization} and {@code updateSlug} answer a whole {@link Organization} without a view, its auth configs' - * {@code clientSecret} included (O22). One test per registry response branch, named as the branch. + * {@code getOrganization} and {@code updateSlug} answer a whole {@link Organization} without a view, + * without its auth configs (D-14; O22 before). One test per registry response branch, named as the branch. * *

Stubbing groups (registry column {@code group}): {@code assembling} for {@code getOrganizationByUser}, whose * sorted page the controller builds from organizations; {@code pass-through} for the others, where the payload is one @@ -397,7 +397,7 @@ void getOrgApiUsageCount() { } } - /** A {@code String} body is passed through as text (§5.2): the slug keeps the JSON quotes. The answer is O22's. */ + /** A {@code String} body is passed through as text (§5.2): the slug keeps the JSON quotes. The answer is the organization without its auth configs (D-14). */ @Test void updateSlug() { Mockito.when(orgApiService.updateSlug(ORG_ID, SLUG_BODY)).thenReturn(Mono.just(OrganizationSamples.organization())); @@ -408,7 +408,7 @@ void updateSlug() { } } - /** {@code withDeleted=true} is handed on to {@code OrgApiService.getOrganization}; the answer is O22's. */ + /** {@code withDeleted=true} is handed on to {@code OrgApiService.getOrganization}; the answer is the organization without its auth configs (D-14). */ @Test void getOrganization() { Mockito.when(orgApiService.getOrganization(ORG_ID, true)).thenReturn(Mono.just(OrganizationSamples.organization())); @@ -499,10 +499,11 @@ private void assertSuccessTrue(String method, Map query, Object... ur } } - /** The whole {@link Organization}, without a view: its auth configs' {@code clientSecret} is in the answer (O22). */ + /** The whole {@link Organization} without its auth configs: no {@code clientSecret} in the answer (D-14). */ private static void assertOrganization(EntityExchangeResult result) { EndpointContract.assertResponse(result, HttpStatus.OK, EndpointContract.success(EndpointContract.s1(Organization.class))); - assertThat(new String(result.getResponseBody(), StandardCharsets.UTF_8)).as("O22: the organization writes its auth configs' secrets") - .contains(PayloadSamples.SECRET_MARKER); + assertThat(new String(result.getResponseBody(), StandardCharsets.UTF_8)) + .as("D-14: the organization answer carries no auth config secret") + .doesNotContain(PayloadSamples.SECRET_MARKER); } } diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/PrivateNpmRegistryEndpointContractTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/PrivateNpmRegistryEndpointContractTest.java index 249b32363e..515e1db9ae 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/PrivateNpmRegistryEndpointContractTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/PrivateNpmRegistryEndpointContractTest.java @@ -17,7 +17,10 @@ import org.lowcoder.domain.organization.model.Organization; import org.lowcoder.domain.organization.model.Organization.OrganizationCommonSettings; import org.lowcoder.domain.organization.service.OrganizationService; +import org.lowcoder.domain.permission.model.ResourceAction; +import org.lowcoder.domain.permission.service.ResourcePermissionService; import org.lowcoder.infra.js.NodeServerHelper; +import org.lowcoder.sdk.constants.Authentication; import org.lowcoder.sdk.contract.BoundarySites; import org.lowcoder.sdk.contract.GoldenJson; import org.mockito.Mockito; @@ -183,6 +186,9 @@ private void visitorOrganizationHas(OrganizationCommonSettings settings) { } private void applicationOrganizationHas(OrganizationCommonSettings settings) { + Mockito.when(builder.mock(ResourcePermissionService.class).checkResourcePermissionWithError( + Authentication.ANONYMOUS_USER_ID, APPLICATION_ID, ResourceAction.READ_APPLICATIONS)) + .thenReturn(Mono.empty()); Mockito.when(builder.mock(ApplicationServiceImpl.class).findById(APPLICATION_ID)) .thenReturn(Mono.just(Application.builder().id(APPLICATION_ID).organizationId(ORG_ID).build())); Mockito.when(organizationService.getById(ORG_ID)).thenReturn(Mono.just(Organization.builder().id(ORG_ID).build())); diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/UserEndpointsContractTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/UserEndpointsContractTest.java index d184bab016..eb8ae5b8d5 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/UserEndpointsContractTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/endpoint/UserEndpointsContractTest.java @@ -41,6 +41,7 @@ import org.lowcoder.sdk.constants.AuthSourceConstants; import org.lowcoder.sdk.contract.CanonicalJson; import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.springframework.core.io.buffer.DataBufferUtils; @@ -102,7 +103,9 @@ class UserEndpointsContractTest { static final String OTHER_LANGUAGE = "xx-NEW136"; static final String HAS_SET_NICKNAME_FIELD = "hasSetNickname"; static final String ORG_NAME = "UserEndpointsContractTest.orgName"; - static final String PASSWORD = "UserEndpointsContractTest.password"; + static final String PASSWORD = "UserEndpointsContractTest.password1"; + /** D-48: refused by the client's password rule regardless of any other check. */ + static final String WEAK_PASSWORD = "a"; static final String BLANK = " "; static final String UNKNOWN_STATUS_TYPE = "UserEndpointsContractTest.unknownStatusType"; static final String NOT_AN_EMAIL = "UserEndpointsContractTest.notAnEmail"; @@ -110,6 +113,7 @@ class UserEndpointsContractTest { /** The visitor is the {@code User} sample; {@code SessionUserService#getVisitorId} answers its id. */ static final User VISITOR = UserSamples.user(); static final String VISITOR_ID = VISITOR.getId(); + private static final String VISITOR_TOKEN = "UserEndpointsContractTest.visitorToken"; static final OrgMember VISITOR_ORG_MEMBER = new OrgMember(UserManagementSamples.orgViewOrganization().getId(), VISITOR_ID, MemberRole.ADMIN, "UserEndpointsContractTest.state", 3_000_000_150L); /** The path's user, a plain member of {@code ORG_ID}, for the admin routes' membership check. */ @@ -218,9 +222,9 @@ void createSCIMUserAndAddToOrgWithInvalidEmail() { } /** - * No organization-domain action: the profile in a {@code ResponseView}. The endpoint has no {@code @JsonView}, so - * the organizations of {@code orgAndRoles} are written whole, the auth configs' {@code clientSecret} included - * (O22); the explicit check makes a fix fail here by name, not only as a golden difference. + * No organization-domain action: the profile in a {@code ResponseView}. The endpoint has no {@code @JsonView}; the + * organizations of {@code orgAndRoles} are written without their auth configs (D-14), and the explicit check fails + * by name if a secret returns, not only as a golden difference. */ @Test void getUserProfile() { @@ -228,8 +232,9 @@ void getUserProfile() { try (ContractTestClient client = client()) { EntityExchangeResult result = CONTRACT.exchange(client, "getUserProfile", Map.of(), null); EndpointContract.assertResponse(result, HttpStatus.OK, EndpointContract.success(EndpointContract.s1(UserProfileView.class))); - assertThat(new String(result.getResponseBody(), StandardCharsets.UTF_8)).as("O22: the profile writes the auth configs' secrets") - .contains(PayloadSamples.SECRET_MARKER); + assertThat(new String(result.getResponseBody(), StandardCharsets.UTF_8)) + .as("D-14: the profile carries no auth config secret") + .doesNotContain(PayloadSamples.SECRET_MARKER); } } @@ -594,10 +599,41 @@ void getProfilePhotoOfUserNotFound() { void updatePassword() { UpdatePasswordRequest request = (UpdatePasswordRequest) PayloadSamples.of(UpdatePasswordRequest.class).value(); Mockito.when(userService.updatePassword(VISITOR_ID, request.oldPassword(), request.newPassword())).thenReturn(Mono.just(Boolean.TRUE)); + Mockito.when(sessionUserService.getVisitorToken()).thenReturn(Mono.just(VISITOR_TOKEN)); + Mockito.when(sessionUserService.endSessionsOfUser(VISITOR_ID, VISITOR_TOKEN)).thenReturn(Mono.empty()); try (ContractTestClient client = client()) { EntityExchangeResult result = CONTRACT.exchange(client, "updatePassword", Map.of(), EndpointContract.d1(UpdatePasswordRequest.class)); EndpointContract.assertResponse(result, HttpStatus.OK, EndpointContract.success(TRUE)); Mockito.verify(userService).updatePassword(VISITOR_ID, request.oldPassword(), request.newPassword()); + Mockito.verify(sessionUserService).endSessionsOfUser(VISITOR_ID, VISITOR_TOKEN); + } + } + + /** D-34: a session that cannot be ended fails the request although the password has changed. */ + @Test + void updatePasswordSessionsNotEnded() { + UpdatePasswordRequest request = (UpdatePasswordRequest) PayloadSamples.of(UpdatePasswordRequest.class).value(); + Mockito.when(userService.updatePassword(VISITOR_ID, request.oldPassword(), request.newPassword())).thenReturn(Mono.just(Boolean.TRUE)); + Mockito.when(sessionUserService.getVisitorToken()).thenReturn(Mono.just(VISITOR_TOKEN)); + Mockito.when(sessionUserService.endSessionsOfUser(VISITOR_ID, VISITOR_TOKEN)).thenReturn( + Mono.error(new BizException(BizError.PASSWORD_CHANGED_SESSIONS_NOT_ENDED, "PASSWORD_CHANGED_SESSIONS_NOT_ENDED", 1))); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "updatePassword", Map.of(), EndpointContract.d1(UpdatePasswordRequest.class)); + EndpointContract.assertBizError(result, BizError.PASSWORD_CHANGED_SESSIONS_NOT_ENDED, "PASSWORD_CHANGED_SESSIONS_NOT_ENDED", 1); + Mockito.verify(userService).updatePassword(VISITOR_ID, request.oldPassword(), request.newPassword()); + } + } + + /** A wrong old password fails before the sweep ever runs. */ + @Test + void updatePasswordWrongOldPassword() { + UpdatePasswordRequest request = (UpdatePasswordRequest) PayloadSamples.of(UpdatePasswordRequest.class).value(); + Mockito.when(userService.updatePassword(VISITOR_ID, request.oldPassword(), request.newPassword())) + .thenReturn(Mono.error(new BizException(BizError.INVALID_PASSWORD, "INVALID_PASSWORD"))); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "updatePassword", Map.of(), EndpointContract.d1(UpdatePasswordRequest.class)); + EndpointContract.assertBizError(result, BizError.INVALID_PASSWORD, "INVALID_PASSWORD"); + Mockito.verify(sessionUserService, Mockito.never()).endSessionsOfUser(Mockito.any(), Mockito.any()); } } @@ -607,6 +643,19 @@ void updatePasswordWithEmptyPassword() { try (ContractTestClient client = client()) { EntityExchangeResult result = CONTRACT.exchange(client, "updatePassword", Map.of(), "{\"oldPassword\": \"" + PASSWORD + "\"}"); EndpointContract.assertBizError(result, BizError.INVALID_PARAMETER, "PASSWORD_EMPTY"); + Mockito.verify(sessionUserService, Mockito.never()).endSessionsOfUser(Mockito.any(), Mockito.any()); + } + } + + /** D-48: a weak new password is refused before the old password is checked or any session is ended. */ + @Test + void updatePasswordTooWeak() { + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "updatePassword", Map.of(), + "{\"oldPassword\": \"" + PASSWORD + "\", \"newPassword\": \"" + WEAK_PASSWORD + "\"}"); + EndpointContract.assertBizError(result, BizError.INVALID_PASSWORD, "PASSWORD_TOO_WEAK"); + Mockito.verifyNoInteractions(userService); + Mockito.verify(sessionUserService, Mockito.never()).endSessionsOfUser(Mockito.any(), Mockito.any()); } } @@ -683,13 +732,39 @@ void resetLostPasswordWithMissingField() { } } - /** The password is a query parameter, not a body. */ + /** D-48: a weak new password is refused before the token is checked or burnt. */ + @Test + void resetLostPasswordTooWeak() { + ResetLostPasswordRequest request = (ResetLostPasswordRequest) PayloadSamples.of(ResetLostPasswordRequest.class).value(); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "resetLostPassword", Map.of(), + "{\"userEmail\": \"" + request.userEmail() + "\", \"token\": \"" + request.token() + "\", \"newPassword\": \"" + WEAK_PASSWORD + "\"}"); + EndpointContract.assertBizError(result, BizError.INVALID_PASSWORD, "PASSWORD_TOO_WEAK"); + Mockito.verifyNoInteractions(userApiService); + } + } + + /** The password is a query parameter, not a body. An account without a password (D-49). */ @Test void setPassword() { - Mockito.when(userService.setPassword(VISITOR_ID, PASSWORD)).thenReturn(Mono.just(Boolean.TRUE)); + Mockito.when(userService.setPasswordIfAbsent(VISITOR_ID, PASSWORD)).thenReturn(Mono.just(Boolean.TRUE)); try (ContractTestClient client = client()) { EntityExchangeResult result = CONTRACT.exchange(client, "setPassword", Map.of("password", PASSWORD), null); EndpointContract.assertResponse(result, HttpStatus.OK, EndpointContract.success(TRUE)); + Mockito.verify(userService).setPasswordIfAbsent(VISITOR_ID, PASSWORD); + Mockito.verify(userService, Mockito.never()).setPassword(Mockito.any(), Mockito.any()); + } + } + + /** An account that already has a password refuses the route (D-49). */ + @Test + void setPasswordAlreadySet() { + Mockito.when(userService.setPasswordIfAbsent(VISITOR_ID, PASSWORD)) + .thenReturn(Mono.error(new BizException(BizError.INVALID_PASSWORD, "PASSWORD_ALREADY_SET"))); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "setPassword", Map.of("password", PASSWORD), null); + EndpointContract.assertBizError(result, BizError.INVALID_PASSWORD, "PASSWORD_ALREADY_SET"); + Mockito.verify(userService, Mockito.never()).setPassword(Mockito.any(), Mockito.any()); } } @@ -698,6 +773,23 @@ void setPasswordEmpty() { try (ContractTestClient client = client()) { EntityExchangeResult result = CONTRACT.exchange(client, "setPassword", Map.of("password", BLANK), null); EndpointContract.assertBizError(result, BizError.INVALID_PARAMETER, "PASSWORD_EMPTY"); + Mockito.verifyNoInteractions(userService); + } + } + + /** + * D-48 ordering against D-49: the visitor fixture already has a password ({@code UserSamples.java:55}), so a + * wrong check order would answer {@code PASSWORD_ALREADY_SET} instead of {@code PASSWORD_TOO_WEAK}. + */ + @Test + void setPasswordTooWeak() { + Mockito.when(userService.setPasswordIfAbsent(VISITOR_ID, WEAK_PASSWORD)) + .thenReturn(Mono.error(new BizException(BizError.INVALID_PASSWORD, "PASSWORD_ALREADY_SET"))); + try (ContractTestClient client = client()) { + EntityExchangeResult result = CONTRACT.exchange(client, "setPassword", Map.of("password", WEAK_PASSWORD), null); + EndpointContract.assertBizError(result, BizError.INVALID_PASSWORD, "PASSWORD_TOO_WEAK"); + Mockito.verify(userService, Mockito.never()).setPasswordIfAbsent(Mockito.any(), Mockito.any()); + Mockito.verify(userService, Mockito.never()).setPassword(Mockito.any(), Mockito.any()); } } diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/support/OrganizationSamples.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/support/OrganizationSamples.java index 79f73850b4..206eb955db 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/support/OrganizationSamples.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/support/OrganizationSamples.java @@ -29,9 +29,9 @@ private OrganizationSamples() { /** * An organization whose domain holds one config of each of the five {@code AbstractAuthConfig} classes, so that - * the computed {@code authConfigs} (from the write-only {@code organizationDomain}) carries all of them. The - * {@code @JsonIgnore}d {@code logoAssetId} and {@code createdAt} are set for the computed {@code logoUrl} and - * {@code createTime}. + * the MongoDB hooks of the domain convert all of them ({@code UserManagementPayloadGettersTest}); the + * organization's JSON has no {@code authConfigs} (D-14). The {@code @JsonIgnore}d {@code logoAssetId} and + * {@code createdAt} are set for the computed {@code logoUrl} and {@code createTime}. */ public static Organization organization() { OrganizationDomain domain = new OrganizationDomain(); diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/support/UserManagementSamples.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/support/UserManagementSamples.java index a9a7e5916a..add8a93500 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/support/UserManagementSamples.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/contract/support/UserManagementSamples.java @@ -82,7 +82,7 @@ public static MarkUserStatusRequest markUserStatusRequest() { public static ResetLostPasswordRequest resetLostPasswordRequest() { return new ResetLostPasswordRequest("ResetLostPasswordRequest.token", "ResetLostPasswordRequest.userEmail", - "ResetLostPasswordRequest.newPassword"); + "ResetLostPasswordRequest.newPassword1"); } public static ResetPasswordRequest resetPasswordRequest() { @@ -90,7 +90,7 @@ public static ResetPasswordRequest resetPasswordRequest() { } public static UpdatePasswordRequest updatePasswordRequest() { - return new UpdatePasswordRequest("UpdatePasswordRequest.oldPassword", "UpdatePasswordRequest.newPassword"); + return new UpdatePasswordRequest("UpdatePasswordRequest.oldPassword", "UpdatePasswordRequest.newPassword1"); } public static UpdateUserRequest updateUserRequest() { diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/datasource/DatasourceApiServiceImplTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/datasource/DatasourceApiServiceImplTest.java index 662e998f88..9a0e1f7d29 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/datasource/DatasourceApiServiceImplTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/datasource/DatasourceApiServiceImplTest.java @@ -221,7 +221,7 @@ void create_generatesGidOnlyWhenMissing_andRunsTheStepsInOrder(String gid, boole stubVisitor(); when(orgMemberService.getOrgMember(ORG_ID, VISITOR_ID)) .thenReturn(Mono.just(new OrgMember(ORG_ID, VISITOR_ID, MemberRole.MEMBER, "CURRENT", 0L))); - when(orgDevChecker.checkCurrentOrgDev()).thenReturn(loggedVoid("dev")); + when(orgDevChecker.checkOrgDev(any())).thenReturn(loggedVoid("dev")); when(datasourceService.create(datasource, VISITOR_ID)).thenReturn(logged("create", datasource)); when(jsDatasourceHelper.processDynamicQueryConfig(datasource)).thenReturn(loggedVoid("process")); @@ -245,7 +245,7 @@ void create_visitorNotInTheOrganization_isNotAuthorizedAndCreatesNothing() { Datasource datasource = datasource(null, "ds", SQL_TYPE, DatasourceStatus.NORMAL); stubVisitor(); when(orgMemberService.getOrgMember(ORG_ID, VISITOR_ID)).thenReturn(Mono.empty()); - lenient().when(orgDevChecker.checkCurrentOrgDev()).thenReturn(loggedVoid("dev")); + lenient().when(orgDevChecker.checkOrgDev(any())).thenReturn(loggedVoid("dev")); lenient().when(datasourceService.create(any(), any())).thenReturn(logged("create", datasource)); StepVerifier.create(service.create(datasource)) @@ -256,7 +256,7 @@ void create_visitorNotInTheOrganization_isNotAuthorizedAndCreatesNothing() { } /** - * Catches a datasource created by a non-developer: a failing {@code checkCurrentOrgDev} stops the creation. + * Catches a datasource created by a non-developer: a failing {@code checkOrgDev} stops the creation. */ @Test void create_developerCheckFails_createsNothing() { @@ -264,7 +264,7 @@ void create_developerCheckFails_createsNothing() { stubVisitor(); when(orgMemberService.getOrgMember(ORG_ID, VISITOR_ID)) .thenReturn(Mono.just(new OrgMember(ORG_ID, VISITOR_ID, MemberRole.MEMBER, "CURRENT", 0L))); - when(orgDevChecker.checkCurrentOrgDev()).thenReturn(Mono.error(denied())); + when(orgDevChecker.checkOrgDev(any())).thenReturn(Mono.error(denied())); lenient().when(datasourceService.create(any(), any())).thenReturn(logged("create", datasource)); StepVerifier.create(service.create(datasource)) @@ -274,6 +274,33 @@ void create_developerCheckFails_createsNothing() { say("create: developer check failed -> nothing created"); } + /** + * D-11/D-41: the developer check runs on the TARGET workspace (the request's {@code organizationId}), not the + * visitor's current one. An admin of a different, current workspace who is a plain member of the target still + * needs the real {@link org.lowcoder.api.usermanagement.OrgDevChecker#checkOrgDev} to refuse, so the call must + * carry the exact target membership; the current-workspace cache is never read in {@code create}. + */ + @Test + void create_developerOfTheCurrentWorkspace_butNotOfTheTargetWorkspace_isRefused() { + Datasource datasource = datasource(null, "ds", SQL_TYPE, DatasourceStatus.NORMAL); + stubVisitor(); + OrgMember targetMember = new OrgMember(ORG_ID, VISITOR_ID, MemberRole.MEMBER, "CURRENT", 0L); + when(orgMemberService.getOrgMember(ORG_ID, VISITOR_ID)).thenReturn(Mono.just(targetMember)); + when(orgDevChecker.checkOrgDev(targetMember)).thenReturn(Mono.error(denied())); + lenient().when(sessionUserService.getVisitorOrgMemberCache()) + .thenReturn(Mono.just(new OrgMember("other-org", VISITOR_ID, MemberRole.ADMIN, "normal", 0L))); + lenient().when(datasourceService.create(any(), any())).thenReturn(logged("create", datasource)); + + StepVerifier.create(service.create(datasource)) + .expectErrorSatisfies(error -> assertBizError(error, BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED")) + .verify(); + + verify(orgDevChecker).checkOrgDev(targetMember); + verify(sessionUserService, never()).getVisitorOrgMemberCache(); + assertThat(events).isEmpty(); + say("create: admin of the current workspace, plain member of the target -> refused, target checked"); + } + // ------------------------------------------------------------------ listJsDatasourcePlugins private List pluginCandidates() { diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/AbstractCorsCredentialsTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/AbstractCorsCredentialsTest.java new file mode 100644 index 0000000000..06b233540d --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/AbstractCorsCredentialsTest.java @@ -0,0 +1,86 @@ +package org.lowcoder.api.framework.security; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.lowcoder.infra.constant.NewUrl; +import org.lowcoder.infra.constant.Url; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import org.springframework.test.web.reactive.server.WebTestClient; + +/** + * Shared preflight helper and assertions for the {@code SecurityConfig.buildCorsConfigurationSource} credentials + * cases below: a listed, non-wildcard origin gets credentials everywhere; an unlisted origin gets a 200 without + * credentials only on a path the configuration used to grant "any origin, with credentials" unconditionally, or on + * any path at all when the configured domains contain the literal {@code "*"} entry; otherwise it is refused, same + * as {@link CorsAllowedDomainsPreflightTest}. + */ +abstract class AbstractCorsCredentialsTest { + + static final String CORS_DOMAINS_PROPERTY = "common.security.corsAllowedDomainString"; + /** A {@code GET}-only path the configuration used to grant "any origin, with credentials" unconditionally, before this fix. */ + static final String FORMER_ANY_ORIGIN_PATH = Url.USER_URL + "/me"; + static final HttpMethod FORMER_ANY_ORIGIN_METHOD = HttpMethod.GET; + /** A {@code POST}-only path, same former-any-origin status as {@link #FORMER_ANY_ORIGIN_PATH}. */ + static final String FORMER_ANY_ORIGIN_PATH_QUERY = Url.QUERY_URL + "/execute"; + static final HttpMethod FORMER_ANY_ORIGIN_QUERY_METHOD = HttpMethod.POST; + /** {@code POST} of the invitation mail: under the allow-list configuration, mounted under {@code /api} and {@code /api/v1}. */ + private static final String INVITATION_MAIL_PATH = "/email/invite"; + static final HttpMethod ALLOW_LIST_METHOD = HttpMethod.POST; + /** An endpoint under the allow-list configuration, in the current and the legacy mount. Never a former any-origin path. */ + static final List ALLOW_LIST_PATHS = List.of(NewUrl.INVITATION_URL + INVITATION_MAIL_PATH, Url.INVITATION_URL + INVITATION_MAIL_PATH); + /** The server the requests go to; CORS compares the request's scheme and host with the origin, so it must be absolute. */ + private static final String SERVER = "http://lowcoder.test"; + private static final String TRUE = "true"; + private static final Duration WAIT = Duration.ofSeconds(30); + + @Autowired + private ApplicationContext context; + + private WebTestClient web; + + @BeforeEach + void setUpClient() { + web = WebTestClient.bindToApplicationContext(context).configureClient().responseTimeout(WAIT).build(); + } + + final EntityExchangeResult preflight(String path, String origin, HttpMethod requestMethod) { + EntityExchangeResult result = web.options().uri(SERVER + path) + .header(HttpHeaders.ORIGIN, origin) + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, requestMethod.name()) + .exchange() + .expectBody().returnResult(); + System.out.println("[" + getClass().getSimpleName() + "] OPTIONS " + path + " (" + requestMethod + ") from " + origin + " -> " + + result.getStatus() + " allow-origin=" + result.getResponseHeaders().getAccessControlAllowOrigin() + + " allow-credentials=" + result.getResponseHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + return result; + } + + final void assertAllowedWithCredentials(String path, String origin, HttpMethod requestMethod) { + EntityExchangeResult result = preflight(path, origin, requestMethod); + assertThat(result.getStatus()).as(path + " " + origin).isEqualTo(HttpStatus.OK); + assertThat(result.getResponseHeaders().getAccessControlAllowOrigin()).as(path + " " + origin).isEqualTo(origin); + assertThat(result.getResponseHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).as(path + " " + origin).isEqualTo(TRUE); + } + + final void assertAllowedWithoutCredentials(String path, String origin, HttpMethod requestMethod) { + EntityExchangeResult result = preflight(path, origin, requestMethod); + assertThat(result.getStatus()).as(path + " " + origin).isEqualTo(HttpStatus.OK); + assertThat(result.getResponseHeaders().getAccessControlAllowOrigin()).as(path + " " + origin).isEqualTo(origin); + assertThat(result.getResponseHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).as(path + " " + origin).isNull(); + } + + final void assertRefused(String path, String origin, HttpMethod requestMethod) { + EntityExchangeResult result = preflight(path, origin, requestMethod); + assertThat(result.getStatus()).as(path + " " + origin).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(result.getResponseHeaders().getAccessControlAllowOrigin()).as(path + " " + origin).isNull(); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/AnonymousRoutesSecurityTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/AnonymousRoutesSecurityTest.java new file mode 100644 index 0000000000..fdfda6efb7 --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/AnonymousRoutesSecurityTest.java @@ -0,0 +1,129 @@ +package org.lowcoder.api.framework.security; + +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.lowcoder.api.authentication.request.AuthRequestFactory; +import org.lowcoder.api.authentication.service.AuthenticationApiServiceImpl; +import org.lowcoder.api.authentication.util.JWTUtils; +import org.lowcoder.api.home.SessionUserService; +import org.lowcoder.domain.authentication.AuthenticationService; +import org.lowcoder.domain.user.model.User; +import org.lowcoder.domain.user.service.UserService; +import org.lowcoder.sdk.config.CommonConfig; +import org.lowcoder.sdk.util.CookieHelper; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.ServerAuthenticationEntryPoint; +import org.springframework.security.web.server.WebFilterChainProxy; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +/** + * Pins D-12 (anonymous {@code POST /api/meta/}) and D-39 (anonymous actuator metrics/prometheus): both now require + * authentication, while {@code /api/status/health} and the unrelated {@code byuser} matcher (D-13, left unchanged) + * stay open to anonymous callers. + */ +class AnonymousRoutesSecurityTest { + + @RestController + static class TestController { + @PostMapping(org.lowcoder.infra.constant.Url.META_URL + "/") + Mono metaOld() { return Mono.just("ok"); } + @PostMapping(org.lowcoder.infra.constant.NewUrl.META_URL + "/") + Mono metaNew() { return Mono.just("ok"); } + @GetMapping(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/prometheus") + Mono prometheus() { return Mono.just("ok"); } + @GetMapping(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/metrics") + Mono metrics() { return Mono.just("ok"); } + @GetMapping(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/metrics/{metricName}") + Mono metricByName(@PathVariable String metricName) { return Mono.just("ok"); } + @GetMapping(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/health") + Mono health() { return Mono.just("ok"); } + @GetMapping(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/health/{component}") + Mono healthComponent(@PathVariable String component) { return Mono.just("ok"); } + @GetMapping(org.lowcoder.infra.constant.Url.ORGANIZATION_URL + "/byuser/{email}") + Mono byUser(@PathVariable String email) { return Mono.just("ok"); } + @GetMapping(org.lowcoder.infra.constant.NewUrl.ORGANIZATION_URL + "/byuser/{email}") + Mono byUserNew(@PathVariable String email) { return Mono.just("ok"); } + } + + private WebTestClient anonymousClient() { + var config = mock(CommonConfig.class, RETURNS_DEEP_STUBS); + when(config.getSecurity().getForbiddenEndpoints()).thenReturn(List.of()); + when(config.getSecurity().getAllCorsAllowedDomains()).thenReturn(List.of("https://trusted.test")); + var users = mock(SessionUserService.class); + when(users.resolveSessionUserFromCookie(nullable(String.class))).thenReturn(Mono.empty()); + var cookieHelper = mock(CookieHelper.class); + var entryPoint = mock(ServerAuthenticationEntryPoint.class); + when(entryPoint.commence(any(), any())).thenAnswer(invocation -> { + invocation.getArgument(0).getResponse() + .setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED); + return Mono.empty(); + }); + var security = new SecurityConfig(config, users, mock(UserService.class), mock(AccessDeniedHandler.class), + entryPoint, cookieHelper, mock(AuthenticationService.class), mock(AuthenticationApiServiceImpl.class), + mock(AuthRequestFactory.class), mock(JWTUtils.class)); + return WebTestClient.bindToController(new TestController()) + .webFilter(new WebFilterChainProxy(security.securityWebFilterChain( + ServerHttpSecurity.http().authenticationManager(authentication -> Mono.empty())))) + .build(); + } + + private WebTestClient authenticatedClient(String token) { + var config = mock(CommonConfig.class, RETURNS_DEEP_STUBS); + when(config.getSecurity().getForbiddenEndpoints()).thenReturn(List.of()); + when(config.getSecurity().getAllCorsAllowedDomains()).thenReturn(List.of("https://trusted.test")); + var users = mock(SessionUserService.class); + var cookieHelper = mock(CookieHelper.class); + when(cookieHelper.getCookieToken(any())).thenReturn(token); + User user = new User(); + user.setId("user1"); + when(users.resolveSessionUserFromCookie(token)).thenReturn(Mono.just(user)); + when(users.extendValidity(token)).thenReturn(Mono.empty()); + var security = new SecurityConfig(config, users, mock(UserService.class), mock(AccessDeniedHandler.class), + mock(ServerAuthenticationEntryPoint.class), cookieHelper, mock(AuthenticationService.class), + mock(AuthenticationApiServiceImpl.class), mock(AuthRequestFactory.class), mock(JWTUtils.class)); + return WebTestClient.bindToController(new TestController()) + .webFilter(new WebFilterChainProxy(security.securityWebFilterChain( + ServerHttpSecurity.http().authenticationManager(authentication -> Mono.empty())))) + .build(); + } + + @Test + void anonymousCallerIsRefusedMetaAndActuatorMetricsButHealthStaysOpen() { + var client = anonymousClient(); + client.post().uri(org.lowcoder.infra.constant.Url.META_URL + "/").exchange().expectStatus().isUnauthorized(); + client.post().uri(org.lowcoder.infra.constant.NewUrl.META_URL + "/").exchange().expectStatus().isUnauthorized(); + client.get().uri(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/prometheus").exchange().expectStatus().isUnauthorized(); + client.get().uri(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/metrics").exchange().expectStatus().isUnauthorized(); + client.get().uri(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/metrics/jvm.memory.used").exchange().expectStatus().isUnauthorized(); + + client.get().uri(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/health").exchange().expectStatus().isOk(); + client.get().uri(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/health/mongo").exchange().expectStatus().isOk(); + client.get().uri(org.lowcoder.infra.constant.Url.ORGANIZATION_URL + "/byuser/someone@example.com") + .exchange().expectStatus().isOk(); + client.get().uri(org.lowcoder.infra.constant.NewUrl.ORGANIZATION_URL + "/byuser/someone@example.com") + .exchange().expectStatus().isOk(); + } + + @Test + void authenticatedCallerReachesMetaAndActuatorMetrics() { + var client = authenticatedClient("tok"); + client.get().uri(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/health").exchange().expectStatus().isOk(); + client.post().uri(org.lowcoder.infra.constant.Url.META_URL + "/").exchange().expectStatus().isOk(); + client.post().uri(org.lowcoder.infra.constant.NewUrl.META_URL + "/").exchange().expectStatus().isOk(); + client.get().uri(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/prometheus").exchange().expectStatus().isOk(); + client.get().uri(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/metrics").exchange().expectStatus().isOk(); + client.get().uri(org.lowcoder.infra.constant.NewUrl.PREFIX + "/status/metrics/jvm.memory.used").exchange().expectStatus().isOk(); + client.get().uri(org.lowcoder.infra.constant.Url.ORGANIZATION_URL + "/byuser/someone@example.com") + .exchange().expectStatus().isOk(); + client.get().uri(org.lowcoder.infra.constant.NewUrl.ORGANIZATION_URL + "/byuser/someone@example.com") + .exchange().expectStatus().isOk(); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsAllowedDomainsPreflightTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsAllowedDomainsPreflightTest.java index 21267482db..750932821b 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsAllowedDomainsPreflightTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsAllowedDomainsPreflightTest.java @@ -26,8 +26,10 @@ * endpoint of the allow-list configuration ({@code /**}) under both {@code /api} and {@code /api/v1}; another origin is * refused with 403 and no allow header. Before the fix the second origin was refused. * - *

Limits: preflights only (an actual cross-origin request gets the same origin check from the same configuration); the - * endpoints that allow every origin ({@code SecurityConfig.buildCorsConfigurationSource}) are not exercised. + *

Limit: preflights only (an actual cross-origin request gets the same origin check from the same configuration). + * The paths that used to grant "any origin, with credentials" unconditionally are exercised by + * {@link CorsCredentialsListedOriginTest}, {@link CorsCredentialsWildcardOnlyTest}, + * {@link CorsCredentialsWildcardSubPatternTest} and {@link CorsCredentialsMixedConfigTest}. * Isolation: its own profile ({@code corsAllowedDomains}), so its own context and database. */ @SpringBootTest(properties = CorsAllowedDomainsPreflightTest.CORS_DOMAINS_PROPERTY + "=" + CorsAllowedDomainsPreflightTest.CORS_DOMAINS) diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsListedOriginTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsListedOriginTest.java new file mode 100644 index 0000000000..04bc73b7a3 --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsListedOriginTest.java @@ -0,0 +1,34 @@ +package org.lowcoder.api.framework.security; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +/** + * {@code corsAllowedDomainString=https://a.example}: a single listed, non-wildcard origin (case (b) of the + * credentials fix). It gets credentials everywhere; an unlisted origin gets no credentials on a former any-origin + * path and is refused outright on a path that was never one. + */ +@SpringBootTest(properties = AbstractCorsCredentialsTest.CORS_DOMAINS_PROPERTY + "=" + CorsCredentialsListedOriginTest.LISTED_ORIGIN) +@ActiveProfiles("corsCredentialsListedOrigin") +class CorsCredentialsListedOriginTest extends AbstractCorsCredentialsTest { + + static final String LISTED_ORIGIN = "https://a.example"; + private static final String UNLISTED_ORIGIN = "https://c.example"; + + @Test + void theListedOriginGetsCredentialsOnAFormerAnyOriginPathAndOnTheAllowList() { + assertAllowedWithCredentials(FORMER_ANY_ORIGIN_PATH, LISTED_ORIGIN, FORMER_ANY_ORIGIN_METHOD); + for (String path : ALLOW_LIST_PATHS) { + assertAllowedWithCredentials(path, LISTED_ORIGIN, ALLOW_LIST_METHOD); + } + } + + @Test + void anUnlistedOriginGetsNoCredentialsOnTheFormerAnyOriginPathAndIsRefusedOnTheAllowList() { + assertAllowedWithoutCredentials(FORMER_ANY_ORIGIN_PATH, UNLISTED_ORIGIN, FORMER_ANY_ORIGIN_METHOD); + for (String path : ALLOW_LIST_PATHS) { + assertRefused(path, UNLISTED_ORIGIN, ALLOW_LIST_METHOD); + } + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsMixedConfigTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsMixedConfigTest.java new file mode 100644 index 0000000000..38113d8ed7 --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsMixedConfigTest.java @@ -0,0 +1,38 @@ +package org.lowcoder.api.framework.security; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +/** + * {@code corsAllowedDomainString=*,https://a.example}: the critical case, proving the two branches (credentialed + * listed origin vs. any-origin-no-credentials) compose correctly in ONE configuration, not just in isolation. The + * listed origin gets credentials everywhere, exactly as in {@link CorsCredentialsListedOriginTest}; an unlisted + * origin gets a 200 without credentials EVERYWHERE too (the literal {@code "*"} entry covers every path when + * present, not only the former any-origin paths) — not a 403, unlike that same test's unlisted origin, because the + * {@code "*"} entry is present in this mixed configuration. + */ +@SpringBootTest(properties = AbstractCorsCredentialsTest.CORS_DOMAINS_PROPERTY + "=" + CorsCredentialsMixedConfigTest.MIXED_DOMAINS) +@ActiveProfiles("corsCredentialsMixedConfig") +class CorsCredentialsMixedConfigTest extends AbstractCorsCredentialsTest { + + static final String LISTED_ORIGIN = "https://a.example"; + static final String MIXED_DOMAINS = "*," + LISTED_ORIGIN; + private static final String UNLISTED_ORIGIN = "https://evil.example"; + + @Test + void theListedOriginGetsCredentialsEverywhereEvenWithTheWildcardAlsoConfigured() { + assertAllowedWithCredentials(FORMER_ANY_ORIGIN_PATH, LISTED_ORIGIN, FORMER_ANY_ORIGIN_METHOD); + for (String path : ALLOW_LIST_PATHS) { + assertAllowedWithCredentials(path, LISTED_ORIGIN, ALLOW_LIST_METHOD); + } + } + + @Test + void anUnlistedOriginGetsNoCredentialsEverywhereButIsNotRefusedBecauseOfTheWildcard() { + assertAllowedWithoutCredentials(FORMER_ANY_ORIGIN_PATH, UNLISTED_ORIGIN, FORMER_ANY_ORIGIN_METHOD); + for (String path : ALLOW_LIST_PATHS) { + assertAllowedWithoutCredentials(path, UNLISTED_ORIGIN, ALLOW_LIST_METHOD); + } + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsWildcardOnlyTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsWildcardOnlyTest.java new file mode 100644 index 0000000000..dcc83406dc --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsWildcardOnlyTest.java @@ -0,0 +1,22 @@ +package org.lowcoder.api.framework.security; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +/** + * {@code corsAllowedDomainString=*}: the shipped default. Every cross-origin answer stays non-credentialed, so a + * browser on another origin cannot read a credentialed answer (case (a) of the credentials fix). + */ +@SpringBootTest(properties = AbstractCorsCredentialsTest.CORS_DOMAINS_PROPERTY + "=*") +@ActiveProfiles("corsCredentialsWildcardOnly") +class CorsCredentialsWildcardOnlyTest extends AbstractCorsCredentialsTest { + + private static final String UNLISTED_ORIGIN = "https://evil.example"; + + @Test + void anyOriginGetsNoCredentialsOnTheFormerAnyOriginPaths() { + assertAllowedWithoutCredentials(FORMER_ANY_ORIGIN_PATH, UNLISTED_ORIGIN, FORMER_ANY_ORIGIN_METHOD); + assertAllowedWithoutCredentials(FORMER_ANY_ORIGIN_PATH_QUERY, UNLISTED_ORIGIN, FORMER_ANY_ORIGIN_QUERY_METHOD); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsWildcardSubPatternTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsWildcardSubPatternTest.java new file mode 100644 index 0000000000..11708edab8 --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/framework/security/CorsCredentialsWildcardSubPatternTest.java @@ -0,0 +1,36 @@ +package org.lowcoder.api.framework.security; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +/** + * {@code corsAllowedDomainString=https://*.example.com}: a wildcard SUB-pattern entry (case (c) of the credentials + * fix), as opposed to the standalone {@code "*"} entry of {@link CorsCredentialsWildcardOnlyTest}. A matching + * origin counts as listed and gets credentials everywhere, exactly like {@link CorsCredentialsListedOriginTest}; + * a non-matching origin is treated the same as that test's unlisted origin. + */ +@SpringBootTest(properties = AbstractCorsCredentialsTest.CORS_DOMAINS_PROPERTY + "=" + CorsCredentialsWildcardSubPatternTest.PATTERN) +@ActiveProfiles("corsCredentialsWildcardSubPattern") +class CorsCredentialsWildcardSubPatternTest extends AbstractCorsCredentialsTest { + + static final String PATTERN = "https://*.example.com"; + private static final String MATCHING_ORIGIN = "https://sub.example.com"; + private static final String NON_MATCHING_ORIGIN = "https://sub.other.com"; + + @Test + void aMatchingSubdomainGetsCredentialsOnAFormerAnyOriginPathAndOnTheAllowList() { + assertAllowedWithCredentials(FORMER_ANY_ORIGIN_PATH, MATCHING_ORIGIN, FORMER_ANY_ORIGIN_METHOD); + for (String path : ALLOW_LIST_PATHS) { + assertAllowedWithCredentials(path, MATCHING_ORIGIN, ALLOW_LIST_METHOD); + } + } + + @Test + void aNonMatchingOriginGetsNoCredentialsOnTheFormerAnyOriginPathAndIsRefusedOnTheAllowList() { + assertAllowedWithoutCredentials(FORMER_ANY_ORIGIN_PATH, NON_MATCHING_ORIGIN, FORMER_ANY_ORIGIN_METHOD); + for (String path : ALLOW_LIST_PATHS) { + assertRefused(path, NON_MATCHING_ORIGIN, ALLOW_LIST_METHOD); + } + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderApiServiceImplTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderApiServiceImplTest.java index df2dd6c108..cbd3e0cb30 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderApiServiceImplTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderApiServiceImplTest.java @@ -26,6 +26,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import org.lowcoder.api.application.view.ApplicationInfoView; @@ -43,6 +44,7 @@ import org.lowcoder.domain.organization.model.OrgMember; import org.lowcoder.domain.organization.model.Organization; import org.lowcoder.domain.organization.service.OrganizationService; +import org.lowcoder.domain.organization.service.OrgMemberService; import org.lowcoder.domain.permission.model.ResourceAction; import org.lowcoder.domain.permission.model.ResourcePermission; import org.lowcoder.domain.permission.model.ResourceRole; @@ -90,6 +92,7 @@ class FolderApiServiceImplTest { private UserService userService; private OrganizationService organizationService; private UserFolderInteractionService interactionService; + private OrgMemberService orgMemberService; private FolderApiServiceImpl service; @BeforeEach @@ -104,9 +107,10 @@ void setUp() { userService = mock(UserService.class); organizationService = mock(OrganizationService.class); interactionService = mock(UserFolderInteractionService.class); + orgMemberService = mock(OrgMemberService.class); service = new FolderApiServiceImpl(folderService, sessionUserService, orgDevChecker, userHomeApiService, relationService, permissionService, permissionHelper, mock(GroupService.class), userService, - organizationService, interactionService); + organizationService, interactionService, orgMemberService); signedInAs(MemberRole.MEMBER); when(orgDevChecker.checkCurrentOrgDev()).thenReturn(Mono.empty()); @@ -114,6 +118,7 @@ relationService, permissionService, permissionHelper, mock(GroupService.class), when(folderService.findByOrganizationId(anyString())).thenReturn(Flux.empty()); when(folderService.create(any(Folder.class))).thenAnswer(invocation -> Mono.just(invocation.getArgument(0))); when(userService.findById(anyString())).thenAnswer(invocation -> Mono.just(user(invocation.getArgument(0)))); + when(orgMemberService.getOrgMember(anyString(), anyString())).thenReturn(Mono.empty()); } // ----------------------------------------------------------------- fixtures @@ -124,6 +129,44 @@ private void signedInAs(MemberRole role) { when(sessionUserService.getVisitorId()).thenReturn(Mono.just(VISITOR)); } + private void memberOf(String org, MemberRole role) { + when(orgMemberService.getOrgMember(org, VISITOR)) + .thenReturn(Mono.just(OrgMember.builder().orgId(org).userId(VISITOR).role(role).build())); + } + + /** Flags for {@code getPermissions}: whether the rows, the group view, the user view and the organization were read. */ + private record PermissionViewStubs(AtomicBoolean rowsRead, AtomicBoolean groupsBuilt, AtomicBoolean usersBuilt, + AtomicBoolean orgRead, PermissionItemView groupItem, PermissionItemView userItem) { + } + + private PermissionViewStubs permissionViewStubs() { + AtomicBoolean rowsRead = new AtomicBoolean(); + AtomicBoolean groupsBuilt = new AtomicBoolean(); + AtomicBoolean usersBuilt = new AtomicBoolean(); + AtomicBoolean orgRead = new AtomicBoolean(); + PermissionItemView groupItem = mock(PermissionItemView.class); + PermissionItemView userItem = mock(PermissionItemView.class); + Organization organization = new Organization(); + organization.setName("Acme"); + when(permissionService.getByResourceTypeAndResourceId(eq(ResourceType.FOLDER), anyString())) + .thenReturn(flagged(rowsRead, List.of())); + when(permissionHelper.getGroupPermissions(anyList())).thenReturn(flagged(groupsBuilt, List.of(groupItem))); + when(permissionHelper.getUserPermissions(anyList())).thenReturn(flagged(usersBuilt, List.of(userItem))); + when(organizationService.getById(anyString())).thenReturn(flagged(orgRead, organization)); + return new PermissionViewStubs(rowsRead, groupsBuilt, usersBuilt, orgRead, groupItem, userItem); + } + + private void assertNothingOfTheListWasRead(PermissionViewStubs stubs) { + assertThat(stubs.rowsRead()).isFalse(); + assertThat(stubs.groupsBuilt()).isFalse(); + assertThat(stubs.usersBuilt()).isFalse(); + assertThat(stubs.orgRead()).isFalse(); + verify(permissionService, never()).getByResourceTypeAndResourceId(any(), any()); + verify(permissionHelper, never()).getGroupPermissions(anyList()); + verify(permissionHelper, never()).getUserPermissions(anyList()); + verify(organizationService, never()).getById(anyString()); + } + private static User user(String id) { User user = new User(); user.setId(id); @@ -904,27 +947,97 @@ void updateAndRemovePermission_requireManagePermission() { assertThat(mutated).isFalse(); } - @Test - void getPermissions_assemblesTheViewFromTheFolderItsPermissionsAndTheOrg() { + /** Catches D-8: any signed-in user reading any folder's permission list. A member of the folder's workspace, in any + * role, still gets the view. */ + @ParameterizedTest + @EnumSource(MemberRole.class) + void getPermissions_memberOfTheFolderWorkspace_inAnyRole_getsTheView(MemberRole role) { when(folderService.findById("f1")).thenReturn(Mono.just(folder("f1", ORG, null, "f1", OTHER_USER))); - when(folderService.findById("ghost")).thenReturn(Mono.empty()); - when(permissionService.getByResourceTypeAndResourceId(ResourceType.FOLDER, "f1")).thenReturn(Mono.just(List.of())); - PermissionItemView groupItem = mock(PermissionItemView.class); - PermissionItemView userItem = mock(PermissionItemView.class); - when(permissionHelper.getGroupPermissions(anyList())).thenReturn(Mono.just(List.of(groupItem))); - when(permissionHelper.getUserPermissions(anyList())).thenReturn(Mono.just(List.of(userItem))); - Organization organization = new Organization(); - organization.setName("Acme"); - when(organizationService.getById(ORG)).thenReturn(Mono.just(organization)); + memberOf(ORG, role); + PermissionViewStubs stubs = permissionViewStubs(); StepVerifier.create(service.getPermissions("f1")).assertNext(view -> { assertThat(view.getCreatorId()).isEqualTo(OTHER_USER); assertThat(view.getOrgName()).isEqualTo("Acme"); - assertThat(view.getGroupPermissions()).containsExactly(groupItem); - assertThat(view.getUserPermissions()).containsExactly(userItem); + assertThat(view.getGroupPermissions()).containsExactly(stubs.groupItem()); + assertThat(view.getUserPermissions()).containsExactly(stubs.userItem()); }).verifyComplete(); - when(permissionService.getByResourceTypeAndResourceId(ResourceType.FOLDER, "ghost")).thenReturn(Mono.just(List.of())); - StepVerifier.create(service.getPermissions("ghost")).verifyComplete(); + assertThat(stubs.rowsRead()).isTrue(); + assertThat(stubs.groupsBuilt()).isTrue(); + assertThat(stubs.usersBuilt()).isTrue(); + assertThat(stubs.orgRead()).isTrue(); + verify(orgMemberService).getOrgMember(ORG, VISITOR); + System.out.println("[FolderApiServiceImplTest] getPermissions, member of the folder workspace as " + role + ": gets the view"); + } + + /** Catches the check reading the visitor's CURRENT workspace membership instead of the folder's workspace. */ + @Test + void getPermissions_memberOfTheFolderWorkspaceThatIsNotCurrent_getsTheView() { + signedInAs(MemberRole.MEMBER); + when(folderService.findById("f9")).thenReturn(Mono.just(folder("f9", OTHER_ORG, null, "f9", OTHER_USER))); + memberOf(OTHER_ORG, MemberRole.MEMBER); + PermissionViewStubs stubs = permissionViewStubs(); + + StepVerifier.create(service.getPermissions("f9")).assertNext(view -> { + assertThat(view.getCreatorId()).isEqualTo(OTHER_USER); + assertThat(view.getOrgName()).isEqualTo("Acme"); + }).verifyComplete(); + verify(organizationService).getById(OTHER_ORG); + verify(orgMemberService).getOrgMember(OTHER_ORG, VISITOR); + verify(sessionUserService, never()).getVisitorOrgMemberCache(); + System.out.println("[FolderApiServiceImplTest] getPermissions, member of a workspace that is not current: gets the view"); + } + + /** Catches D-8 itself: a non-member of the folder's workspace reading the list. */ + @Test + void getPermissions_nonMemberOfTheFolderWorkspace_isNotAuthorized_andReadsNothingOfTheList() { + signedInAs(MemberRole.MEMBER); + when(folderService.findById("f9")).thenReturn(Mono.just(folder("f9", OTHER_ORG, null, "f9", OTHER_USER))); + PermissionViewStubs stubs = permissionViewStubs(); + + StepVerifier.create(service.getPermissions("f9")) + .expectErrorSatisfies(error -> { + assertThat(error).isInstanceOf(BizException.class); + assertThat(((BizException) error).getError()).isEqualTo(BizError.NOT_AUTHORIZED); + assertThat(((BizException) error).getMessageKey()).isEqualTo("NOT_AUTHORIZED"); + }) + .verify(); + assertNothingOfTheListWasRead(stubs); + System.out.println("[FolderApiServiceImplTest] getPermissions, non-member of the folder workspace: NOT_AUTHORIZED, nothing read"); + } + + /** Catches an empty visitor id reaching the membership lookup or the list. */ + @Test + void getPermissions_withoutAVisitor_isNotAuthorized_andReadsNothingOfTheList() { + when(sessionUserService.getVisitorId()).thenReturn(Mono.empty()); + when(folderService.findById("f1")).thenReturn(Mono.just(folder("f1", ORG, null, "f1", OTHER_USER))); + PermissionViewStubs stubs = permissionViewStubs(); + + StepVerifier.create(service.getPermissions("f1")) + .expectErrorSatisfies(error -> { + assertThat(error).isInstanceOf(BizException.class); + assertThat(((BizException) error).getError()).isEqualTo(BizError.NOT_AUTHORIZED); + }) + .verify(); + verify(orgMemberService, never()).getOrgMember(any(), any()); + assertNothingOfTheListWasRead(stubs); + System.out.println("[FolderApiServiceImplTest] getPermissions, no visitor: NOT_AUTHORIZED, nothing read"); + } + + /** Catches the folder-not-found error being normalized or swallowed instead of passed through unchanged. */ + @Test + void getPermissions_ofAnUnknownObjectId_passesTheFolderNotFoundErrorThrough_andChecksNothingElse() { + BizException notFound = new BizException(BizError.NO_RESOURCE_FOUND, "FOLDER_NOT_FOUND", "ghost"); + when(folderService.findById("ghost")).thenReturn(Mono.error(notFound)); + PermissionViewStubs stubs = permissionViewStubs(); + + StepVerifier.create(service.getPermissions("ghost")) + .expectErrorSatisfies(error -> assertThat(error).isSameAs(notFound)) + .verify(); + verify(sessionUserService, never()).getVisitorId(); + verify(orgMemberService, never()).getOrgMember(any(), any()); + assertNothingOfTheListWasRead(stubs); + System.out.println("[FolderApiServiceImplTest] getPermissions, unknown object id: the FOLDER_NOT_FOUND error passes through unchanged"); } // ------------------------------------------------------------ view building diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderPermissionListThroughTheStackTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderPermissionListThroughTheStackTest.java new file mode 100644 index 0000000000..a5225f23d0 --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/FolderPermissionListThroughTheStackTest.java @@ -0,0 +1,208 @@ +package org.lowcoder.api.home; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; + +import java.lang.reflect.Constructor; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lowcoder.api.framework.view.ResponseView; +import org.lowcoder.api.permission.PermissionHelper; +import org.lowcoder.api.util.BusinessEventPublisher; +import org.lowcoder.api.util.GidService; +import org.lowcoder.domain.folder.model.Folder; +import org.lowcoder.domain.folder.repository.FolderRepository; +import org.lowcoder.domain.folder.service.FolderElementRelationService; +import org.lowcoder.domain.folder.service.FolderService; +import org.lowcoder.domain.folder.service.FolderServiceImpl; +import org.lowcoder.domain.organization.model.Organization; +import org.lowcoder.domain.organization.model.OrgMember; +import org.lowcoder.domain.organization.service.OrgMemberService; +import org.lowcoder.domain.permission.model.ResourcePermission; +import org.lowcoder.domain.permission.service.ResourcePermissionService; +import org.lowcoder.infra.constant.NewUrl; +import org.lowcoder.infra.mongo.MongoUpsertHelper; +import org.lowcoder.sdk.exception.BizError; +import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * {@code GET /api/folders/{folderId}/permissions} through the real controller, {@code GidService}, {@link + * FolderApiServiceImpl} and {@link FolderServiceImpl} (D-8): a member of the folder's workspace reads the list, by + * object id and by gid; a non-member gets NOT_AUTHORIZED, with none of the permission rows, the group or user view or + * the organization read; an unknown object id still answers NO_RESOURCE_FOUND, unchanged. The unknown-gid answer + * (FOLDER_NOT_EXIST before this method ever runs, BF-158) stays pinned by {@link FolderUnknownGidOperationsProbeTest}. + * Wiring follows {@link FolderUnknownGidOperationsProbeTest#wire()}. + */ +class FolderPermissionListThroughTheStackTest { + + private static final String TAG = "[FolderPermissionListThroughTheStackTest] "; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String FOREIGN_ORG = "org-of-the-folder"; + private static final String VISITOR = "visitor-id"; + private static final String CREATOR = "creator-user-id"; + private static final String KNOWN_ID = "65a1b2c3d4e5f60718293a0f"; + private static final String KNOWN_GID = "0190aaaa-bbbb-7ccc-8ddd-eeeeeeeeeeee"; + private static final String UNKNOWN_ID = "65a1b2c3d4e5f60718293aff"; + + private org.lowcoder.api.contract.support.ContractTestClient client; + private FolderApiServiceImpl folderApiService; + private FolderService folderService; + private FolderRepository folderRepository; + private ResourcePermissionService permissions; + private SessionUserService session; + private PermissionHelper helper; + private org.lowcoder.domain.organization.service.OrganizationService organizations; + private OrgMemberService orgMembers; + + @BeforeEach + void wire() { + org.lowcoder.api.contract.support.ContractTestClient.Builder builder = org.lowcoder.api.contract.support.ContractTestClient.builder(); + folderRepository = Mockito.mock(FolderRepository.class); + Folder folder = new Folder(); + ReflectionTestUtils.setField(folder, "id", KNOWN_ID); + folder.setOrganizationId(FOREIGN_ORG); + folder.setCreatedBy(CREATOR); + folder.setGid(KNOWN_GID); + Mockito.when(folderRepository.findById(KNOWN_ID)).thenReturn(Mono.just(folder)); + Mockito.when(folderRepository.findByGid(KNOWN_GID)).thenReturn(Flux.just(folder)); + Mockito.when(folderRepository.findByGid(Mockito.argThat(gid -> gid == null || !gid.equals(KNOWN_GID)))).thenReturn(Flux.empty()); + Mockito.when(folderRepository.findById(UNKNOWN_ID)).thenReturn(Mono.empty()); + GidService gidService = new GidService(); + ReflectionTestUtils.setField(gidService, "folderRepository", folderRepository); + builder.singleton("gidService", gidService); + folderService = new FolderServiceImpl(folderRepository, Mockito.mock(MongoUpsertHelper.class)); + builder.singleton("folderService", folderService); + + Constructor widest = Arrays.stream(FolderApiServiceImpl.class.getDeclaredConstructors()) + .max(Comparator.comparingInt(Constructor::getParameterCount)).orElseThrow(); + Object[] collaborators = Arrays.stream(widest.getParameterTypes()) + .map(type -> type == FolderService.class ? folderService : builder.mock(type)).toArray(); + try { + folderApiService = (FolderApiServiceImpl) widest.newInstance(collaborators); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("cannot build FolderApiServiceImpl", e); + } + builder.singleton("folderApiService", folderApiService); + permissions = builder.mock(ResourcePermissionService.class); + session = builder.mock(SessionUserService.class); + helper = builder.mock(PermissionHelper.class); + organizations = builder.mock(org.lowcoder.domain.organization.service.OrganizationService.class); + orgMembers = builder.mock(OrgMemberService.class); + builder.mock(BusinessEventPublisher.class); + builder.mock(FolderElementRelationService.class); + + builder.visitor(VISITOR, Mockito.mock(OrgMember.class)); + Mockito.when(permissions.getByResourceTypeAndResourceId(any(), any())).thenReturn(Mono.just(List.of())); + Mockito.when(helper.getGroupPermissions(any())).thenReturn(Mono.just(List.of())); + Mockito.when(helper.getUserPermissions(any())).thenReturn(Mono.just(List.of())); + Organization foreign = new Organization(); + foreign.setName("Foreign"); + Mockito.when(organizations.getById(FOREIGN_ORG)).thenReturn(Mono.just(foreign)); + + builder.controller(FolderController.class); + builder.mock(org.lowcoder.api.application.ApplicationApiService.class); + client = builder.build(); + System.out.println(TAG + "wired: real controller, GidService, FolderApiServiceImpl and FolderServiceImpl"); + } + + @AfterEach + void close() { + client.close(); + } + + /** Guards the wiring: the stubs the observations depend on are the objects the service and the controller use. */ + @Test + void theWiringReachedTheCollaboratorsTheTestsRelyOn() { + assertSame(orgMembers, ReflectionTestUtils.getField(folderApiService, "orgMemberService")); + assertSame(permissions, ReflectionTestUtils.getField(folderApiService, "resourcePermissionService")); + assertSame(session, ReflectionTestUtils.getField(folderApiService, "sessionUserService")); + assertSame(helper, ReflectionTestUtils.getField(folderApiService, "permissionHelper")); + assertSame(organizations, ReflectionTestUtils.getField(folderApiService, "organizationService")); + assertTrue(ReflectionTestUtils.getField(folderApiService, "folderService") instanceof FolderServiceImpl); + System.out.println(TAG + "wiring reached orgMembers, permissions, session, helper, organizations and the real folder service"); + } + + private record Outcome(int status, int code) { + } + + private Outcome call(String label, String path) { + var spec = client.web().method(org.springframework.http.HttpMethod.GET).uri(path); + EntityExchangeResult result = spec.exchange().expectBody().returnResult(); + try { + JsonNode json = JSON.readTree(result.getResponseBody()); + Outcome outcome = new Outcome(result.getStatus().value(), json.get("code").asInt()); + System.out.println(TAG + label + " -> " + outcome + " " + json); + return outcome; + } catch (java.io.IOException e) { + throw new IllegalStateException("response is not JSON", e); + } + } + + private String permissionsPath(String folderKey) { + return NewUrl.FOLDER_URL + "/" + folderKey + "/permissions"; + } + + private String body(String folderKey) { + return new String(client.web().method(org.springframework.http.HttpMethod.GET).uri(permissionsPath(folderKey)) + .exchange().expectBody().returnResult().getResponseBody()); + } + + /** D-8, positive control: a member of the folder's workspace reads the list, by object id and by gid. */ + @Test + void aMemberOfTheFolderWorkspaceReadsTheListByObjectIdAndByGidD8() { + Mockito.when(orgMembers.getOrgMember(FOREIGN_ORG, VISITOR)) + .thenReturn(Mono.just(OrgMember.builder().orgId(FOREIGN_ORG).userId(VISITOR).role(org.lowcoder.domain.organization.model.MemberRole.MEMBER).build())); + + for (String key : List.of(KNOWN_ID, KNOWN_GID)) { + Outcome outcome = call("member by " + key, permissionsPath(key)); + assertEquals(new Outcome(200, ResponseView.SUCCESS), outcome); + String json = body(key); + assertTrue(json.contains(CREATOR), "body carries the creator id"); + } + System.out.println(TAG + "a member of the folder workspace reads the list by object id and by gid"); + } + + /** D-8 itself: a non-member of the folder's workspace is refused, and nothing of the list is read. */ + @Test + void aNonMemberGetsNotAuthorizedByObjectIdAndByGidAndNoRowIsReadD8() { + Mockito.when(orgMembers.getOrgMember(FOREIGN_ORG, VISITOR)).thenReturn(Mono.empty()); + + for (String key : List.of(KNOWN_ID, KNOWN_GID)) { + Outcome outcome = call("non-member by " + key, permissionsPath(key)); + assertEquals(new Outcome(BizError.NOT_AUTHORIZED.getHttpErrorCode(), BizError.NOT_AUTHORIZED.getBizErrorCode()), outcome); + String json = body(key); + assertFalse(json.contains(CREATOR), "the creator id does not leak"); + assertFalse(json.contains("Foreign"), "the workspace name does not leak"); + } + Mockito.verify(permissions, Mockito.never()).getByResourceTypeAndResourceId(any(), any()); + Mockito.verify(helper, Mockito.never()).getGroupPermissions(any()); + Mockito.verify(helper, Mockito.never()).getUserPermissions(any()); + Mockito.verify(organizations, Mockito.never()).getById(any()); + System.out.println(TAG + "a non-member is refused by object id and by gid, and nothing of the list is read"); + } + + /** An unknown object id still answers NO_RESOURCE_FOUND, unchanged by this phase. */ + @Test + void anUnknownObjectIdStillAnswersNoResourceFoundD8() { + Outcome outcome = call("unknown object id", permissionsPath(UNKNOWN_ID)); + + assertEquals(new Outcome(BizError.NO_RESOURCE_FOUND.getHttpErrorCode(), BizError.NO_RESOURCE_FOUND.getBizErrorCode()), outcome); + Mockito.verify(orgMembers, Mockito.never()).getOrgMember(any(), any()); + Mockito.verify(permissions, Mockito.never()).getByResourceTypeAndResourceId(any(), any()); + System.out.println(TAG + "an unknown object id still answers NO_RESOURCE_FOUND; the membership check never runs"); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/SessionUserServiceImplEndSessionsTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/SessionUserServiceImplEndSessionsTest.java new file mode 100644 index 0000000000..45c793590e --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/home/SessionUserServiceImplEndSessionsTest.java @@ -0,0 +1,234 @@ +package org.lowcoder.api.home; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.lowcoder.api.usermanagement.UserApiService; +import org.lowcoder.domain.organization.service.OrgMemberService; +import org.lowcoder.domain.user.model.Connection; +import org.lowcoder.domain.user.model.User; +import org.lowcoder.domain.user.service.UserService; +import org.lowcoder.sdk.config.CommonConfig; +import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.data.redis.core.ReactiveValueOperations; +import org.springframework.test.util.ReflectionTestUtils; + +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** + * Unit tests of {@link SessionUserServiceImpl#endSessionsOfUser} (D-34): the sweep that ends every session of a + * user except an optionally kept one, used by a password change, a lost-password reset and an ENTERPRISE admin + * reset. A mocked {@code ReactiveValueOperations} and {@code UserApiService} stand in for Redis and the Mongo + * token-list cleanup; {@code events} records {@code delete:} and {@code removeToken:} on + * subscription, so ordering is observable. + */ +@ExtendWith(MockitoExtension.class) +class SessionUserServiceImplEndSessionsTest { + + private static final String USER_ID = "user-1"; + private static final String T1 = "token-1"; + private static final String T2 = "token-2"; + private static final String KEEP = "token-keep"; + + @Mock private UserService userService; + @Mock private OrgMemberService orgMemberService; + @Mock private UserApiService userApiService; + @Mock private ReactiveRedisTemplate reactiveTemplate; + @Mock private ReactiveValueOperations ops; + + private SessionUserServiceImpl service; + private final List events = new ArrayList<>(); + + @BeforeEach + void setUp() { + service = new SessionUserServiceImpl(); + ReflectionTestUtils.setField(service, "commonConfig", new CommonConfig()); + ReflectionTestUtils.setField(service, "userService", userService); + ReflectionTestUtils.setField(service, "orgMemberService", orgMemberService); + ReflectionTestUtils.setField(service, "userApiService", userApiService); + ReflectionTestUtils.setField(service, "reactiveTemplate", reactiveTemplate); + lenient().when(reactiveTemplate.opsForValue()).thenReturn(ops); + } + + private static User userWithTokens() { + Connection email = Connection.builder().source("EMAIL").rawId(USER_ID).tokens(Set.of(T1, KEEP)).build(); + Connection google = Connection.builder().source("GOOGLE").rawId(USER_ID).tokens(new HashSet<>(Set.of(T2))).build(); + return User.builder().id(USER_ID).connections(Set.of(email, google)).build(); + } + + private void stubDelete(String token) { + when(ops.delete(token)).thenReturn(Mono.fromSupplier(() -> { + events.add("delete:" + token); + return true; + })); + } + + private void stubRemoveToken(String token) { + when(userApiService.removeToken(USER_ID, token)).thenReturn(Mono.fromRunnable(() -> events.add("removeToken:" + token))); + } + + private static void assertBizError(Throwable throwable, BizError expected, String messageKey) { + assertThat(throwable).isInstanceOf(BizException.class); + BizException biz = (BizException) throwable; + assertThat(biz.getError()).isEqualTo(expected); + assertThat(biz.getMessageKey()).isEqualTo(messageKey); + } + + @Test + void endSessionsOfUser_keepsOnlyTheKeptToken_deletesThenRemovesEveryOther() { + when(userService.findById(USER_ID)).thenReturn(Mono.just(userWithTokens())); + stubDelete(T1); + stubDelete(T2); + stubRemoveToken(T1); + stubRemoveToken(T2); + + StepVerifier.create(service.endSessionsOfUser(USER_ID, KEEP)).verifyComplete(); + + verify(ops).delete(T1); + verify(ops).delete(T2); + verify(ops, never()).delete(KEEP); + verify(userApiService).removeToken(USER_ID, T1); + verify(userApiService).removeToken(USER_ID, T2); + verify(userApiService, never()).removeToken(USER_ID, KEEP); + assertThat(events.indexOf("delete:" + T1)).isLessThan(events.indexOf("removeToken:" + T1)); + assertThat(events.indexOf("delete:" + T2)).isLessThan(events.indexOf("removeToken:" + T2)); + verify(ops, never()).get(anyString()); + System.out.println("[SessionUserServiceImplEndSessionsTest] keep=" + KEEP + " events=" + events); + } + + @ParameterizedTest + @NullAndEmptySource + void endSessionsOfUser_nullOrBlankKeep_endsEverySession(String keep) { + when(userService.findById(USER_ID)).thenReturn(Mono.just(userWithTokens())); + stubDelete(T1); + stubDelete(T2); + stubDelete(KEEP); + stubRemoveToken(T1); + stubRemoveToken(T2); + stubRemoveToken(KEEP); + + StepVerifier.create(service.endSessionsOfUser(USER_ID, keep)).verifyComplete(); + + verify(ops).delete(T1); + verify(ops).delete(T2); + verify(ops).delete(KEEP); + verify(userApiService).removeToken(USER_ID, T1); + verify(userApiService).removeToken(USER_ID, T2); + verify(userApiService).removeToken(USER_ID, KEEP); + System.out.println("[SessionUserServiceImplEndSessionsTest] keep='" + keep + "' -> every token ended"); + } + + @Test + void endSessionsOfUser_keyAlreadyGone_isNotAnError() { + when(userService.findById(USER_ID)).thenReturn(Mono.just(userWithTokens())); + when(ops.delete(T1)).thenReturn(Mono.just(false)); + stubDelete(T2); + stubRemoveToken(T1); + stubRemoveToken(T2); + + StepVerifier.create(service.endSessionsOfUser(USER_ID, KEEP)).verifyComplete(); + + verify(userApiService).removeToken(USER_ID, T1); + System.out.println("[SessionUserServiceImplEndSessionsTest] delete(T1) false (already gone) -> not an error, still removed"); + } + + @Test + void endSessionsOfUser_redisFailsOnce_retriesAndSucceeds() { + when(userService.findById(USER_ID)).thenReturn(Mono.just(userWithTokens())); + AtomicInteger t1Attempts = new AtomicInteger(); + // retry() resubscribes to the Mono ops.delete(T1) already returned, so a plain Mono.error would fail every + // retry too; Mono.defer re-evaluates the supplier on every subscription, so each retry counts a fresh attempt. + when(ops.delete(T1)).thenReturn(Mono.defer(() -> { + int attempt = t1Attempts.incrementAndGet(); + if (attempt == 1) { + return Mono.error(new RuntimeException("transient redis error")); + } + return Mono.just(true); + })); + stubDelete(T2); + stubRemoveToken(T1); + stubRemoveToken(T2); + + StepVerifier.create(service.endSessionsOfUser(USER_ID, KEEP)).verifyComplete(); + + assertThat(t1Attempts.get()).isEqualTo(2); + verify(userApiService).removeToken(USER_ID, T1); + System.out.println("[SessionUserServiceImplEndSessionsTest] T1 failed once, retried, attempts=" + t1Attempts.get()); + } + + @Test + void endSessionsOfUser_redisFailsTwice_triesTheRestAndFails() { + when(userService.findById(USER_ID)).thenReturn(Mono.just(userWithTokens())); + AtomicInteger t1Attempts = new AtomicInteger(); + when(ops.delete(T1)).thenReturn(Mono.defer(() -> { + t1Attempts.incrementAndGet(); + return Mono.error(new RuntimeException("persistent redis error")); + })); + stubDelete(T2); + stubDelete(KEEP); + stubRemoveToken(T2); + stubRemoveToken(KEEP); + + StepVerifier.create(service.endSessionsOfUser(USER_ID, null)) + .expectErrorSatisfies(error -> { + assertBizError(error, BizError.PASSWORD_CHANGED_SESSIONS_NOT_ENDED, "PASSWORD_CHANGED_SESSIONS_NOT_ENDED"); + assertThat(((BizException) error).getArgs()).as("the number of sessions that could not be ended").containsExactly(1); + }) + .verify(); + + assertThat(t1Attempts.get()).isEqualTo(2); + verify(ops).delete(T2); + verify(ops).delete(KEEP); + verify(userApiService).removeToken(USER_ID, T2); + verify(userApiService).removeToken(USER_ID, KEEP); + verify(userApiService, never()).removeToken(USER_ID, T1); + System.out.println("[SessionUserServiceImplEndSessionsTest] T1 failed twice -> PASSWORD_CHANGED_SESSIONS_NOT_ENDED; T2 and KEEP still ended"); + } + + @Test + void endSessionsOfUser_mongoCleanupFails_stillCompletes() { + when(userService.findById(USER_ID)).thenReturn(Mono.just(userWithTokens())); + stubDelete(T1); + stubDelete(T2); + when(userApiService.removeToken(USER_ID, T1)).thenReturn(Mono.error(new RuntimeException("mongo down"))); + stubRemoveToken(T2); + + StepVerifier.create(service.endSessionsOfUser(USER_ID, KEEP)).verifyComplete(); + + verify(ops).delete(T1); + verify(ops).delete(T2); + System.out.println("[SessionUserServiceImplEndSessionsTest] mongo cleanup failed for T1 -> still completes, both tokens deleted from redis"); + } + + @Test + void endSessionsOfUser_unknownUser_completesWithoutRedis() { + when(userService.findById(USER_ID)).thenReturn(Mono.empty()); + + StepVerifier.create(service.endSessionsOfUser(USER_ID, KEEP)).verifyComplete(); + + verifyNoInteractions(ops, userApiService); + System.out.println("[SessionUserServiceImplEndSessionsTest] unknown user -> completes, no redis or mongo call"); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/npm/PrivateNpmRegistryControllerPermissionTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/npm/PrivateNpmRegistryControllerPermissionTest.java new file mode 100644 index 0000000000..b5e365464a --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/npm/PrivateNpmRegistryControllerPermissionTest.java @@ -0,0 +1,146 @@ +package org.lowcoder.api.npm; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BiFunction; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.lowcoder.api.home.SessionUserService; +import org.lowcoder.domain.application.model.Application; +import org.lowcoder.domain.application.service.ApplicationServiceImpl; +import org.lowcoder.domain.organization.model.Organization; +import org.lowcoder.domain.organization.service.OrgMemberServiceImpl; +import org.lowcoder.domain.organization.service.OrganizationService; +import org.lowcoder.domain.permission.model.ResourceAction; +import org.lowcoder.domain.permission.service.ResourcePermissionService; +import org.lowcoder.infra.js.NodeServerHelper; +import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; +import org.mockito.InOrder; +import org.springframework.core.io.Resource; +import org.springframework.http.ResponseEntity; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** + * Pins D-35: the npm registry proxy must check READ on the path's {@code applicationId} before resolving the + * workspace or forwarding anything to node-service. One case per outcome, run for both endpoint methods. + */ +class PrivateNpmRegistryControllerPermissionTest { + + private static final String APPLICATION_ID = "PrivateNpmRegistryControllerPermissionTest.applicationId"; + private static final String ORG_ID = "PrivateNpmRegistryControllerPermissionTest.orgId"; + private static final String OUTSIDER_ID = "PrivateNpmRegistryControllerPermissionTest.outsiderId"; + private static final String VISITOR_ID = "PrivateNpmRegistryControllerPermissionTest.visitorId"; + private static final String PATH = "some-package"; + + private OrganizationService organizationService; + private SessionUserService sessionUserService; + private NodeServerHelper nodeServerHelper; + private OrgMemberServiceImpl orgMemberServiceImpl; + private ApplicationServiceImpl applicationServiceImpl; + private ResourcePermissionService resourcePermissionService; + private PrivateNpmRegistryController controller; + + private static Stream>>> endpoints() { + return Stream.of( + (c, id) -> c.getNpmPackageMeta(id, PATH), + (c, id) -> c.getNpmPackageAsset(id, PATH) + ); + } + + private void setUp() { + organizationService = mock(OrganizationService.class); + sessionUserService = mock(SessionUserService.class); + nodeServerHelper = mock(NodeServerHelper.class); + orgMemberServiceImpl = mock(OrgMemberServiceImpl.class); + applicationServiceImpl = mock(ApplicationServiceImpl.class); + resourcePermissionService = mock(ResourcePermissionService.class); + controller = new PrivateNpmRegistryController(organizationService, sessionUserService, nodeServerHelper, + orgMemberServiceImpl, applicationServiceImpl, resourcePermissionService); + } + + @ParameterizedTest + @MethodSource("endpoints") + void anonymousVisitorDenied(BiFunction>> endpoint) { + setUp(); + when(sessionUserService.getVisitorId()).thenReturn(Mono.just(org.lowcoder.sdk.constants.Authentication.ANONYMOUS_USER_ID)); + when(resourcePermissionService.checkResourcePermissionWithError( + org.lowcoder.sdk.constants.Authentication.ANONYMOUS_USER_ID, APPLICATION_ID, ResourceAction.READ_APPLICATIONS)) + .thenReturn(Mono.error(new BizException(BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED"))); + + StepVerifier.create(endpoint.apply(controller, APPLICATION_ID)) + .expectErrorMatches(e -> e instanceof BizException be && be.getError() == BizError.NOT_AUTHORIZED) + .verify(); + + verify(applicationServiceImpl, never()).findById(any()); + verify(organizationService, never()).getById(any()); + verify(organizationService, never()).getOrgCommonSettings(any()); + verify(nodeServerHelper, never()).createUri(any()); + System.out.println("[PrivateNpmRegistryControllerPermissionTest] anonymousVisitorDenied: NOT_AUTHORIZED, nothing resolved or forwarded"); + } + + @ParameterizedTest + @MethodSource("endpoints") + void signedInOutsiderDenied(BiFunction>> endpoint) { + setUp(); + when(sessionUserService.getVisitorId()).thenReturn(Mono.just(OUTSIDER_ID)); + when(resourcePermissionService.checkResourcePermissionWithError(OUTSIDER_ID, APPLICATION_ID, ResourceAction.READ_APPLICATIONS)) + .thenReturn(Mono.error(new BizException(BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED"))); + + StepVerifier.create(endpoint.apply(controller, APPLICATION_ID)) + .expectErrorMatches(e -> e instanceof BizException be && be.getError() == BizError.NOT_AUTHORIZED) + .verify(); + + verify(applicationServiceImpl, never()).findById(any()); + verify(organizationService, never()).getById(any()); + verify(organizationService, never()).getOrgCommonSettings(any()); + verify(nodeServerHelper, never()).createUri(any()); + System.out.println("[PrivateNpmRegistryControllerPermissionTest] signedInOutsiderDenied: NOT_AUTHORIZED, nothing resolved or forwarded"); + } + + @ParameterizedTest + @MethodSource("endpoints") + void allowed(BiFunction>> endpoint) { + setUp(); + AtomicBoolean findByIdSubscribed = new AtomicBoolean(false); + when(sessionUserService.getVisitorId()).thenReturn(Mono.just(VISITOR_ID)); + when(resourcePermissionService.checkResourcePermissionWithError(VISITOR_ID, APPLICATION_ID, ResourceAction.READ_APPLICATIONS)) + .thenReturn(Mono.empty()); + when(applicationServiceImpl.findById(APPLICATION_ID)) + .thenReturn(Mono.just(Application.builder().id(APPLICATION_ID).organizationId(ORG_ID).build()) + .doOnSubscribe(s -> findByIdSubscribed.set(true))); + when(organizationService.getById(ORG_ID)).thenReturn(Mono.just(Organization.builder().id(ORG_ID).build())); + when(organizationService.getOrgCommonSettings(ORG_ID)).thenReturn(Mono.empty()); + + StepVerifier.create(endpoint.apply(controller, APPLICATION_ID)).verifyComplete(); + + assertThat(findByIdSubscribed).isTrue(); + InOrder order = inOrder(resourcePermissionService, applicationServiceImpl, organizationService); + order.verify(resourcePermissionService).checkResourcePermissionWithError(VISITOR_ID, APPLICATION_ID, ResourceAction.READ_APPLICATIONS); + order.verify(applicationServiceImpl).findById(APPLICATION_ID); + order.verify(organizationService).getById(ORG_ID); + order.verify(organizationService).getOrgCommonSettings(ORG_ID); + verify(resourcePermissionService, times(1)) + .checkResourcePermissionWithError(VISITOR_ID, APPLICATION_ID, ResourceAction.READ_APPLICATIONS); + System.out.println("[PrivateNpmRegistryControllerPermissionTest] allowed: check ran before findById/getById/getOrgCommonSettings"); + } + + @ParameterizedTest + @MethodSource("endpoints") + void noneUnchanged(BiFunction>> endpoint) { + setUp(); + when(sessionUserService.getVisitorOrgMemberCache()) + .thenReturn(Mono.just(org.lowcoder.domain.organization.model.OrgMember.builder().orgId(ORG_ID).build())); + when(organizationService.getOrgCommonSettings(ORG_ID)).thenReturn(Mono.empty()); + + StepVerifier.create(endpoint.apply(controller, "none")).verifyComplete(); + + verifyNoInteractions(resourcePermissionService); + System.out.println("[PrivateNpmRegistryControllerPermissionTest] noneUnchanged: no permission check for 'none'"); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/query/ApplicationQueryApiServiceImplTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/query/ApplicationQueryApiServiceImplTest.java index fde399f717..f10ac8f7fc 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/query/ApplicationQueryApiServiceImplTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/query/ApplicationQueryApiServiceImplTest.java @@ -11,6 +11,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import static org.lowcoder.domain.permission.model.ResourceAction.EDIT_APPLICATIONS; import static org.lowcoder.domain.permission.model.ResourceAction.READ_APPLICATIONS; import java.util.ArrayList; @@ -33,11 +34,13 @@ import org.lowcoder.api.home.SessionUserService; import org.lowcoder.api.query.view.QueryExecutionRequest; import org.lowcoder.domain.application.model.Application; +import org.lowcoder.domain.application.model.ApplicationVersion; import org.lowcoder.domain.application.service.ApplicationRecordService; import org.lowcoder.domain.application.service.ApplicationService; import org.lowcoder.domain.datasource.model.Datasource; import org.lowcoder.domain.datasource.model.DatasourceCreationSource; import org.lowcoder.domain.datasource.service.DatasourceService; +import org.lowcoder.domain.permission.model.ResourceAction; import org.lowcoder.domain.permission.service.ResourcePermissionService; import org.lowcoder.domain.query.model.ApplicationQuery; import org.lowcoder.domain.query.model.BaseQuery; @@ -167,12 +170,17 @@ void setUp() { appQuery = new ApplicationQuery("q-id", "q-gid", "q-name", DATASOURCE_ID, Map.of("sql", "select 1"), "manual", TIMEOUT, "mysql"); lenient().when(sessionUserService.getVisitor()).thenReturn(Mono.just(visitor)); - lenient().when(applicationService.findById(APP_ID)).thenReturn(Mono.just(app)); + lenient().when(applicationService.findById(APP_ID)).thenAnswer(invocation -> Mono.defer(() -> { + events.add("app:" + APP_ID); + return Mono.just(app); + })); lenient().when(app.getOrganizationId()).thenReturn(APP_ORG); lenient().when(app.getQueryByViewModeAndQueryId(anyBoolean(), eq(QUERY_ID), eq(applicationRecordService))) .thenAnswer(invocation -> Mono.just(appQuery)); lenient().when(resourcePermissionService.checkResourcePermissionWithError(anyString(), anyString(), eq(READ_APPLICATIONS))) - .thenAnswer(invocation -> loggedPermission(invocation.getArgument(1))); + .thenAnswer(invocation -> loggedPermission(READ_APPLICATIONS, invocation.getArgument(1))); + lenient().when(resourcePermissionService.checkResourcePermissionWithError(anyString(), anyString(), eq(EDIT_APPLICATIONS))) + .thenAnswer(invocation -> loggedPermission(EDIT_APPLICATIONS, invocation.getArgument(1))); lenient().when(datasourceService.getById(DATASOURCE_ID)).thenAnswer(invocation -> Mono.defer(() -> { events.add("datasource"); return Mono.just(datasource); @@ -192,13 +200,32 @@ private static void say(String format, Object... args) { System.out.println(LOG_PREFIX + String.format(format, args)); } - private Mono loggedPermission(String resourceId) { + private Mono loggedPermission(ResourceAction action, String resourceId) { return Mono.defer(() -> { - events.add("permission:" + resourceId); + events.add(action.name() + ":" + resourceId); return Mono.empty(); }); } + /** Stubs {@code getAllDependentModulesFromApplicationId(rootId, viewMode)} and records its own event. */ + private void modulesOf(String rootId, boolean viewMode, String... moduleIds) { + List modules = Stream.of(moduleIds).map(ApplicationQueryApiServiceImplTest::moduleWithId).toList(); + lenient().when(applicationService.getAllDependentModulesFromApplicationId(rootId, viewMode)) + .thenAnswer(invocation -> Mono.defer(() -> { + events.add("modules:" + rootId + ":" + viewMode); + return Mono.just(modules); + })); + } + + /** Catches a read that must not happen after a refusal: the app document, the module lookup's effect already asserted + * via events, the query, the datasource and the execution. */ + private void assertNothingReadAfterTheRefusal() { + assertThat(events).doesNotContain("app:" + APP_ID, "datasource", "execute"); + verify(app, never()).getQueryByViewModeAndQueryId(anyBoolean(), anyString(), any()); + verify(datasourceService, never()).getById(anyString()); + verifyNoInteractions(queryExecutionService, libraryQueryService, libraryQueryRecordService, applicationRecordService); + } + private static void assertBizError(Throwable error, BizError expected, String messageKey) { assertThat(error).isInstanceOf(BizException.class); assertThat(((BizException) error).getError()).isEqualTo(expected); @@ -267,48 +294,67 @@ void execute_blankAppId_isInvalidAppId(String appId) { static Stream permissionRows() { return Stream.of( - Arguments.of("edit mode, no path", false, null, APP_ID), - Arguments.of("edit mode ignores the path", false, new String[] {ROOT_APP_ID}, APP_ID), - Arguments.of("view mode, null path", true, null, APP_ID), - Arguments.of("view mode, empty path", true, new String[0], APP_ID), - Arguments.of("view mode, blank root", true, new String[] {" "}, APP_ID), - Arguments.of("view mode, root app in the path", true, new String[] {ROOT_APP_ID}, ROOT_APP_ID), - Arguments.of("view mode, only the first path entry is the root", true, new String[] {ROOT_APP_ID, "nested-module"}, ROOT_APP_ID)); + Arguments.of("edit, null path", false, null, + List.of("EDIT_APPLICATIONS:" + APP_ID), false), + Arguments.of("edit, empty path", false, new String[0], + List.of("EDIT_APPLICATIONS:" + APP_ID), false), + Arguments.of("edit, blank root", false, new String[] {" "}, + List.of("EDIT_APPLICATIONS:" + APP_ID), false), + Arguments.of("edit, root equals the app id (own app)", false, new String[] {APP_ID}, + List.of("EDIT_APPLICATIONS:" + APP_ID), false), + Arguments.of("edit, module of a host", false, new String[] {ROOT_APP_ID}, + List.of("EDIT_APPLICATIONS:" + ROOT_APP_ID, "modules:" + ROOT_APP_ID + ":false", "READ_APPLICATIONS:" + APP_ID), true), + Arguments.of("edit, nested module (root is the first entry)", false, new String[] {ROOT_APP_ID, "nested-module"}, + List.of("EDIT_APPLICATIONS:" + ROOT_APP_ID, "modules:" + ROOT_APP_ID + ":false", "READ_APPLICATIONS:" + APP_ID), true), + Arguments.of("view mode, null path", true, null, + List.of("READ_APPLICATIONS:" + APP_ID), true), + Arguments.of("view mode, empty path", true, new String[0], + List.of("READ_APPLICATIONS:" + APP_ID), true), + Arguments.of("view mode, blank root", true, new String[] {" "}, + List.of("READ_APPLICATIONS:" + APP_ID), true), + Arguments.of("view mode, root app in the path", true, new String[] {ROOT_APP_ID}, + List.of("modules:" + ROOT_APP_ID + ":true", "READ_APPLICATIONS:" + ROOT_APP_ID), true), + Arguments.of("view mode, only the first path entry is the root", true, new String[] {ROOT_APP_ID, "nested-module"}, + List.of("modules:" + ROOT_APP_ID + ":true", "READ_APPLICATIONS:" + ROOT_APP_ID), true)); } /** - * Catches reading the wrong app's permission: edit mode checks READ_APPLICATIONS on the app id and ignores the path; - * view mode checks it on the root app of the path (when it is not blank and the app is one of its dependent - * modules) and on the app id otherwise. The permission check runs before the datasource is fetched or executed. + * Catches permission checks on the wrong app, in the wrong order, or with the wrong query selection: view mode checks + * READ on the root app of the path (when it is not blank and the app is one of its dependent modules), or on the app + * id otherwise; edit mode of the app's OWN query (no host) checks EDIT on the app id and ignores the path; edit mode + * of a module run in another app's (the host's) editor checks EDIT on the host, then membership, then READ on the + * module itself (D-10). The permission checks run before the app, the datasource or the query are fetched. */ @ParameterizedTest(name = "{0}") @MethodSource("permissionRows") - void execute_checksReadPermissionOnTheRightApp_beforeAnythingElse(String label, boolean viewMode, String[] path, String checkedId) { - List modules = List.of(moduleWithId(ROOT_APP_ID), moduleWithId(APP_ID)); - lenient().when(applicationService.getAllDependentModulesFromApplicationId(ROOT_APP_ID, true)).thenReturn(Mono.just(modules)); + void execute_checksPermissionOnTheRightAppsInOrder_beforeAnythingElse(String label, boolean viewMode, String[] path, + List expectedEventsBeforeApp, boolean liveQueriesFlag) { + modulesOf(ROOT_APP_ID, true, ROOT_APP_ID, APP_ID); + modulesOf(ROOT_APP_ID, false, ROOT_APP_ID, APP_ID); StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, viewMode, path))) .expectNext(result) .verifyComplete(); - assertThat(events).containsExactly("permission:" + checkedId, "datasource", "execute"); - if (!viewMode) { - verify(applicationService, never()).getAllDependentModulesFromApplicationId(anyString(), anyBoolean()); - } - say("%s -> permission checked on %s, events %s", label, checkedId, events); + List expected = new ArrayList<>(expectedEventsBeforeApp); + expected.addAll(List.of("app:" + APP_ID, "datasource", "execute")); + assertThat(events).containsExactly(expected.toArray(new String[0])); + verify(app).getQueryByViewModeAndQueryId(liveQueriesFlag, QUERY_ID, applicationRecordService); + say("%s -> events %s", label, events); } /** - * Catches a query executed after a failed permission check: the error of the check is the result, and neither the - * datasource is fetched nor the query executed. + * Catches a query executed after a failed permission check: the error of the check is the result, and nothing after + * it (the app, the module lookup, the datasource, the execution) is read. */ @ParameterizedTest(name = "view mode {0}") @ValueSource(booleans = {false, true}) - void execute_deniedReadPermission_stopsBeforeTheDatasourceAndTheExecution(boolean viewMode) { + void execute_deniedPermission_stopsBeforeAnythingElse(boolean viewMode) { BizException denied = new BizException(BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED"); - when(resourcePermissionService.checkResourcePermissionWithError(VISITOR_ID, APP_ID, READ_APPLICATIONS)) + ResourceAction deniedAction = viewMode ? READ_APPLICATIONS : EDIT_APPLICATIONS; + when(resourcePermissionService.checkResourcePermissionWithError(VISITOR_ID, APP_ID, deniedAction)) .thenReturn(Mono.defer(() -> { - events.add("permission:" + APP_ID); + events.add(deniedAction.name() + ":" + APP_ID); return Mono.error(denied); })); @@ -316,9 +362,101 @@ void execute_deniedReadPermission_stopsBeforeTheDatasourceAndTheExecution(boolea .expectErrorSatisfies(error -> assertThat(error).isSameAs(denied)) .verify(); - assertThat(events).containsExactly("permission:" + APP_ID); - verify(queryExecutionService, never()).executeQuery(any(), any(), any(), any(), any()); - say("denied read permission (view mode %s) -> %s", viewMode, events); + assertThat(events).containsExactly(deniedAction.name() + ":" + APP_ID); + assertNothingReadAfterTheRefusal(); + say("denied permission (view mode %s) -> %s", viewMode, events); + } + + /** Catches EDIT alone being treated as enough for a module query of a host: READ on the module must still be checked. */ + @Test + void execute_editModeOwnApp_readIsNotEnough() { + when(resourcePermissionService.checkResourcePermissionWithError(VISITOR_ID, APP_ID, EDIT_APPLICATIONS)) + .thenReturn(Mono.error(new BizException(BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED"))); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, false, null))) + .expectErrorSatisfies(error -> assertBizError(error, BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED")) + .verify(); + + verify(resourcePermissionService, never()).checkResourcePermissionWithError(VISITOR_ID, APP_ID, READ_APPLICATIONS); + assertNothingReadAfterTheRefusal(); + say("edit own app, EDIT refused -> NOT_AUTHORIZED, READ never consulted"); + } + + @Test + void execute_hostedModule_noEditOnTheHost_isDenied() { + when(resourcePermissionService.checkResourcePermissionWithError(VISITOR_ID, ROOT_APP_ID, EDIT_APPLICATIONS)) + .thenReturn(Mono.defer(() -> { + events.add("EDIT_APPLICATIONS:" + ROOT_APP_ID); + return Mono.error(new BizException(BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED")); + })); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, false, new String[] {ROOT_APP_ID}))) + .expectErrorSatisfies(error -> assertBizError(error, BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED")) + .verify(); + + assertThat(events).containsExactly("EDIT_APPLICATIONS:" + ROOT_APP_ID); + verify(applicationService, never()).getAllDependentModulesFromApplicationId(anyString(), anyBoolean()); + verify(resourcePermissionService, never()).checkResourcePermissionWithError(VISITOR_ID, APP_ID, READ_APPLICATIONS); + assertNothingReadAfterTheRefusal(); + say("hosted module, host EDIT refused -> NOT_AUTHORIZED, no module lookup, no READ on the module"); + } + + @Test + void execute_hostedModule_notAModuleOfTheHost_isInvalid() { + modulesOf(ROOT_APP_ID, false, ROOT_APP_ID, "some-other-module"); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, false, new String[] {ROOT_APP_ID}))) + .expectErrorSatisfies(error -> assertBizError(error, BizError.INVALID_PARAMETER, "INVALID_PARAMETER")) + .verify(); + + assertThat(events).containsExactly("EDIT_APPLICATIONS:" + ROOT_APP_ID, "modules:" + ROOT_APP_ID + ":false"); + verify(resourcePermissionService, never()).checkResourcePermissionWithError(VISITOR_ID, APP_ID, READ_APPLICATIONS); + assertNothingReadAfterTheRefusal(); + say("hosted module, not among the host's modules -> INVALID_PARAMETER, READ never checked"); + } + + @Test + void execute_hostedModule_editorWithoutReadOnTheModule_isDenied() { + modulesOf(ROOT_APP_ID, false, ROOT_APP_ID, APP_ID); + when(resourcePermissionService.checkResourcePermissionWithError(VISITOR_ID, APP_ID, READ_APPLICATIONS)) + .thenReturn(Mono.defer(() -> { + events.add("READ_APPLICATIONS:" + APP_ID); + return Mono.error(new BizException(BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED")); + })); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, false, new String[] {ROOT_APP_ID}))) + .expectErrorSatisfies(error -> assertBizError(error, BizError.NOT_AUTHORIZED, "NOT_AUTHORIZED")) + .verify(); + + assertThat(events).containsExactly("EDIT_APPLICATIONS:" + ROOT_APP_ID, "modules:" + ROOT_APP_ID + ":false", "READ_APPLICATIONS:" + APP_ID); + assertNothingReadAfterTheRefusal(); + say("hosted module, host EDIT passes, membership passes, module READ refused -> NOT_AUTHORIZED"); + } + + static Stream moduleLookupFailureRows() { + return Stream.of( + // the lookup's own error passes through unchanged (ApplicationQueryApiServiceImpl.java:187-191: flatMap, no catch). + Arguments.of("lookup errors", Mono.error(new BizException(BizError.NO_RESOURCE_FOUND, "NO_RESOURCE_FOUND")), BizError.NO_RESOURCE_FOUND, "NO_RESOURCE_FOUND"), + // an empty completion is caught by the defensive switchIfEmpty guard (:195-198) and becomes INVALID_PARAMETER. + Arguments.of("lookup completes empty", Mono.empty(), BizError.INVALID_PARAMETER, "INVALID_PARAMETER")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("moduleLookupFailureRows") + void execute_hostedModule_moduleLookupFails_orCompletesEmpty_isNotAPass(String label, Mono> lookupAnswer, BizError expectedError, String expectedMessage) { + lenient().when(applicationService.getAllDependentModulesFromApplicationId(ROOT_APP_ID, false)) + .thenAnswer(invocation -> Mono.defer(() -> { + events.add("modules:" + ROOT_APP_ID + ":false"); + return lookupAnswer; + })); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, false, new String[] {ROOT_APP_ID}))) + .expectErrorSatisfies(error -> assertBizError(error, expectedError, expectedMessage)) + .verify(); + + verify(resourcePermissionService, never()).checkResourcePermissionWithError(VISITOR_ID, APP_ID, READ_APPLICATIONS); + assertNothingReadAfterTheRefusal(); + say("%s -> %s, READ never checked", label, expectedError); } /** @@ -327,20 +465,170 @@ void execute_deniedReadPermission_stopsBeforeTheDatasourceAndTheExecution(boolea * checked on the forged root and nothing is executed. When the app is among the modules, the permission is checked * on the root. */ + @Test + void execute_viewMode_rootEqualsTheApp_isStillInvalid() { + Application rootStandIn = moduleWithId(ROOT_APP_ID); + lenient().when(applicationService.findById(ROOT_APP_ID)).thenReturn(Mono.just(rootStandIn)); + modulesOf(ROOT_APP_ID, true, "some-other-module"); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(ROOT_APP_ID, QUERY_ID, true, new String[] {ROOT_APP_ID}))) + .expectErrorSatisfies(error -> assertBizError(error, BizError.INVALID_PARAMETER, "INVALID_PARAMETER")) + .verify(); + + verify(resourcePermissionService, never()).checkResourcePermissionWithError(anyString(), anyString(), any()); + say("view mode, root equals the app, not among the (forged) modules -> INVALID_PARAMETER, no permission check"); + } + @Test void execute_forgedPath_appNotAmongTheRootsModules_isRejected() { - List modules = List.of(moduleWithId(ROOT_APP_ID), moduleWithId("some-other-module")); - when(applicationService.getAllDependentModulesFromApplicationId(ROOT_APP_ID, true)).thenReturn(Mono.just(modules)); + modulesOf(ROOT_APP_ID, true, ROOT_APP_ID, "some-other-module"); StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, true, new String[] {ROOT_APP_ID}))) .expectErrorSatisfies(error -> assertBizError(error, BizError.INVALID_PARAMETER, "INVALID_PARAMETER")) .verify(); - assertThat(events).isEmpty(); + assertThat(events).containsExactly("modules:" + ROOT_APP_ID + ":true"); verify(resourcePermissionService, never()).checkResourcePermissionWithError(anyString(), anyString(), any()); say("forged path -> INVALID_PARAMETER, no permission check, no execution"); } + // ------------------------------------------------------------------ query selection (live vs. draft, D-10) + + private static final String DRAFT_ONLY_ID = "query-draft-only"; + + /** A query map in the exact JSON shape {@link ApplicationQuery}'s {@code @JsonCreator} expects, built by hand + * (not round-tripped through an {@code ApplicationQuery} instance: its default getter-based serialization does + * not use the same property names its constructor expects). */ + private static Map q(String id, String sql) { + Map map = new HashMap<>(); + map.put("id", id); + map.put("gid", id + "-gid"); + map.put("name", id + "-name"); + map.put("datasourceId", DATASOURCE_ID); + map.put("comp", Map.of("sql", sql)); + map.put("triggerType", "manual"); + map.put("timeout", TIMEOUT); + map.put("compType", PLAIN_TYPE); + return map; + } + + private static Application moduleWithQueries(String id, Map... queries) { + return Application.builder().id(id).organizationId(APP_ORG) + .editingApplicationDSL(Map.of("queries", List.of(queries))) + .build(); + } + + private void published(String appId, Map... liveQueries) { + lenient().when(applicationRecordService.getLatestRecordByApplicationId(appId)) + .thenReturn(Mono.just(ApplicationVersion.builder().applicationDSL(Map.of("queries", List.of(liveQueries))).build())); + } + + private void neverPublished(String appId) { + lenient().when(applicationRecordService.getLatestRecordByApplicationId(appId)).thenReturn(Mono.empty()); + } + + /** Catches the wrong query text (draft vs. published) and the wrong error: a real {@link Application}, not the + * {@code app} mock, so {@code Application.java}'s own live/draft selection runs. Reads the LATEST call's config + * (not an exactly-once verify): some selection tests execute more than once to contrast two outcomes. */ + @SuppressWarnings("unchecked") + private String executedSql() { + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(queryExecutionService, org.mockito.Mockito.atLeastOnce()).executeQuery(any(), captor.capture(), any(), any(), any()); + List> all = captor.getAllValues(); + return (String) all.get(all.size() - 1).get("sql"); + } + + @Test + void execute_publishedModule_draftTextDiffers_inHostEditor_runsLiveText() { + Application module = moduleWithQueries(APP_ID, q(QUERY_ID, "draft"), q(DRAFT_ONLY_ID, "draft-only")); + when(applicationService.findById(APP_ID)).thenReturn(Mono.just(module)); + published(APP_ID, q(QUERY_ID, "live")); + modulesOf(ROOT_APP_ID, false, ROOT_APP_ID, APP_ID); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, false, new String[] {ROOT_APP_ID}))) + .expectNext(result).verifyComplete(); + + assertThat(executedSql()).isEqualTo("live"); + say("S1 published module, draft differs, host editor -> live text ran"); + } + + @Test + void execute_publishedModule_draftOnlyQuery_inHostEditor_isQueryNotFound() { + Application module = moduleWithQueries(APP_ID, q(QUERY_ID, "draft"), q(DRAFT_ONLY_ID, "draft-only")); + when(applicationService.findById(APP_ID)).thenReturn(Mono.just(module)); + published(APP_ID, q(QUERY_ID, "live")); + modulesOf(ROOT_APP_ID, false, ROOT_APP_ID, APP_ID); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, DRAFT_ONLY_ID, false, new String[] {ROOT_APP_ID}))) + .expectErrorSatisfies(error -> assertBizError(error, BizError.QUERY_NOT_FOUND, "LIBRARY_QUERY_NOT_FOUND")) + .verify(); + + verify(queryExecutionService, never()).executeQuery(any(), any(), any(), any(), any()); + verify(datasourceService, never()).getById(anyString()); + say("S2 published module, draft-only query, host editor -> QUERY_NOT_FOUND, nothing executed"); + } + + @Test + void execute_publishedModule_ownEditor_runsItsDraft() { + Application module = moduleWithQueries(APP_ID, q(QUERY_ID, "draft"), q(DRAFT_ONLY_ID, "draft-only")); + when(applicationService.findById(APP_ID)).thenReturn(Mono.just(module)); + published(APP_ID, q(QUERY_ID, "live")); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, false, null))) + .expectNext(result).verifyComplete(); + assertThat(executedSql()).isEqualTo("draft"); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, DRAFT_ONLY_ID, false, null))) + .expectNext(result).verifyComplete(); + assertThat(executedSql()).isEqualTo("draft-only"); + say("S3 published module, own editor -> runs its own draft"); + } + + @Test + void execute_neverPublishedModule_inHostEditor_runsItsDraft_acceptedBehaviour() { + Application module = moduleWithQueries(APP_ID, q(QUERY_ID, "draft")); + when(applicationService.findById(APP_ID)).thenReturn(Mono.just(module)); + neverPublished(APP_ID); + modulesOf(ROOT_APP_ID, false, ROOT_APP_ID, APP_ID); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, false, new String[] {ROOT_APP_ID}))) + .expectNext(result).verifyComplete(); + + assertThat(executedSql()).isEqualTo("draft"); + say("S4 never-published module, host editor -> runs its draft (accepted, 3.3 b)"); + } + + @Test + void execute_rootEqualsTheAppId_runsItsDraft_onlyEditChecked() { + Application own = moduleWithQueries(APP_ID, q(QUERY_ID, "draft")); + when(applicationService.findById(APP_ID)).thenReturn(Mono.just(own)); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, false, new String[] {APP_ID}))) + .expectNext(result).verifyComplete(); + + assertThat(executedSql()).isEqualTo("draft"); + assertThat(events).containsExactly("EDIT_APPLICATIONS:" + APP_ID, "datasource", "execute"); + verify(applicationService, never()).getAllDependentModulesFromApplicationId(anyString(), anyBoolean()); + say("S5 root equals the app id -> runs its draft, only EDIT checked"); + } + + @Test + void execute_viewMode_publishedOrNeverPublished_pins() { + Application module = moduleWithQueries(APP_ID, q(QUERY_ID, "draft")); + when(applicationService.findById(APP_ID)).thenReturn(Mono.just(module)); + published(APP_ID, q(QUERY_ID, "live")); + + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, true, null))) + .expectNext(result).verifyComplete(); + assertThat(executedSql()).isEqualTo("live"); + + neverPublished(APP_ID); + StepVerifier.create(service.executeApplicationQuery(exchange, request(APP_ID, QUERY_ID, true, null))) + .expectNext(result).verifyComplete(); + assertThat(executedSql()).isEqualTo("draft"); + say("S6 view mode: published runs live, never-published runs its draft (unchanged)"); + } + // ------------------------------------------------------------------ the datasource / app tenant check private static final int USER_CREATED = DatasourceCreationSource.USER_CREATED.getValue(); diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/GroupApiServiceImplTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/GroupApiServiceImplTest.java index f1d8d8bec4..d786863dbf 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/GroupApiServiceImplTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/GroupApiServiceImplTest.java @@ -204,6 +204,11 @@ private static void assertBizError(Throwable error, BizError expected) { assertThat(((BizException) error).getError()).isEqualTo(expected); } + private static void assertBizError(Throwable error, BizError expected, String messageKey) { + assertBizError(error, expected); + assertThat(((BizException) error).getMessageKey()).isEqualTo(messageKey); + } + private static List userIds(GroupMemberAggregateView view) { return view.getMembers().stream().map(GroupMemberView::getUserId).toList(); } @@ -880,6 +885,51 @@ void update_handsTheGroupIdNameAndRuleToTheGroupService() { group.getDynamicRule()); } + /** + * D-52: a rename of a system group (any of the three encodings) is refused with UNSUPPORTED_OPERATION + * (message key BAD_REQUEST) and writes nothing, even though the same request also carries a dynamic rule change. + */ + @ParameterizedTest(name = "type {0}, allUsersGroup {1}") + @MethodSource("systemGroups") + void update_systemGroupRename_isUnsupportedAndWritesNothing(String type, Boolean allUsersGroup) { + stubVisitor(orgMember(MemberRole.ADMIN), null, group(GROUP_ID, ORG_ID, type, allUsersGroup)); + UpdateGroupRequest request = new UpdateGroupRequest(); + request.setGroupName("renamed"); + request.setDynamicRule(DYNAMIC_RULE); + + StepVerifier.create(service.update(GROUP_ID, request)) + .expectErrorSatisfies(error -> assertBizError(error, BizError.UNSUPPORTED_OPERATION, "BAD_REQUEST")) + .verify(); + + verify(groupService, never()).updateGroup(any(Group.class)); + assertThat(mutations).hasValue(0); + say("update: system group (type=%s, allUsersGroup=%s) rename -> UNSUPPORTED_OPERATION/BAD_REQUEST, no write", + type, allUsersGroup); + } + + /** + * D-52: a system group's dynamic-rule-only update (no name in the request) is not refused: the guard checks the + * request's {@code groupName} field, not the group's system-ness in isolation. + */ + @ParameterizedTest(name = "type {0}, allUsersGroup {1}") + @MethodSource("systemGroups") + void update_systemGroupDynamicRuleOnly_isWritten(String type, Boolean allUsersGroup) { + stubVisitor(orgMember(MemberRole.ADMIN), null, group(GROUP_ID, ORG_ID, type, allUsersGroup)); + ArgumentCaptor updated = ArgumentCaptor.forClass(Group.class); + when(groupService.updateGroup(updated.capture())).thenReturn(Mono.just(true)); + UpdateGroupRequest request = new UpdateGroupRequest(); + request.setDynamicRule(DYNAMIC_RULE); + + StepVerifier.create(service.update(GROUP_ID, request)).expectNext(true).verifyComplete(); + + Group group = updated.getValue(); + assertThat(group.getId()).isEqualTo(GROUP_ID); + assertThat(group.getName(java.util.Locale.ENGLISH)).isNull(); + assertThat(group.getDynamicRule()).isEqualTo(DYNAMIC_RULE); + say("update: system group (type=%s, allUsersGroup=%s) dynamic-rule-only -> written, name untouched", + type, allUsersGroup); + } + /** * Catches an admin removing their own membership through {@code removeUser}: CANNOT_REMOVE_MYSELF and nothing * is removed. diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/InvitationAndUserApiServiceTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/InvitationAndUserApiServiceTest.java index ec519b159b..336a1ed391 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/InvitationAndUserApiServiceTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/InvitationAndUserApiServiceTest.java @@ -51,8 +51,8 @@ /** * {@link InvitationApiServiceImpl} (joining by invitation, the invitation view, invitation creation), * {@link InvitationVO} and {@link UserApiServiceImpl} (the admin gate of user detail and password reset, and the - * removal of stale tokens), with every collaborator mocked. The two one-line delegates of {@code UserApiServiceImpl} - * ({@code lostPassword}, {@code resetLostPassword}) are not tested: that would test a mock. + * removal of stale tokens), with every collaborator mocked. The one-line delegate {@code lostPassword} is not + * tested: that would test a mock; {@code resetLostPassword} is tested in {@code UserApiServiceImplResetLostPasswordTest}. * *

Fixed (BF-080, was the plan section 9 row "InvitationApiServiceImpl raises INVITER_NOT_FOUND with the message key * INVITED_ORG_DELETED"): a missing inviter is reported with its own message @@ -70,6 +70,7 @@ class InvitationAndUserApiServiceTest { private static final String INVITATION_ID = "invitation-1"; private static final String ORG_ID = "org-1"; private static final String VISITOR_ID = "visitor-1"; + private static final String VISITOR_TOKEN = "InvitationAndUserApiServiceTest.visitorToken"; private static final String CREATOR_ID = "creator-1"; private static final String TARGET_ID = "target-1"; private static final String ORG_NAME = "Org One"; @@ -474,6 +475,11 @@ void userOperation_requiresAnAdminOfTheVisitorsOrgAndATargetInThatOrg(UserOperat lenient().when(userService.findById(TARGET_ID)).thenReturn(logged("findById", target)); lenient().when(userService.buildUserDetail(target, false)).thenReturn(logged("detail", detail)); lenient().when(userService.resetPassword(TARGET_ID)).thenReturn(logged("reset", "new-password")); + lenient().when(sessionUserService.getVisitorToken()).thenReturn(Mono.just(VISITOR_TOKEN)); + lenient().when(sessionUserService.endSessionsOfUser(TARGET_ID, null)).thenReturn(Mono.defer(() -> { + events.add("endSessions"); + return Mono.empty(); + })); Mono result = operation == UserOperation.GET_DETAIL ? userApiService.getUserDetailById(TARGET_ID) : userApiService.resetPassword(TARGET_ID); @@ -484,8 +490,9 @@ void userOperation_requiresAnAdminOfTheVisitorsOrgAndATargetInThatOrg(UserOperat // resetPassword's new checkResetTargetBelowSuperAdmin also calls // userService.findById(userId) (to read the superAdmin flag) before userService.resetPassword, reusing // this test's existing logged("findById", target) stub -- so the allowed case now logs "findById" too. + // resetPassword's sweep (D-34) then ends the target's sessions, logging "endSessions" last. assertThat(events).isEqualTo(operation == UserOperation.GET_DETAIL - ? List.of("findById", "detail") : List.of("findById", "reset")); + ? List.of("findById", "detail") : List.of("findById", "reset", "endSessions")); } else { StepVerifier.create(result) .expectErrorSatisfies(error -> assertBizError(error, BizError.UNSUPPORTED_OPERATION, "BAD_REQUEST")) diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/OrgDevCheckerTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/OrgDevCheckerTest.java new file mode 100644 index 0000000000..f8aa559b31 --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/OrgDevCheckerTest.java @@ -0,0 +1,146 @@ +package org.lowcoder.api.usermanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.lowcoder.api.home.SessionUserService; +import org.lowcoder.domain.group.model.Group; +import org.lowcoder.domain.group.service.GroupMemberService; +import org.lowcoder.domain.group.service.GroupService; +import org.lowcoder.domain.organization.model.MemberRole; +import org.lowcoder.domain.organization.model.OrgMember; +import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** + * {@link OrgDevChecker#checkOrgDev} (D-11, D-41): admin, super admin or a member of the given membership's own + * workspace dev group passes; a plain member outside the dev group is refused with NEED_DEV_TO_CREATE_RESOURCE. + * Unlike {@link OrgDevChecker#checkCurrentOrgDev}, the membership is passed in by the caller, not read from + * {@code sessionUserService.getVisitorOrgMemberCache()} — the whole point of the new method, so every case here + * verifies that the session cache is never consulted. + */ +class OrgDevCheckerTest { + + private static final String LOG_PREFIX = "[OrgDevCheckerTest] "; + private static final String ORG_ID = "org-1"; + private static final String USER_ID = "user-1"; + private static final String MSG_NEED_DEV = "NEED_DEV_TO_CREATE_RESOURCE"; + + private final SessionUserService sessionUserService = mock(SessionUserService.class); + private final GroupService groupService = mock(GroupService.class); + private final GroupMemberService groupMemberService = mock(GroupMemberService.class); + private final OrgDevChecker checker = new OrgDevChecker(sessionUserService, groupService, groupMemberService); + + private static OrgMember member(MemberRole role) { + return new OrgMember(ORG_ID, USER_ID, role, "normal", 0L); + } + + private static void say(String format, Object... args) { + System.out.println(LOG_PREFIX + String.format(format, args)); + } + + @Test + void admin_passes_withoutConsultingTheDevGroupOrTheSessionCache() { + OrgMember admin = member(MemberRole.ADMIN); + + StepVerifier.create(checker.checkOrgDev(admin)).verifyComplete(); + + verifyNoInteractions(groupService, groupMemberService, sessionUserService); + say("admin -> passes, no dev-group lookup, no session cache read"); + } + + @Test + void superAdmin_passes_withoutConsultingTheDevGroupOrTheSessionCache() { + OrgMember superAdmin = member(MemberRole.SUPER_ADMIN); + + StepVerifier.create(checker.checkOrgDev(superAdmin)).verifyComplete(); + + verifyNoInteractions(groupService, groupMemberService, sessionUserService); + say("super admin -> passes, no dev-group lookup, no session cache read"); + } + + @Test + void memberOfTheDevGroup_passes() { + OrgMember plainMember = member(MemberRole.MEMBER); + Group devGroup = new Group(); + when(groupService.getDevGroup(ORG_ID)).thenReturn(Mono.just(devGroup)); + when(groupMemberService.isMember(devGroup, USER_ID)).thenReturn(Mono.just(true)); + + StepVerifier.create(checker.checkOrgDev(plainMember)).verifyComplete(); + + verifyNoInteractions(sessionUserService); + say("member of the dev group -> passes, the session cache is never read"); + } + + @Test + void plainMember_notInTheDevGroup_isRefused() { + OrgMember plainMember = member(MemberRole.MEMBER); + Group devGroup = new Group(); + when(groupService.getDevGroup(ORG_ID)).thenReturn(Mono.just(devGroup)); + when(groupMemberService.isMember(devGroup, USER_ID)).thenReturn(Mono.just(false)); + + StepVerifier.create(checker.checkOrgDev(plainMember)) + .expectErrorSatisfies(error -> { + assertThat(error).isInstanceOf(BizException.class); + BizException biz = (BizException) error; + assertThat(biz.getError()).isEqualTo(BizError.NEED_DEV_TO_CREATE_RESOURCE); + assertThat(biz.getMessageKey()).isEqualTo(MSG_NEED_DEV); + }) + .verify(); + + verifyNoInteractions(sessionUserService); + say("plain member, not in the dev group -> NEED_DEV_TO_CREATE_RESOURCE, the session cache is never read"); + } + + @Test + void plainMember_noDevGroupAtAll_isRefused() { + OrgMember plainMember = member(MemberRole.MEMBER); + when(groupService.getDevGroup(ORG_ID)).thenReturn(Mono.empty()); + + StepVerifier.create(checker.checkOrgDev(plainMember)) + .expectErrorSatisfies(error -> { + assertThat(error).isInstanceOf(BizException.class); + assertThat(((BizException) error).getError()).isEqualTo(BizError.NEED_DEV_TO_CREATE_RESOURCE); + }) + .verify(); + + verify(groupMemberService, never()).isMember(any(), any()); + verifyNoInteractions(sessionUserService); + say("plain member, workspace has no dev group -> NEED_DEV_TO_CREATE_RESOURCE, no membership lookup attempted"); + } + + /** + * D-11/D-41 itself: an admin of the visitor's CURRENT workspace who is only a plain, non-dev member of a + * DIFFERENT, given workspace is refused for that given workspace — {@code checkOrgDev} decides purely from the + * membership it is handed, never from {@code sessionUserService.getVisitorOrgMemberCache()}. + */ + @Test + void adminOfTheCurrentWorkspace_butPlainMemberOfTheGivenWorkspace_isRefusedForTheGivenWorkspace() { + OrgMember currentWorkspaceAdmin = new OrgMember("current-org", USER_ID, MemberRole.ADMIN, "normal", 0L); + lenientStubSessionCacheTo(currentWorkspaceAdmin); + OrgMember targetWorkspaceMember = member(MemberRole.MEMBER); + Group devGroup = new Group(); + when(groupService.getDevGroup(ORG_ID)).thenReturn(Mono.just(devGroup)); + when(groupMemberService.isMember(devGroup, USER_ID)).thenReturn(Mono.just(false)); + + StepVerifier.create(checker.checkOrgDev(targetWorkspaceMember)) + .expectErrorSatisfies(error -> assertThat(((BizException) error).getError()).isEqualTo(BizError.NEED_DEV_TO_CREATE_RESOURCE)) + .verify(); + + verify(groupService).getDevGroup(ORG_ID); + verifyNoInteractions(sessionUserService); + say("admin of the current workspace, plain member of the given workspace -> refused for the given workspace"); + } + + private void lenientStubSessionCacheTo(OrgMember member) { + org.mockito.Mockito.lenient().when(sessionUserService.getVisitorOrgMemberCache()).thenReturn(Mono.just(member)); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetLostPasswordTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetLostPasswordTest.java new file mode 100644 index 0000000000..dfbdc6fe08 --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetLostPasswordTest.java @@ -0,0 +1,100 @@ +package org.lowcoder.api.usermanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lowcoder.api.home.SessionUserService; +import org.lowcoder.domain.organization.service.OrgMemberService; +import org.lowcoder.domain.user.repository.UserRepository; +import org.lowcoder.domain.user.service.UserService; +import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; + +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** + * {@code UserApiServiceImpl#resetLostPassword} (D-34): after the domain reset of a lost password, every session of + * the account is ended, for an anonymous caller none is kept. + */ +class UserApiServiceImplResetLostPasswordTest { + + private static final String EMAIL = "UserApiServiceImplResetLostPasswordTest.email@example.com"; + private static final String TOKEN = "UserApiServiceImplResetLostPasswordTest.resetToken"; + private static final String NEW_PASSWORD = "UserApiServiceImplResetLostPasswordTest.newPassword"; + private static final String USER_ID = "UserApiServiceImplResetLostPasswordTest.userId"; + + private SessionUserService sessionUserService; + private UserService userService; + private UserApiServiceImpl service; + + @BeforeEach + void setUp() { + sessionUserService = mock(SessionUserService.class); + OrgMemberService orgMemberService = mock(OrgMemberService.class); + userService = mock(UserService.class); + service = new UserApiServiceImpl(sessionUserService, orgMemberService, userService, mock(UserRepository.class)); + } + + @Test + void resetLostPassword_success_endsEverySessionAfterTheReset() { + List order = new ArrayList<>(); + when(userService.resetLostPassword(EMAIL, TOKEN, NEW_PASSWORD)).thenReturn(Mono.defer(() -> { + order.add("reset"); + return Mono.just(USER_ID); + })); + when(sessionUserService.endSessionsOfUser(USER_ID, null)).thenReturn(Mono.defer(() -> { + order.add("endSessions"); + return Mono.empty(); + })); + + StepVerifier.create(service.resetLostPassword(EMAIL, TOKEN, NEW_PASSWORD)).expectNext(true).verifyComplete(); + + assertThat(order).containsExactly("reset", "endSessions"); + } + + @Test + void resetLostPassword_tokenRefused_endsNoSession() { + BizException refused = new BizException(BizError.INVALID_PARAMETER, "INVALID_TOKEN"); + when(userService.resetLostPassword(EMAIL, TOKEN, NEW_PASSWORD)).thenReturn(Mono.error(refused)); + + StepVerifier.create(service.resetLostPassword(EMAIL, TOKEN, NEW_PASSWORD)) + .expectErrorSatisfies(error -> assertThat(error).isSameAs(refused)) + .verify(); + + verify(sessionUserService, never()).endSessionsOfUser(anyString(), any()); + } + + @Test + void resetLostPassword_noQualifyingAccount_answersEmptyAndEndsNoSession() { + when(userService.resetLostPassword(EMAIL, TOKEN, NEW_PASSWORD)).thenReturn(Mono.empty()); + + StepVerifier.create(service.resetLostPassword(EMAIL, TOKEN, NEW_PASSWORD)).verifyComplete(); + + verify(sessionUserService, never()).endSessionsOfUser(anyString(), any()); + } + + @Test + void resetLostPassword_sessionsNotEnded_answersTheError() { + when(userService.resetLostPassword(EMAIL, TOKEN, NEW_PASSWORD)).thenReturn(Mono.just(USER_ID)); + when(sessionUserService.endSessionsOfUser(USER_ID, null)).thenReturn( + Mono.error(new BizException(BizError.PASSWORD_CHANGED_SESSIONS_NOT_ENDED, "PASSWORD_CHANGED_SESSIONS_NOT_ENDED", 1))); + + StepVerifier.create(service.resetLostPassword(EMAIL, TOKEN, NEW_PASSWORD)) + .expectErrorSatisfies(error -> { + assertThat(error).isInstanceOf(BizException.class); + assertThat(((BizException) error).getError()).isEqualTo(BizError.PASSWORD_CHANGED_SESSIONS_NOT_ENDED); + }) + .verify(); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetPasswordTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetPasswordTest.java index cd3a8628b7..7b5fddbeaa 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetPasswordTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserApiServiceImplResetPasswordTest.java @@ -1,10 +1,16 @@ package org.lowcoder.api.usermanagement; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.BeforeEach; @@ -40,6 +46,7 @@ class UserApiServiceImplResetPasswordTest { private static final String VISITOR_ID = "visitor-1"; private static final String TARGET_ID = "target-1"; private static final String NEW_PASSWORD = "UserApiServiceImplResetPasswordTest.newPassword"; + private static final String VISITOR_TOKEN = "UserApiServiceImplResetPasswordTest.visitorToken"; private SessionUserService sessionUserService; private OrgMemberService orgMemberService; @@ -52,6 +59,8 @@ void setUp() { orgMemberService = mock(OrgMemberService.class); userService = mock(UserService.class); service = new UserApiServiceImpl(sessionUserService, orgMemberService, userService, mock(UserRepository.class)); + when(sessionUserService.getVisitorToken()).thenReturn(Mono.just(VISITOR_TOKEN)); + when(sessionUserService.endSessionsOfUser(anyString(), any())).thenReturn(Mono.empty()); } private void visitorIs(String visitorId, MemberRole visitorRole) { @@ -95,6 +104,7 @@ void targetSuperAdminRole_adminVisitor_refusedD40() { assertUnsupportedOperation(service.resetPassword(TARGET_ID)); assertThat(reset).as("userService.resetPassword must never be subscribed").isFalse(); + verify(sessionUserService, never()).endSessionsOfUser(any(), any()); } /** Target ADMIN role but the account-wide superAdmin flag is set, ADMIN-role visitor -> refused, nothing reset. */ @@ -108,6 +118,7 @@ void targetSuperAdminFlagRoleAdmin_adminVisitor_refusedD40() { assertUnsupportedOperation(service.resetPassword(TARGET_ID)); assertThat(reset).as("userService.resetPassword must never be subscribed").isFalse(); + verify(sessionUserService, never()).endSessionsOfUser(any(), any()); } /** @@ -125,6 +136,7 @@ void targetSuperAdminRole_superAdminVisitor_nonSelf_refusedD40() { assertUnsupportedOperation(service.resetPassword(TARGET_ID)); assertThat(reset).isFalse(); + verify(sessionUserService, never()).endSessionsOfUser(any(), any()); } @Test @@ -137,6 +149,7 @@ void targetSuperAdminFlagRoleAdmin_superAdminVisitor_nonSelf_refusedD40() { assertUnsupportedOperation(service.resetPassword(TARGET_ID)); assertThat(reset).isFalse(); + verify(sessionUserService, never()).endSessionsOfUser(any(), any()); } /** A plain MEMBER target, superAdmin flag false -> reset (unaffected, the baseline allowed case). */ @@ -192,6 +205,7 @@ void visitorNotAnAdmin_refusedUnchangedD40() { assertUnsupportedOperation(service.resetPassword(TARGET_ID)); assertThat(reset).isFalse(); + verify(sessionUserService, never()).endSessionsOfUser(any(), any()); } /** Target not a member of the visitor's current org -> unchanged answer (the existing, unaffected check runs first). */ @@ -205,5 +219,74 @@ void targetNotAMember_refusedUnchangedD40() { assertUnsupportedOperation(service.resetPassword(TARGET_ID)); assertThat(reset).isFalse(); + verify(sessionUserService, never()).endSessionsOfUser(any(), any()); + } + + /** D-34: an admin resetting ANOTHER user's password ends every session of the target, keeping none. */ + @Test + void resetOfAnotherUser_endsEverySessionOfTheTargetD34() { + visitorIs(VISITOR_ID, MemberRole.ADMIN); + targetIs(MemberRole.MEMBER, false); + when(userService.resetPassword(TARGET_ID)).thenReturn(Mono.just(NEW_PASSWORD)); + + StepVerifier.create(service.resetPassword(TARGET_ID)).expectNext(NEW_PASSWORD).verifyComplete(); + + verify(sessionUserService).endSessionsOfUser(TARGET_ID, null); + verify(sessionUserService, never()).endSessionsOfUser(any(), eq(VISITOR_TOKEN)); + } + + /** D-34: an admin resetting its OWN password keeps the session that asked for the reset. */ + @Test + void selfReset_keepsTheCallersSessionD34() { + visitorIs(VISITOR_ID, MemberRole.ADMIN); + when(orgMemberService.getOrgMember(ORG_ID, VISITOR_ID)) + .thenReturn(Mono.just(new OrgMember(ORG_ID, VISITOR_ID, MemberRole.ADMIN, "visitor-state", 0L))); + when(userService.resetPassword(VISITOR_ID)).thenReturn(Mono.just(NEW_PASSWORD)); + + StepVerifier.create(service.resetPassword(VISITOR_ID)).expectNext(NEW_PASSWORD).verifyComplete(); + + verify(sessionUserService).endSessionsOfUser(VISITOR_ID, VISITOR_TOKEN); + verify(sessionUserService, never()).endSessionsOfUser(VISITOR_ID, null); + } + + /** D-34: the sweep runs only AFTER the domain reset, never before or interleaved with it. */ + @Test + void reset_endsSessionsOnlyAfterTheResetD34() { + visitorIs(VISITOR_ID, MemberRole.ADMIN); + targetIs(MemberRole.MEMBER, false); + List order = new ArrayList<>(); + when(userService.resetPassword(TARGET_ID)).thenReturn(Mono.defer(() -> { + order.add("reset"); + return Mono.just(NEW_PASSWORD); + })); + when(sessionUserService.endSessionsOfUser(TARGET_ID, null)).thenReturn(Mono.defer(() -> { + order.add("endSessions"); + return Mono.empty(); + })); + + StepVerifier.create(service.resetPassword(TARGET_ID)).expectNext(NEW_PASSWORD).verifyComplete(); + + assertThat(order).containsExactly("reset", "endSessions"); + } + + /** D-34: when a session cannot be ended, the request fails even though the password already changed. */ + @Test + void reset_sessionsNotEnded_answersTheErrorD34() { + visitorIs(VISITOR_ID, MemberRole.ADMIN); + targetIs(MemberRole.MEMBER, false); + AtomicBoolean reset = new AtomicBoolean(); + when(userService.resetPassword(TARGET_ID)).thenReturn(flagged(reset, NEW_PASSWORD)); + when(sessionUserService.endSessionsOfUser(TARGET_ID, null)).thenReturn( + Mono.error(new BizException(BizError.PASSWORD_CHANGED_SESSIONS_NOT_ENDED, "PASSWORD_CHANGED_SESSIONS_NOT_ENDED", 1))); + + StepVerifier.create(service.resetPassword(TARGET_ID)) + .expectErrorSatisfies(error -> { + assertThat(error).isInstanceOf(BizException.class); + assertThat(((BizException) error).getError()).isEqualTo(BizError.PASSWORD_CHANGED_SESSIONS_NOT_ENDED); + assertThat(((BizException) error).getMessageKey()).isEqualTo("PASSWORD_CHANGED_SESSIONS_NOT_ENDED"); + }) + .verify(); + + assertThat(reset).as("the password was changed before the sweep failed").isTrue(); } } diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserCreateInOrgPasswordRuleTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserCreateInOrgPasswordRuleTest.java new file mode 100644 index 0000000000..60b3da47d0 --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserCreateInOrgPasswordRuleTest.java @@ -0,0 +1,109 @@ +package org.lowcoder.api.usermanagement; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lowcoder.sdk.exception.BizError.NOT_AUTHORIZED; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.lowcoder.api.common.InitData; +import org.lowcoder.api.common.mockuser.WithMockUser; +import org.lowcoder.api.usermanagement.UserEndpoints.CreateUserRequest; +import org.lowcoder.domain.encryption.EncryptionService; +import org.lowcoder.domain.user.model.User; +import org.lowcoder.domain.user.repository.UserRepository; +import org.lowcoder.sdk.exception.BizException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +import lombok.extern.slf4j.Slf4j; + +/** + * Real-stack, real-MongoDB cover for the client's password rule (D-48) at an admin's create-user route + * ({@code POST /api/users/new/{orgId}} -> {@link UserController#createUserAndAddToOrg}), which the mocked + * {@code UserEndpointsContractTest} cannot exercise because it mocks {@code AuthenticationApiService} -- + * the rule lives in {@link org.lowcoder.api.authentication.request.form.FormAuthRequest}, one layer below + * that mock. + */ +@SpringBootTest +@ActiveProfiles("createUserPasswordRule") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@Slf4j +public class UserCreateInOrgPasswordRuleTest { + + private static final String ORG_ID = WithMockUser.DEFAULT_CURRENT_ORG_ID; + private static final String NON_ADMIN_USER_ID = "user02"; + private static final String WEAK_PASSWORD = "a"; + private static final String ACCEPTABLE_PASSWORD = "lowcoder1"; + + @Autowired + private UserController userController; + @Autowired + private UserRepository userRepository; + @Autowired + private EncryptionService encryptionService; + @Autowired + private InitData initData; + + @BeforeAll + public void beforeAll() { + initData.init(); + } + + private User findByEmail(String email) { + return userRepository.findByEmailOrConnections_Email(email, email).next().block(); + } + + private BizException expectFailure(String email, String password, String what) { + try { + userController.createUserAndAddToOrg(ORG_ID, new CreateUserRequest(email, password)).block(); + } catch (BizException e) { + return e; + } + throw new AssertionError("expected " + what + " to fail, but it succeeded"); + } + + @Test + @WithMockUser + void createUserAndAddToOrg_weakPassword_failsPasswordTooWeakAndStoresNothing() { + String address = "pwrule.weak@example.com"; + + BizException exception = expectFailure(address, WEAK_PASSWORD, "admin create-user with a weak password"); + log.info("[UserCreateInOrgPasswordRuleTest] weak password create -> {} / {}", exception.getError(), exception.getMessageKey()); + + assertEquals(org.lowcoder.sdk.exception.BizError.INVALID_PASSWORD, exception.getError()); + assertEquals("PASSWORD_TOO_WEAK", exception.getMessageKey()); + assertNull(findByEmail(address), "nothing may be stored for a refused password"); + } + + @Test + @WithMockUser + void createUserAndAddToOrg_acceptablePassword_createsAndStoresTheHash() { + String address = "pwrule.ok@example.com"; + + userController.createUserAndAddToOrg(ORG_ID, new CreateUserRequest(address, ACCEPTABLE_PASSWORD)).block(); + + User stored = findByEmail(address); + assertNotNull(stored, "an acceptable password must create and store the account"); + assertTrue(encryptionService.matchPassword(ACCEPTABLE_PASSWORD, stored.getPassword()), + "the stored hash must match the password that was set"); + log.info("[UserCreateInOrgPasswordRuleTest] acceptable password create -> id={}", stored.getId()); + } + + @Test + @WithMockUser(id = NON_ADMIN_USER_ID) + void createUserAndAddToOrg_nonAdminWithAWeakPassword_failsNotAuthorizedBeforeTheRuleRuns() { + String address = "pwrule.nonadmin@example.com"; + + BizException exception = expectFailure(address, WEAK_PASSWORD, "admin create-user by a non-admin"); + log.info("[UserCreateInOrgPasswordRuleTest] non-admin create -> {}", exception.getError()); + + assertEquals(NOT_AUTHORIZED, exception.getError(), + "a non-admin must be turned away by the role check, not by the password rule"); + assertNull(findByEmail(address), "nothing may be stored when the caller is not authorized"); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserSetPasswordIfAbsentMongoTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserSetPasswordIfAbsentMongoTest.java new file mode 100644 index 0000000000..30ddf0e924 --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/api/usermanagement/UserSetPasswordIfAbsentMongoTest.java @@ -0,0 +1,177 @@ +package org.lowcoder.api.usermanagement; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.UUID; + +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.lowcoder.domain.encryption.EncryptionService; +import org.lowcoder.domain.user.model.User; +import org.lowcoder.domain.user.repository.UserRepository; +import org.lowcoder.domain.user.service.UserService; +import org.lowcoder.sdk.exception.BizException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +/** + * Real-MongoDB cover for {@code UserServiceImpl#setPasswordIfAbsent} (D-49): the domain unit test + * ({@code UserServiceImplPasswordTest}) mocks {@code UserRepository}, so it never exercises the conditional + * filter {@code CustomUserRepositoryImpl#setPasswordIfAbsent} builds. This class saves real users with + * Testcontainers MongoDB and proves the filter itself, including that it is race-proof. + */ +@SpringBootTest +@ActiveProfiles("setPasswordIfAbsent") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@Slf4j +public class UserSetPasswordIfAbsentMongoTest { + + private static final String PASSWORDLESS_PASSWORD = "e2e-d49-passwordless-password"; + private static final String BLANK_STORED_PASSWORD = " "; + private static final String ORIGINAL_PASSWORD = "e2e-d49-original-password"; + private static final String ATTEMPTED_PASSWORD = "e2e-d49-attempted-password"; + private static final int RACE_ROUNDS = 20; + + @Autowired + private UserService userService; + @Autowired + private UserRepository userRepository; + @Autowired + private EncryptionService encryptionService; + + private static String uniqueName(String label) { + return "UserSetPasswordIfAbsentMongoTest." + label + "." + UUID.randomUUID(); + } + + private User save(User user) { + return userRepository.save(user).block(); + } + + private User reload(String userId) { + return userRepository.findById(userId).block(); + } + + @Test + void setPasswordIfAbsent_passwordlessUser_setsItAndEncryptsIt() { + User user = save(User.builder().name(uniqueName("passwordless")).build()); + + Boolean result = userService.setPasswordIfAbsent(user.getId(), PASSWORDLESS_PASSWORD).block(); + + assertTrue(result, "setPasswordIfAbsent on a passwordless account"); + User reloaded = reload(user.getId()); + assertTrue(encryptionService.matchPassword(PASSWORDLESS_PASSWORD, reloaded.getPassword()), + "the stored hash matches the password that was set"); + log.info("[UserSetPasswordIfAbsentMongoTest] passwordless user {} -> password set", user.getId()); + } + + @Test + void setPasswordIfAbsent_blankStoredPassword_setsItAndEncryptsIt() { + User user = save(User.builder().name(uniqueName("blank")).password(BLANK_STORED_PASSWORD).build()); + + Boolean result = userService.setPasswordIfAbsent(user.getId(), PASSWORDLESS_PASSWORD).block(); + + assertTrue(result, "setPasswordIfAbsent on a blank-password account (the regex branch of the filter)"); + User reloaded = reload(user.getId()); + assertTrue(encryptionService.matchPassword(PASSWORDLESS_PASSWORD, reloaded.getPassword()), + "the stored hash matches the password that was set"); + log.info("[UserSetPasswordIfAbsentMongoTest] blank-password user {} -> password set", user.getId()); + } + + @Test + void setPasswordIfAbsent_userWithAPassword_failsAndChangesNothing() { + String originalHash = encryptionService.encryptPassword(ORIGINAL_PASSWORD); + User user = save(User.builder().name(uniqueName("has-password")).password(originalHash).build()); + + BizException error = (BizException) catchThrowable(() -> userService.setPasswordIfAbsent(user.getId(), ATTEMPTED_PASSWORD).block()); + + assertEquals(org.lowcoder.sdk.exception.BizError.INVALID_PASSWORD, error.getError()); + assertEquals("PASSWORD_ALREADY_SET", error.getMessageKey()); + User reloaded = reload(user.getId()); + assertEquals(originalHash, reloaded.getPassword(), "the stored hash is unchanged, byte for byte"); + assertTrue(encryptionService.matchPassword(ORIGINAL_PASSWORD, reloaded.getPassword()), "still matches the original password"); + assertFalse(encryptionService.matchPassword(ATTEMPTED_PASSWORD, reloaded.getPassword()), "does not match the attempted one"); + log.info("[UserSetPasswordIfAbsentMongoTest] user {} with a password -> PASSWORD_ALREADY_SET, unchanged", user.getId()); + } + + private static Throwable catchThrowable(Runnable runnable) { + try { + runnable.run(); + } catch (Throwable t) { + return t; + } + throw new AssertionError("expected setPasswordIfAbsent to fail, but it succeeded"); + } + + /** True if {@code error} is exactly the PASSWORD_ALREADY_SET BizException the race is meant to produce; any other error is a real failure. */ + private static boolean isPasswordAlreadySet(Throwable error) { + return error instanceof BizException biz + && biz.getError() == org.lowcoder.sdk.exception.BizError.INVALID_PASSWORD + && "PASSWORD_ALREADY_SET".equals(biz.getMessageKey()); + } + + /** + * Maps an error of one of the two concurrent calls to "lost" (PASSWORD_ALREADY_SET, the expected outcome for + * the call the conditional update refuses); any other error is a real failure, never a race loss, so it is + * logged with the round and call it came from and re-emitted wrapped in an {@link AssertionError} that carries + * that context, instead of a bare rethrow that would otherwise lose which round and which call (A or B) failed. + */ + private static Mono rethrowWithRound(int round, String call, Throwable error) { + if (isPasswordAlreadySet(error)) { + return Mono.just("PASSWORD_ALREADY_SET"); + } + log.error("[UserSetPasswordIfAbsentMongoTest] round {} call {}: unexpected error", round, call, error); + return Mono.error(new AssertionError("round " + round + " call " + call + ": unexpected error " + error, error)); + } + + /** + * Two concurrent {@code setPasswordIfAbsent} calls on one passwordless account: the single conditional update + * guarantees exactly one wins and the other sees PASSWORD_ALREADY_SET, never both succeeding and never the + * second one overwriting the winner. A pass does not prove the two updates interleaved in this particular + * round; the filter is what guarantees it (inverted in the plan's section 6 step 2, which removes the filter + * and shows this test then fails). + */ + @RepeatedTest(RACE_ROUNDS) + void setPasswordIfAbsent_concurrentCallsOnOnePasswordlessAccount_exactlyOneWins(org.junit.jupiter.api.RepetitionInfo repetitionInfo) { + int round = repetitionInfo.getCurrentRepetition(); + User user = save(User.builder().name(uniqueName("race-" + round)).build()); + String passwordA = "e2e-d49-race-a-" + round; + String passwordB = "e2e-d49-race-b-" + round; + + Mono callA = userService.setPasswordIfAbsent(user.getId(), passwordA) + .map(ignored -> passwordA) + .onErrorResume(e -> rethrowWithRound(round, "A", e)) + .subscribeOn(Schedulers.parallel()); + Mono callB = userService.setPasswordIfAbsent(user.getId(), passwordB) + .map(ignored -> passwordB) + .onErrorResume(e -> rethrowWithRound(round, "B", e)) + .subscribeOn(Schedulers.parallel()); + + var outcomes = Mono.zip(callA, callB).block(); + String outcomeA = outcomes.getT1(); + String outcomeB = outcomes.getT2(); + + String winner; + if (!"PASSWORD_ALREADY_SET".equals(outcomeA) && "PASSWORD_ALREADY_SET".equals(outcomeB)) { + winner = outcomeA; + } else if ("PASSWORD_ALREADY_SET".equals(outcomeA) && !"PASSWORD_ALREADY_SET".equals(outcomeB)) { + winner = outcomeB; + } else { + throw new AssertionError("round " + round + ": expected exactly one winner and one PASSWORD_ALREADY_SET, got A=" + + outcomeA + " B=" + outcomeB); + } + String loser = winner.equals(passwordA) ? passwordB : passwordA; + + User reloaded = reload(user.getId()); + assertTrue(encryptionService.matchPassword(winner, reloaded.getPassword()), "round " + round + ": the stored hash matches the winner"); + assertFalse(encryptionService.matchPassword(loser, reloaded.getPassword()), "round " + round + ": the stored hash does not match the loser"); + log.info("[UserSetPasswordIfAbsentMongoTest] race round {}: winner={} loser=PASSWORD_ALREADY_SET", round, winner.equals(passwordA) ? "A" : "B"); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/bundle/BundleRepositoryFindByOrganizationIdMongoTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/bundle/BundleRepositoryFindByOrganizationIdMongoTest.java new file mode 100644 index 0000000000..952073730f --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/bundle/BundleRepositoryFindByOrganizationIdMongoTest.java @@ -0,0 +1,71 @@ +package org.lowcoder.domain.bundle; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; +import java.util.List; + +import org.bson.types.ObjectId; +import org.junit.jupiter.api.Test; +import org.lowcoder.api.ServerApplication; +import org.lowcoder.domain.bundle.model.Bundle; +import org.lowcoder.domain.bundle.repository.BundleRepository; +import org.lowcoder.sdk.constants.FieldName; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.mongodb.core.ReactiveMongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.test.context.ActiveProfiles; + +/** + * {@link BundleRepository#findByOrganizationId} against the MongoDB test container (D-60): two bundles stored under + * one organization and one under another must answer exactly the two, by id, never the third. + */ +@SpringBootTest(classes = ServerApplication.class) +@ActiveProfiles("test") +class BundleRepositoryFindByOrganizationIdMongoTest { + + private static final Duration TIMEOUT = Duration.ofSeconds(30); + private static final String LOG_PREFIX = "[BundleRepositoryFindByOrganizationIdMongoTest] "; + + @Autowired + private BundleRepository repository; + @Autowired + private ReactiveMongoTemplate mongo; + + private static String id() { + return new ObjectId().toHexString(); + } + + private Bundle saveBundle(String organizationId, String gid) { + Bundle bundle = Bundle.builder().name("find-by-org-bundle-" + gid).gid(gid).organizationId(organizationId).build(); + return mongo.save(bundle).block(TIMEOUT); + } + + @Test + void findByOrganizationIdAnswersExactlyThatOrganizationsBundlesD60() { + String orgX = id(); + String orgY = id(); + String gidX1 = id(); + String gidX2 = id(); + String gidY = id(); + Bundle x1 = saveBundle(orgX, gidX1); + Bundle x2 = saveBundle(orgX, gidX2); + Bundle y = saveBundle(orgY, gidY); + + try { + List foundForX = repository.findByOrganizationId(orgX).map(Bundle::getId).collectList().block(TIMEOUT); + List foundForY = repository.findByOrganizationId(orgY).map(Bundle::getId).collectList().block(TIMEOUT); + + System.out.println(LOG_PREFIX + "org X bundles: " + foundForX + "; org Y bundles: " + foundForY); + assertThat(foundForX).as("bundles of org X").containsExactlyInAnyOrder(x1.getId(), x2.getId()); + assertThat(foundForY).as("bundles of org Y").containsExactly(y.getId()); + } finally { + long removed = mongo.remove(Query.query(Criteria.where(FieldName.GID).in(List.of(gidX1, gidX2, gidY))), Bundle.class) + .block(TIMEOUT).getDeletedCount(); + System.out.println(LOG_PREFIX + "removed " + removed + " of the 3 bundle(s) the test stored"); + assertThat(removed).as("bundles removed").isEqualTo(3); + } + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/permission/ResourcePermissionBatchWorkspaceMongoTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/permission/ResourcePermissionBatchWorkspaceMongoTest.java new file mode 100644 index 0000000000..001b07c0a5 --- /dev/null +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/domain/permission/ResourcePermissionBatchWorkspaceMongoTest.java @@ -0,0 +1,366 @@ +package org.lowcoder.domain.permission; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.DoubleStream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.lowcoder.api.ServerApplication; +import org.lowcoder.domain.application.model.Application; +import org.lowcoder.domain.application.service.ApplicationService; +import org.lowcoder.domain.bundle.model.Bundle; +import org.lowcoder.domain.bundle.service.BundleService; +import org.lowcoder.domain.datasource.model.Datasource; +import org.lowcoder.domain.datasource.model.DatasourceCreationSource; +import org.lowcoder.domain.datasource.model.DatasourceStatus; +import org.lowcoder.domain.datasource.repository.DatasourceRepository; +import org.lowcoder.domain.group.model.Group; +import org.lowcoder.domain.group.service.GroupMemberService; +import org.lowcoder.domain.organization.model.MemberRole; +import org.lowcoder.domain.organization.model.Organization; +import org.lowcoder.domain.organization.model.OrganizationState; +import org.lowcoder.domain.organization.service.OrgMemberService; +import org.lowcoder.domain.permission.model.ResourceAction; +import org.lowcoder.domain.permission.model.ResourceRole; +import org.lowcoder.domain.permission.service.ResourcePermissionService; +import org.lowcoder.domain.plugin.client.DatasourcePluginClient; +import org.lowcoder.domain.plugin.service.DatasourceMetaInfoService; +import org.lowcoder.sdk.exception.BizError; +import org.lowcoder.sdk.exception.BizException; +import org.lowcoder.sdk.models.JsDatasourceConnectionConfig; +import org.lowcoder.sdk.util.IDUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.mongodb.core.ReactiveMongoTemplate; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestPropertySource; + +import reactor.core.publisher.Mono; + +/** + * {@code ResourcePermissionService.getMaxMatchingPermission} / {@code checkResourcePermissionWithError} against the + * MongoDB test container (D-38): every id of a batch is decided in its OWN workspace instead of the first id's. Own + * Spring context (extra property, hence its own database), the pattern of {@code DatasourceRepositoryMongoTest}: a + * mocked {@code DatasourceMetaInfoService} (every type is a JS data source) and a mocked {@code DatasourcePluginClient} + * (no plugin definition). Every test generates its own ids; no seed data. + */ +@SpringBootTest(classes = ServerApplication.class) +@ActiveProfiles("test") +@TestPropertySource(properties = "d38.context=batch-workspace") +class ResourcePermissionBatchWorkspaceMongoTest { + + private static final Duration TIMEOUT = Duration.ofSeconds(30); + private static final String LOG_PREFIX = "[ResourcePermissionBatchWorkspaceMongoTest] "; + + @MockBean + private DatasourceMetaInfoService datasourceMetaInfoService; + @MockBean + private DatasourcePluginClient datasourcePluginClient; + @Autowired + private ReactiveMongoTemplate mongo; + @Autowired + private OrgMemberService orgMemberService; + @Autowired + private GroupMemberService groupMemberService; + @Autowired + private ResourcePermissionService resourcePermissionService; + @Autowired + private ApplicationService applicationService; + @Autowired + private BundleService bundleService; + @Autowired + private DatasourceRepository datasourceRepository; + + private final String userId = "user-" + IDUtils.generate(); + + private static String newId() { + return IDUtils.generate(); + } + + private String createOrg() { + Organization org = Organization.builder().name("org-" + newId()).gid(newId()).state(OrganizationState.ACTIVE).build(); + return mongo.save(org).block(TIMEOUT).getId(); + } + + private void addMember(String orgId, MemberRole role) { + orgMemberService.addMember(orgId, userId, role).block(TIMEOUT); + } + + private String createGroup(String orgId) { + return mongo.save(Group.builder().organizationId(orgId).name("group-" + newId()).build()).block(TIMEOUT).getId(); + } + + private void addGroupMember(String orgId, String groupId) { + groupMemberService.addMember(orgId, groupId, userId, MemberRole.MEMBER).block(TIMEOUT); + } + + private void grantUser(String resourceId, org.lowcoder.domain.permission.model.ResourceType type, ResourceRole role) { + resourcePermissionService.addResourcePermissionToUser(resourceId, userId, role, type).block(TIMEOUT); + } + + private void grantGroup(String resourceId, org.lowcoder.domain.permission.model.ResourceType type, String groupId, ResourceRole role) { + resourcePermissionService.insertBatchPermission(type, resourceId, null, Set.of(groupId), role).block(TIMEOUT); + } + + private String createApp(String orgId) { + Application application = Application.builder().organizationId(orgId).name("app-" + newId()).gid(UUID.randomUUID().toString()) + .editingApplicationDSL(new HashMap<>()).build(); + return mongo.save(application).block(TIMEOUT).getId(); + } + + private String createAppWithSlug(String orgId, String slug) { + Application application = Application.builder().organizationId(orgId).name("app-" + newId()).gid(UUID.randomUUID().toString()) + .slug(slug).editingApplicationDSL(new HashMap<>()).build(); + return mongo.save(application).block(TIMEOUT).getId(); + } + + private String createBundle(String orgId) { + Bundle bundle = Bundle.builder().organizationId(orgId).name("bundle-" + newId()).gid(UUID.randomUUID().toString()).build(); + return mongo.save(bundle).block(TIMEOUT).getId(); + } + + private String createDatasource(String orgId) { + JsDatasourceConnectionConfig config = new JsDatasourceConnectionConfig(); + config.put("host", "db.example"); + Datasource datasource = Datasource.builder().organizationId(orgId).name("ds-" + newId()).type("someJsPlugin") + .gid(UUID.randomUUID().toString()).creationSource(DatasourceCreationSource.USER_CREATED.getValue()) + .datasourceStatus(DatasourceStatus.NORMAL).detailConfig(config).build(); + return datasourceRepository.save(datasource).block(TIMEOUT).getId(); + } + + private Map maxMatching(List ids, ResourceAction action) { + Map answer = + resourcePermissionService.getMaxMatchingPermission(userId, ids, action).block(TIMEOUT); + Map roles = new HashMap<>(); + answer.forEach((id, permission) -> roles.put(id, permission.getResourceRole())); + return roles; + } + + @org.junit.jupiter.api.BeforeEach + void everyTypeIsAJsDatasourceWithoutADefinition() { + when(datasourceMetaInfoService.isJsDatasourcePlugin(anyString())).thenReturn(true); + when(datasourcePluginClient.getDatasourcePluginDefinition(anyString())).thenReturn(Mono.empty()); + } + + /** Catches a batch answer diverging from each id's own one-id answer in the same workspace. */ + @Test + void applicationsOfOneWorkspace_batchAnswerEqualsEachOneIdAnswer() { + String orgId = createOrg(); + addMember(orgId, MemberRole.MEMBER); + String groupId = createGroup(orgId); + addGroupMember(orgId, groupId); + String a1 = createApp(orgId); + String a2 = createApp(orgId); + String a3 = createApp(orgId); + grantUser(a1, org.lowcoder.domain.permission.model.ResourceType.APPLICATION, ResourceRole.EDITOR); + grantGroup(a2, org.lowcoder.domain.permission.model.ResourceType.APPLICATION, groupId, ResourceRole.VIEWER); + + Map batch = maxMatching(List.of(a1, a2, a3), ResourceAction.READ_APPLICATIONS); + + assertThat(batch).containsExactlyInAnyOrderEntriesOf(Map.of(a1, ResourceRole.EDITOR, a2, ResourceRole.VIEWER)); + for (String id : List.of(a1, a2, a3)) { + var oneId = resourcePermissionService.getMaxMatchingPermission(userId, id, ResourceAction.READ_APPLICATIONS).blockOptional(TIMEOUT); + if (batch.containsKey(id)) { + assertThat(oneId).isPresent(); + assertThat(oneId.get().getResourceRole()).isEqualTo(batch.get(id)); + } else { + assertThat(oneId).isEmpty(); + } + } + System.out.println(LOG_PREFIX + "applications of one workspace: batch answer equals each one-id answer"); + } + + /** Data source analogue of the test above. */ + @Test + void datasourcesOfOneWorkspace_batchAnswerEqualsEachOneIdAnswer() { + String orgId = createOrg(); + addMember(orgId, MemberRole.MEMBER); + String groupId = createGroup(orgId); + addGroupMember(orgId, groupId); + String d1 = createDatasource(orgId); + String d2 = createDatasource(orgId); + String d3 = createDatasource(orgId); + grantUser(d1, org.lowcoder.domain.permission.model.ResourceType.DATASOURCE, ResourceRole.OWNER); + grantGroup(d2, org.lowcoder.domain.permission.model.ResourceType.DATASOURCE, groupId, ResourceRole.VIEWER); + + Map batch = maxMatching(List.of(d1, d2, d3), ResourceAction.USE_DATASOURCES); + + assertThat(batch).containsExactlyInAnyOrderEntriesOf(Map.of(d1, ResourceRole.OWNER, d2, ResourceRole.VIEWER)); + for (String id : List.of(d1, d2, d3)) { + var oneId = resourcePermissionService.getMaxMatchingPermission(userId, id, ResourceAction.USE_DATASOURCES).blockOptional(TIMEOUT); + if (batch.containsKey(id)) { + assertThat(oneId).isPresent(); + assertThat(oneId.get().getResourceRole()).isEqualTo(batch.get(id)); + } else { + assertThat(oneId).isEmpty(); + } + } + System.out.println(LOG_PREFIX + "data sources of one workspace: batch answer equals each one-id answer"); + } + + static List> bothOrders() { + return List.of(List.of(0, 1, 2), List.of(2, 1, 0)); + } + + /** Catches D-38 on the bundle list: a bundle the user created in a workspace it never joined getting the first + * bundle's workspace and admin role instead of being decided in its own. */ + @ParameterizedTest + @MethodSource("bothOrders") + void bundlesCreatedInThreeWorkspaces_eachIsDecidedByItsOwnMembership(List order) { + String w1 = createOrg(); + addMember(w1, MemberRole.ADMIN); + String w2 = createOrg(); + addMember(w2, MemberRole.MEMBER); + String g2 = createGroup(w2); + addGroupMember(w2, g2); + String w3 = createOrg(); + String b1 = createBundle(w1); + String b2 = createBundle(w2); + String b3 = createBundle(w3); + grantGroup(b2, org.lowcoder.domain.permission.model.ResourceType.BUNDLE, g2, ResourceRole.VIEWER); + grantUser(b3, org.lowcoder.domain.permission.model.ResourceType.BUNDLE, ResourceRole.OWNER); + List all = List.of(b1, b2, b3); + List ids = order.stream().map(all::get).toList(); + + Map batch = maxMatching(ids, ResourceAction.READ_BUNDLES); + + assertThat(batch).containsExactlyInAnyOrderEntriesOf(Map.of(b1, ResourceRole.OWNER, b2, ResourceRole.VIEWER)); + assertThat(batch).as("b3: never a member of w3, its stored OWNER row from creation does not count").doesNotContainKey(b3); + System.out.println(LOG_PREFIX + "orders " + order + ": b1 OWNER (admin of w1), b2 VIEWER (group in w2), b3 absent (never in w3)"); + } + + static List> twoOrders() { + return List.of(List.of(0, 1), List.of(1, 0)); + } + + /** Catches D-38 on the nav layout / cross-workspace sub-application case. */ + @ParameterizedTest + @MethodSource("twoOrders") + void subApplicationsOfTwoWorkspaces_eachIsDecidedByItsOwnMembership(List order) { + String w1 = createOrg(); + addMember(w1, MemberRole.ADMIN); + String w2 = createOrg(); + addMember(w2, MemberRole.MEMBER); + String a1 = createApp(w1); + String x1 = createApp(w2); + List all = List.of(a1, x1); + List ids = order.stream().map(all::get).toList(); + + Map batch = maxMatching(ids, ResourceAction.READ_APPLICATIONS); + + assertThat(batch).containsExactlyInAnyOrderEntriesOf(Map.of(a1, ResourceRole.OWNER)); + assertThat(batch).as("x1: a plain member of w2 without a grant").doesNotContainKey(x1); + System.out.println(LOG_PREFIX + "orders " + order + ": a1 OWNER (admin of w1), x1 absent (member of w2, no grant)"); + } + + /** D-38's own repro: an admin role in one workspace must not grant USE of another workspace's data source. */ + @ParameterizedTest + @MethodSource("twoOrders") + void datasourcesOfTwoWorkspaces_adminRoleElsewhereGrantsNothing(List order) { + String w1 = createOrg(); + addMember(w1, MemberRole.ADMIN); + String w2 = createOrg(); + addMember(w2, MemberRole.MEMBER); + String dA = createDatasource(w1); + String dB = createDatasource(w2); + List all = List.of(dA, dB); + List ids = order.stream().map(all::get).toList(); + + Map batch = maxMatching(ids, ResourceAction.USE_DATASOURCES); + + assertThat(batch).containsExactlyInAnyOrderEntriesOf(Map.of(dA, ResourceRole.OWNER)); + assertThat(batch).as("dB: w1's admin role grants nothing in w2").doesNotContainKey(dB); + System.out.println(LOG_PREFIX + "orders " + order + ": dA OWNER (admin of w1), dB absent (member of w2 only)"); + } + + /** Catches an unknown application id failing the whole batch, and pins the one-id contract is unchanged. */ + @Test + void batchWithAnUnknownApplicationId_leavesItOut_oneUnknownIdStillFails() { + String orgId = createOrg(); + addMember(orgId, MemberRole.ADMIN); + String a1 = createApp(orgId); + String unusedId = "unused-" + newId(); + + for (List order : List.of(List.of(a1, unusedId), List.of(unusedId, a1))) { + Map batch = maxMatching(order, ResourceAction.READ_APPLICATIONS); + assertThat(batch).containsExactlyInAnyOrderEntriesOf(Map.of(a1, ResourceRole.OWNER)); + } + + assertThatThrownBy(() -> resourcePermissionService.checkResourcePermissionWithError(userId, unusedId, ResourceAction.READ_APPLICATIONS) + .block(TIMEOUT)) + .isInstanceOf(BizException.class) + .extracting(error -> ((BizException) error).getError()) + .isEqualTo(BizError.NO_RESOURCE_FOUND); + System.out.println(LOG_PREFIX + "an unknown application id in a batch is left out; a single unknown id still fails"); + } + + /** Catches an application slug two applications share failing or borrowing an answer in a batch (D-38). */ + @ParameterizedTest + @MethodSource("sharedSlugOrders") + void batchWithASharedApplicationSlug_leavesItOut_oneSharedSlugStillFails(List order) { + String w1 = createOrg(); + addMember(w1, MemberRole.ADMIN); + String w2 = createOrg(); + String slug = "d38shared" + IDUtils.generate(); + String a1 = createApp(w1); + String s1 = createAppWithSlug(w1, slug); + createAppWithSlug(w2, slug); + List all = List.of(a1, s1, slug); + List ids = order.stream().map(all::get).toList(); + + Map batch = maxMatching(ids, ResourceAction.READ_APPLICATIONS); + + assertThat(batch).containsExactlyInAnyOrderEntriesOf(Map.of(a1, ResourceRole.OWNER, s1, ResourceRole.OWNER)); + assertThatThrownBy(() -> resourcePermissionService.checkResourcePermissionWithError(userId, slug, ResourceAction.READ_APPLICATIONS) + .block(TIMEOUT)) + .isInstanceOf(BizException.class) + .extracting(error -> ((BizException) error).getError()) + .isEqualTo(BizError.NO_RESOURCE_FOUND); + System.out.println(LOG_PREFIX + "orders " + order + ": a shared slug in a batch is left out, not failing the batch; alone it still fails"); + } + + static List> sharedSlugOrders() { + return List.of(List.of(0, 1, 2), List.of(2, 1, 0)); + } + + /** Batch cost of 200 applications of one workspace: median/p95 over 20 timed runs after 5 warm-ups. */ + @Test + void twoHundredApplicationsOfOneWorkspace_answerEveryIdAndPrintTheCost() { + String orgId = createOrg(); + addMember(orgId, MemberRole.MEMBER); + List ids = new ArrayList<>(); + for (int i = 0; i < 200; i++) { + String id = createApp(orgId); + grantUser(id, org.lowcoder.domain.permission.model.ResourceType.APPLICATION, ResourceRole.VIEWER); + ids.add(id); + } + + for (int warmup = 0; warmup < 5; warmup++) { + maxMatching(ids, ResourceAction.READ_APPLICATIONS); + } + double[] millis = new double[20]; + for (int run = 0; run < 20; run++) { + long start = System.nanoTime(); + Map batch = maxMatching(ids, ResourceAction.READ_APPLICATIONS); + millis[run] = (System.nanoTime() - start) / 1_000_000.0; + assertThat(batch).hasSize(200); + } + double[] sorted = DoubleStream.of(millis).sorted().toArray(); + double median = sorted[sorted.length / 2]; + double p95 = sorted[(int) Math.min(sorted.length - 1, Math.round(sorted.length * 0.95))]; + System.out.println(LOG_PREFIX + "200 applications of one workspace: median " + median + " ms, p95 " + p95 + " ms over 20 runs"); + } +} diff --git a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/runner/eventlistener/OrgAndGroupEventListenerTest.java b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/runner/eventlistener/OrgAndGroupEventListenerTest.java index 4b603e19d0..e06b99730f 100644 --- a/server/api-service/lowcoder-server/src/test/java/org/lowcoder/runner/eventlistener/OrgAndGroupEventListenerTest.java +++ b/server/api-service/lowcoder-server/src/test/java/org/lowcoder/runner/eventlistener/OrgAndGroupEventListenerTest.java @@ -27,10 +27,14 @@ import org.lowcoder.domain.application.model.Application; import org.lowcoder.domain.application.model.ApplicationStatus; import org.lowcoder.domain.application.service.ApplicationService; +import org.lowcoder.domain.bundle.model.Bundle; +import org.lowcoder.domain.bundle.service.BundleService; import org.lowcoder.domain.datasource.model.Datasource; import org.lowcoder.domain.datasource.model.DatasourceStatus; import org.lowcoder.domain.datasource.repository.DatasourceRepository; import org.lowcoder.domain.datasource.service.DatasourceService; +import org.lowcoder.domain.folder.model.Folder; +import org.lowcoder.domain.folder.service.FolderService; import org.lowcoder.domain.group.event.GroupDeletedEvent; import org.lowcoder.domain.group.model.Group; import org.lowcoder.domain.group.service.GroupMemberService; @@ -73,6 +77,8 @@ class OrgAndGroupEventListenerTest { private static final String APP_2 = "app-2"; private static final String DATASOURCE_1 = "ds-1"; private static final String DATASOURCE_2 = "ds-2"; + private static final String FOLDER_1 = "folder-1"; + private static final String BUNDLE_1 = "bundle-1"; private static final String SCHEDULER_THREAD = "org-event-async-executor"; private static final long WAIT_SECONDS = 10; private static final int RETRIES = 3; @@ -85,6 +91,8 @@ class OrgAndGroupEventListenerTest { private DatasourceService datasourceService; private ResourcePermissionService resourcePermissionService; private DatasourceRepository datasourceRepository; + private FolderService folderService; + private BundleService bundleService; private final List events = new CopyOnWriteArrayList<>(); private final List dropped = new CopyOnWriteArrayList<>(); @@ -102,6 +110,8 @@ void setUp() { datasourceService = mock(DatasourceService.class); resourcePermissionService = mock(ResourcePermissionService.class); datasourceRepository = mock(DatasourceRepository.class); + folderService = mock(FolderService.class); + bundleService = mock(BundleService.class); ReflectionTestUtils.setField(listener, "orgMemberService", orgMemberService); ReflectionTestUtils.setField(listener, "groupService", groupService); ReflectionTestUtils.setField(listener, "groupMemberService", groupMemberService); @@ -109,6 +119,8 @@ void setUp() { ReflectionTestUtils.setField(listener, "datasourceService", datasourceService); ReflectionTestUtils.setField(listener, "resourcePermissionService", resourcePermissionService); ReflectionTestUtils.setField(listener, "datasourceRepository", datasourceRepository); + ReflectionTestUtils.setField(listener, "folderService", folderService); + ReflectionTestUtils.setField(listener, "bundleService", bundleService); Hooks.onErrorDropped(error -> { dropped.add(error); Throwable expected = expectedFailure; @@ -135,6 +147,18 @@ private static Datasource datasource(String id) { return Datasource.builder().id(id).build(); } + private static Folder folder(String id) { + Folder folder = new Folder(); + folder.setId(id); + return folder; + } + + private static Bundle bundle(String id) { + Bundle bundle = Bundle.builder().build(); + bundle.setId(id); + return bundle; + } + private static void await(CountDownLatch latch, String what) throws InterruptedException { assertThat(latch.await(WAIT_SECONDS, TimeUnit.SECONDS)).as("waited for: " + what).isTrue(); } @@ -450,12 +474,16 @@ void onGroupDeleted_givesUpAfterThreeRetries_withoutRaisingToTheCaller() throws // ------------------------------------------------------------------ onUserLeaveOrg - private void stubOrgContents(List groups, List apps, List datasources) { + private void stubOrgContents(List groups, List apps, List datasources, List folders, List bundles) { when(groupService.getByOrgId(ORG_ID)).thenReturn(Flux.fromIterable(groups.stream().map(OrgAndGroupEventListenerTest::group).toList())); when(applicationService.findByOrganizationIdWithoutDsl(ORG_ID)) .thenReturn(Flux.fromIterable(apps.stream().map(OrgAndGroupEventListenerTest::application).toList())); when(datasourceService.getByOrgId(ORG_ID)) .thenReturn(Flux.fromIterable(datasources.stream().map(OrgAndGroupEventListenerTest::datasource).toList())); + when(folderService.findByOrganizationId(ORG_ID)) + .thenReturn(Flux.fromIterable(folders.stream().map(OrgAndGroupEventListenerTest::folder).toList())); + when(bundleService.findByOrganizationId(ORG_ID)) + .thenReturn(Flux.fromIterable(bundles.stream().map(OrgAndGroupEventListenerTest::bundle).toList())); } /** @@ -464,10 +492,10 @@ private void stubOrgContents(List groups, List apps, List threads = new CopyOnWriteArrayList<>(); - stubOrgContents(List.of(GROUP_1, GROUP_2), List.of(APP_1, APP_2), List.of(DATASOURCE_1)); + stubOrgContents(List.of(GROUP_1, GROUP_2), List.of(APP_1, APP_2), List.of(DATASOURCE_1), List.of(FOLDER_1), List.of(BUNDLE_1)); for (String groupId : List.of(GROUP_1, GROUP_2)) { when(groupMemberService.removeMember(groupId, USER_ID)).thenReturn(Mono.defer(() -> { events.add("group " + groupId); @@ -490,28 +518,42 @@ void onUserLeaveOrg_removesTheUserFromEveryGroup_andEveryApplicationAndDatasourc removals.countDown(); return Mono.just(true); })); + when(resourcePermissionService.removeUserFolderPermission(FOLDER_1, USER_ID)).thenReturn(Mono.defer(() -> { + events.add("folder " + FOLDER_1); + threads.add(Thread.currentThread().getName()); + removals.countDown(); + return Mono.just(true); + })); + when(resourcePermissionService.removeUserBundlePermission(BUNDLE_1, USER_ID)).thenReturn(Mono.defer(() -> { + events.add("bundle " + BUNDLE_1); + threads.add(Thread.currentThread().getName()); + removals.countDown(); + return Mono.just(true); + })); listener.onUserLeaveOrg(new OrgMemberLeftEvent(ORG_ID, USER_ID)); - await(removals, "the five removals"); + await(removals, "the seven removals"); assertThat(Set.copyOf(events)).containsExactlyInAnyOrder("group " + GROUP_1, "group " + GROUP_2, - "application " + APP_1, "application " + APP_2, "datasource " + DATASOURCE_1); - assertThat(events).hasSize(5); - assertThat(threads).as("every part runs on the listener's scheduler, none on the caller").hasSize(5) + "application " + APP_1, "application " + APP_2, "datasource " + DATASOURCE_1, "folder " + FOLDER_1, "bundle " + BUNDLE_1); + assertThat(events).hasSize(7); + assertThat(threads).as("every part runs on the listener's scheduler, none on the caller").hasSize(7) .allSatisfy(name -> assertThat(name).isEqualTo(SCHEDULER_THREAD)); verify(applicationService).findByOrganizationIdWithoutDsl(ORG_ID); } @Test - void onUserLeaveOrg_anOrgWithoutGroupsApplicationsOrDatasources_callsNoRemoval() throws InterruptedException { - CountDownLatch listed = new CountDownLatch(3); + void onUserLeaveOrg_anOrgWithoutGroupsApplicationsDatasourcesFoldersOrBundles_callsNoRemoval() throws InterruptedException { + CountDownLatch listed = new CountDownLatch(5); when(groupService.getByOrgId(ORG_ID)).thenReturn(Flux.defer(() -> Flux.empty().doOnComplete(listed::countDown))); when(applicationService.findByOrganizationIdWithoutDsl(ORG_ID)) .thenReturn(Flux.defer(() -> Flux.empty().doOnComplete(listed::countDown))); when(datasourceService.getByOrgId(ORG_ID)).thenReturn(Flux.defer(() -> Flux.empty().doOnComplete(listed::countDown))); + when(folderService.findByOrganizationId(ORG_ID)).thenReturn(Flux.defer(() -> Flux.empty().doOnComplete(listed::countDown))); + when(bundleService.findByOrganizationId(ORG_ID)).thenReturn(Flux.defer(() -> Flux.empty().doOnComplete(listed::countDown))); listener.onUserLeaveOrg(new OrgMemberLeftEvent(ORG_ID, USER_ID)); - await(listed, "the three listings"); + await(listed, "the five listings"); verifyNoInteractions(groupMemberService, resourcePermissionService); assertThat(dropped).isEmpty(); @@ -523,8 +565,10 @@ void onUserLeaveOrg_eachPartRetries_aTransientFailureStillCleansEverything() thr AtomicInteger groupAttempts = new AtomicInteger(); AtomicInteger appAttempts = new AtomicInteger(); AtomicInteger datasourceAttempts = new AtomicInteger(); - CountDownLatch done = new CountDownLatch(3); - stubOrgContents(List.of(GROUP_1), List.of(APP_1), List.of(DATASOURCE_1)); + AtomicInteger folderAttempts = new AtomicInteger(); + AtomicInteger bundleAttempts = new AtomicInteger(); + CountDownLatch done = new CountDownLatch(5); + stubOrgContents(List.of(GROUP_1), List.of(APP_1), List.of(DATASOURCE_1), List.of(FOLDER_1), List.of(BUNDLE_1)); when(groupMemberService.removeMember(GROUP_1, USER_ID)).thenReturn(Mono.defer(() -> { if (groupAttempts.incrementAndGet() <= 2) { return Mono.error(new IllegalStateException("transient group")); @@ -546,24 +590,40 @@ void onUserLeaveOrg_eachPartRetries_aTransientFailureStillCleansEverything() thr done.countDown(); return Mono.just(true); })); + when(resourcePermissionService.removeUserFolderPermission(FOLDER_1, USER_ID)).thenReturn(Mono.defer(() -> { + if (folderAttempts.incrementAndGet() <= 2) { + return Mono.error(new IllegalStateException("transient folder")); + } + done.countDown(); + return Mono.just(true); + })); + when(resourcePermissionService.removeUserBundlePermission(BUNDLE_1, USER_ID)).thenReturn(Mono.defer(() -> { + if (bundleAttempts.incrementAndGet() <= 2) { + return Mono.error(new IllegalStateException("transient bundle")); + } + done.countDown(); + return Mono.just(true); + })); listener.onUserLeaveOrg(new OrgMemberLeftEvent(ORG_ID, USER_ID)); - await(done, "all three parts to succeed after two failures each"); + await(done, "all five parts to succeed after two failures each"); assertThat(groupAttempts.get()).isEqualTo(3); assertThat(appAttempts.get()).isEqualTo(3); assertThat(datasourceAttempts.get()).isEqualTo(3); + assertThat(folderAttempts.get()).isEqualTo(3); + assertThat(bundleAttempts.get()).isEqualTo(3); assertThat(dropped).isEmpty(); } - /** A part that always fails is attempted 1 + 3 times, for each of the three parts on its own. */ + /** A part that always fails is attempted 1 + 3 times, for each of the five parts on its own. */ @ParameterizedTest(name = "always failing part: {0}") - @ValueSource(strings = {"group", "application", "datasource"}) + @ValueSource(strings = {"group", "application", "datasource", "folder", "bundle"}) void onUserLeaveOrg_aPartThatAlwaysFails_isAttemptedFourTimes(String part) throws InterruptedException { IllegalStateException failure = new IllegalStateException("permanent " + part); expectedFailure = failure; AtomicInteger attempts = new AtomicInteger(); - stubOrgContents(List.of(GROUP_1), List.of(APP_1), List.of(DATASOURCE_1)); + stubOrgContents(List.of(GROUP_1), List.of(APP_1), List.of(DATASOURCE_1), List.of(FOLDER_1), List.of(BUNDLE_1)); Mono failing = Mono.defer(() -> { attempts.incrementAndGet(); return Mono.error(failure); @@ -573,6 +633,10 @@ void onUserLeaveOrg_aPartThatAlwaysFails_isAttemptedFourTimes(String part) throw .thenReturn("application".equals(part) ? failing : Mono.just(true)); when(resourcePermissionService.removeUserDatasourcePermission(DATASOURCE_1, USER_ID)) .thenReturn("datasource".equals(part) ? failing : Mono.just(true)); + when(resourcePermissionService.removeUserFolderPermission(FOLDER_1, USER_ID)) + .thenReturn("folder".equals(part) ? failing : Mono.just(true)); + when(resourcePermissionService.removeUserBundlePermission(BUNDLE_1, USER_ID)) + .thenReturn("bundle".equals(part) ? failing : Mono.just(true)); listener.onUserLeaveOrg(new OrgMemberLeftEvent(ORG_ID, USER_ID)); await(droppedLatch, "the end of the failing handler"); @@ -598,7 +662,7 @@ void onUserLeaveOrg_aPersistentFailureDoesNotCancelTheOtherParts() throws Interr AtomicInteger applicationCancelled = new AtomicInteger(); AtomicInteger applicationCompleted = new AtomicInteger(); AtomicReference> applicationSink = new AtomicReference<>(); - stubOrgContents(List.of(GROUP_1), List.of(APP_1), List.of()); + stubOrgContents(List.of(GROUP_1), List.of(APP_1), List.of(), List.of(), List.of()); when(groupMemberService.removeMember(GROUP_1, USER_ID)).thenReturn(Mono.defer(() -> { groupGaveUp.countDown(); return Mono.error(failure); @@ -623,4 +687,76 @@ void onUserLeaveOrg_aPersistentFailureDoesNotCancelTheOtherParts() throws Interr assertThat(droppedFailure(failure)).isTrue(); say("group part failed for good -> application part not cancelled, finished; then the handler ended with the error"); } + + /** D-60: a persistent folder-removal failure does not cancel the still-running application part, same shape as the group case. */ + @Test + void onUserLeaveOrg_aPersistentFolderFailureDoesNotCancelTheOtherParts() throws InterruptedException { + IllegalStateException failure = new IllegalStateException("permanent folder failure"); + expectedFailure = failure; + CountDownLatch applicationInFlight = new CountDownLatch(1); + CountDownLatch folderGaveUp = new CountDownLatch(1 + RETRIES); + AtomicInteger applicationCancelled = new AtomicInteger(); + AtomicInteger applicationCompleted = new AtomicInteger(); + AtomicReference> applicationSink = new AtomicReference<>(); + stubOrgContents(List.of(), List.of(APP_1), List.of(), List.of(FOLDER_1), List.of()); + when(resourcePermissionService.removeUserFolderPermission(FOLDER_1, USER_ID)).thenReturn(Mono.defer(() -> { + folderGaveUp.countDown(); + return Mono.error(failure); + })); + when(resourcePermissionService.removeUserApplicationPermission(APP_1, USER_ID)).thenReturn(Mono.create(sink -> { + sink.onCancel(applicationCancelled::incrementAndGet); + applicationSink.set(sink); + applicationInFlight.countDown(); + }).doOnNext(ignored -> applicationCompleted.incrementAndGet())); + + listener.onUserLeaveOrg(new OrgMemberLeftEvent(ORG_ID, USER_ID)); + await(applicationInFlight, "the application part to be in flight"); + await(folderGaveUp, "the folder part to fail on every attempt"); + + assertThat(applicationCancelled.get()).as("the failing folder part does not cancel the application part").isZero(); + assertThat(droppedFailure(failure)).as("the handler waits for the application part before it ends").isFalse(); + applicationSink.get().success(true); + await(droppedLatch, "the end of the handler after the application part finished"); + + assertThat(applicationCompleted.get()).as("the application permission removal finished").isEqualTo(1); + assertThat(applicationCancelled.get()).isZero(); + assertThat(droppedFailure(failure)).isTrue(); + say("folder part failed for good -> application part not cancelled, finished; then the handler ended with the error"); + } + + /** D-60: a persistent bundle-removal failure does not cancel the still-running application part, same shape as the group case. */ + @Test + void onUserLeaveOrg_aPersistentBundleFailureDoesNotCancelTheOtherParts() throws InterruptedException { + IllegalStateException failure = new IllegalStateException("permanent bundle failure"); + expectedFailure = failure; + CountDownLatch applicationInFlight = new CountDownLatch(1); + CountDownLatch bundleGaveUp = new CountDownLatch(1 + RETRIES); + AtomicInteger applicationCancelled = new AtomicInteger(); + AtomicInteger applicationCompleted = new AtomicInteger(); + AtomicReference> applicationSink = new AtomicReference<>(); + stubOrgContents(List.of(), List.of(APP_1), List.of(), List.of(), List.of(BUNDLE_1)); + when(resourcePermissionService.removeUserBundlePermission(BUNDLE_1, USER_ID)).thenReturn(Mono.defer(() -> { + bundleGaveUp.countDown(); + return Mono.error(failure); + })); + when(resourcePermissionService.removeUserApplicationPermission(APP_1, USER_ID)).thenReturn(Mono.create(sink -> { + sink.onCancel(applicationCancelled::incrementAndGet); + applicationSink.set(sink); + applicationInFlight.countDown(); + }).doOnNext(ignored -> applicationCompleted.incrementAndGet())); + + listener.onUserLeaveOrg(new OrgMemberLeftEvent(ORG_ID, USER_ID)); + await(applicationInFlight, "the application part to be in flight"); + await(bundleGaveUp, "the bundle part to fail on every attempt"); + + assertThat(applicationCancelled.get()).as("the failing bundle part does not cancel the application part").isZero(); + assertThat(droppedFailure(failure)).as("the handler waits for the application part before it ends").isFalse(); + applicationSink.get().success(true); + await(droppedLatch, "the end of the handler after the application part finished"); + + assertThat(applicationCompleted.get()).as("the application permission removal finished").isEqualTo(1); + assertThat(applicationCancelled.get()).isZero(); + assertThat(droppedFailure(failure)).isTrue(); + say("bundle part failed for good -> application part not cancelled, finished; then the handler ended with the error"); + } } diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/contract-registry.tsv b/server/api-service/lowcoder-server/src/test/resources/json-contract/contract-registry.tsv index 19cb5d0d74..397d0aae72 100644 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/contract-registry.tsv +++ b/server/api-service/lowcoder-server/src/test/resources/json-contract/contract-registry.tsv @@ -28,9 +28,9 @@ ApplicationEndpoints#update(String, Application, Boolean) codec WP2 org.lowcoder ApplicationEndpoints#updateEditState(String, UpdateEditStateRequest) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationEndpointsContractTest pass-through 174 return=updateEditState ApplicationEndpoints#updatePermission(String, String, UpdatePermissionRequest) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationEndpointsContractTest pass-through 231 return=updatePermissionWithUnknownRole; 233 return=updatePermission ApplicationEndpoints#updateSlug(String, String) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationEndpointsContractTest pass-through 181 return=updateSlug -ApplicationHistorySnapshotEndpoints#create(ApplicationHistorySnapshotRequest) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationHistorySnapshotEndpointsContractTest pass-through 47 return=create -ApplicationHistorySnapshotEndpoints#getHistorySnapshotDsl(String, String) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationHistorySnapshotEndpointsContractTest assembling 136 return=getHistorySnapshotDsl; 145 return=getHistorySnapshotDsl -ApplicationHistorySnapshotEndpoints#getHistorySnapshotDslArchived(String, String) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationHistorySnapshotEndpointsContractTest assembling 161 return=getHistorySnapshotDslArchived; 170 return=getHistorySnapshotDslArchived +ApplicationHistorySnapshotEndpoints#create(ApplicationHistorySnapshotRequest) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationHistorySnapshotEndpointsContractTest pass-through 49 return=create +ApplicationHistorySnapshotEndpoints#getHistorySnapshotDsl(String, String) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationHistorySnapshotEndpointsContractTest assembling 136 return=getHistorySnapshotDsl; 142 switchIfEmpty=getHistorySnapshotDslOfAnotherApplication; 148 return=getHistorySnapshotDsl +ApplicationHistorySnapshotEndpoints#getHistorySnapshotDslArchived(String, String) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationHistorySnapshotEndpointsContractTest assembling 164 return=getHistorySnapshotDslArchived; 170 switchIfEmpty=getHistorySnapshotDslArchivedOfAnotherApplication; 176 return=getHistorySnapshotDslArchived ApplicationHistorySnapshotEndpoints#listAllHistorySnapshotBriefInfo(String, int, int, String, String, Instant, Instant) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationHistorySnapshotEndpointsContractTest assembling org.lowcoder.api.application.ApplicationHistorySnapshotEndpoints$ApplicationHistorySnapshotBriefInfo 70 return=listAllHistorySnapshotBriefInfo; 90 return=listAllHistorySnapshotBriefInfo ApplicationHistorySnapshotEndpoints#listAllHistorySnapshotBriefInfoArchived(String, int, int, String, String, Instant, Instant) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationHistorySnapshotEndpointsContractTest assembling org.lowcoder.api.application.ApplicationHistorySnapshotEndpoints$ApplicationHistorySnapshotBriefInfo 107 return=listAllHistorySnapshotBriefInfoArchived; 127 return=listAllHistorySnapshotBriefInfoArchived ApplicationRecordEndpoints#delete(String) codec WP2 org.lowcoder.api.contract.endpoint.ApplicationRecordEndpointsContractTest pass-through 24 return=delete @@ -111,8 +111,8 @@ MetaEndpoints#getMetaData(GetMetaDataRequest) codec WP7 org.lowcoder.api.contrac ApiFlowEndpoints#flow(FlowRequest) decode-only WP7 org.lowcoder.api.contract.endpoint.ApiFlowEndpointsContractTest pass-through 64 return=flowSeatSyncWithAnotherMethod; 64 Mono.error=flowSeatSyncWithAnotherMethod; 68 return=flowSeatSyncWithRetriesOutOfRange; 71 return=flowSeatSync; 74 return=flowWithoutMethod; 78 return=flowWithRetriesOrTimeoutOutOfRange; 84 return=flow; 94 onErrorResume=flowUpstreamFailed; 98 return=flowFailingBeforeTheRequest; 98 Mono.error=flowFailingBeforeTheRequest §1.3: the outbound HTTPS client is built inline (ApiFlowController.java:84-93; the seat-sync path (:62-72) delegates to WorkspaceSeatSyncService) and the answer is the upstream's text, not JSON; FlowRequest is decoded at codec level, the outbound request is run against a local server through a test subclass that redirects the client, and the outbound body is pinned by api-flow JsLibraryEndpoints#getMeta(Collection) codec WP7 org.lowcoder.api.contract.endpoint.JsLibraryEndpointsContractTest pass-through 110 return=getMetaWithoutNames; 112 return=getMeta; 115 return=getMetaRecommended; 116 defaultIfEmpty=getMetaRecommendedNotLoadedYet; 118 return=getMeta; 119 onErrorReturn=getMetaFetchFailed JsLibraryEndpoints#getRecommendationMetas() codec WP7 org.lowcoder.api.contract.endpoint.JsLibraryEndpointsContractTest pass-through 104 return=getRecommendationMetas -PrivateNpmRegistryEndpoint#getNpmPackageAsset(String, String) codec WP7 org.lowcoder.api.contract.endpoint.PrivateNpmRegistryEndpointContractTest pass-through 46 return=getNpmPackageAsset -PrivateNpmRegistryEndpoint#getNpmPackageMeta(String, String) codec WP7 org.lowcoder.api.contract.endpoint.PrivateNpmRegistryEndpointContractTest pass-through 41 return=getNpmPackageMeta +PrivateNpmRegistryEndpoint#getNpmPackageAsset(String, String) codec WP7 org.lowcoder.api.contract.endpoint.PrivateNpmRegistryEndpointContractTest pass-through 49 return=getNpmPackageAsset +PrivateNpmRegistryEndpoint#getNpmPackageMeta(String, String) codec WP7 org.lowcoder.api.contract.endpoint.PrivateNpmRegistryEndpointContractTest pass-through 44 return=getNpmPackageMeta LibraryQueryEndpoints#create(LibraryQuery) codec WP6 org.lowcoder.api.contract.endpoint.LibraryQueryEndpointsContractTest pass-through 72 return=create LibraryQueryEndpoints#delete(String) codec WP6 org.lowcoder.api.contract.endpoint.LibraryQueryEndpointsContractTest pass-through 93 return=delete LibraryQueryEndpoints#dropDownList(String) codec WP6 org.lowcoder.api.contract.endpoint.LibraryQueryEndpointsContractTest pass-through 51 return=dropDownList @@ -158,24 +158,24 @@ OrganizationEndpoints#updateOrgCommonSettings(String, UpdateOrgCommonSettingsReq OrganizationEndpoints#updateRoleForMember(UpdateRoleRequest, String) codec WP4 org.lowcoder.api.contract.endpoint.OrganizationEndpointsContractTest pass-through 122 return=updateRoleForMember OrganizationEndpoints#updateSlug(String, String) codec WP4 org.lowcoder.api.contract.endpoint.OrganizationEndpointsContractTest pass-through 190 return=updateSlug OrganizationEndpoints#uploadLogo(String, Mono) codec WP4 org.lowcoder.api.contract.endpoint.OrganizationEndpointsContractTest pass-through org.springframework.http.codec.multipart.FilePart 98 return=uploadLogo -UserEndpoints#createSCIMUserAndAddToOrg(String, CreateUserRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.lowcoder.domain.user.model.User 92 return=createSCIMUserAndAddToOrg; 95 return=createSCIMUserAndAddToOrgWithInvalidEmail; 102 return=createSCIMUserAndAddToOrg; 105 return=createSCIMUserAndAddToOrg; 108 switchIfEmpty=createSCIMUserAndAddToOrgForNewUser; 119 return=createSCIMUserAndAddToOrgForNewUser -UserEndpoints#createUserAndAddToOrg(String, CreateUserRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.lowcoder.domain.user.model.User 68 return=createUserAndAddToOrg -UserEndpoints#deleteProfilePhoto() codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 237 return=deleteProfilePhoto -UserEndpoints#deleteProfilePhotoById(String, String) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 244 return=deleteProfilePhotoById -UserEndpoints#getCurrentUser(ServerWebExchange) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 316 return=getCurrentUser -UserEndpoints#getProfilePhoto(ServerWebExchange) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 251 return=getProfilePhoto; 257 return=getProfilePhoto; 258 switchIfEmpty=getProfilePhotoNotFound -UserEndpoints#getProfilePhoto(ServerWebExchange, String) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 257 return=getProfilePhotoOfUser; 258 switchIfEmpty=getProfilePhotoOfUserNotFound -UserEndpoints#getUserDetail(String) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.lowcoder.domain.user.model.UserDetail 323 return=getUserDetail -UserEndpoints#getUserOrgs(ServerWebExchange, String, Integer, Integer) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest assembling org.lowcoder.api.usermanagement.view.OrgView 142 return=getUserOrgs; 148 return=getUserOrgs; 164 return=getUserOrgs; 169 return=getUserOrgs -UserEndpoints#getUserProfile(ServerWebExchange) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.lowcoder.api.usermanagement.view.UserProfileView,org.lowcoder.api.authentication.dto.RedirectView 130 return=getUserProfileRedirect; 134 switchIfEmpty=getUserProfile -UserEndpoints#lostPassword(LostPasswordRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 287 return=lostPasswordWithoutEmail; 289 return=lostPassword -UserEndpoints#markStatus(MarkUserStatusRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 186 return=markStatusWithUnknownType; 189 return=markStatus -UserEndpoints#newUserGuidanceShown() codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 177 return=newUserGuidanceShown -UserEndpoints#resetLostPassword(ResetLostPasswordRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 297 return=resetLostPasswordWithMissingField; 300 return=resetLostPassword -UserEndpoints#resetPassword(ResetPasswordRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 274 return=resetPasswordOutsideEnterpriseMode; 277 return=resetPasswordWithoutUserId; 279 return=resetPassword -UserEndpoints#setPassword(String) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 307 return=setPasswordEmpty; 309 return=setPassword -UserEndpoints#update(String, String, UpdateUserRequest, ServerWebExchange) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 202 return=updateById -UserEndpoints#update(UpdateUserRequest, ServerWebExchange) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 196 return=update; 202 return=update -UserEndpoints#updatePassword(UpdatePasswordRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 264 return=updatePasswordWithEmptyPassword; 266 return=updatePassword -UserEndpoints#uploadProfilePhoto(Mono) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.springframework.http.codec.multipart.FilePart 222 return=uploadProfilePhoto -UserEndpoints#uploadProfilePhotoById(String, String, Mono) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.springframework.http.codec.multipart.FilePart 229 return=uploadProfilePhotoById +UserEndpoints#createSCIMUserAndAddToOrg(String, CreateUserRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.lowcoder.domain.user.model.User 93 return=createSCIMUserAndAddToOrg; 96 return=createSCIMUserAndAddToOrgWithInvalidEmail; 103 return=createSCIMUserAndAddToOrg; 106 return=createSCIMUserAndAddToOrg; 109 switchIfEmpty=createSCIMUserAndAddToOrgForNewUser; 120 return=createSCIMUserAndAddToOrgForNewUser +UserEndpoints#createUserAndAddToOrg(String, CreateUserRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.lowcoder.domain.user.model.User 69 return=createUserAndAddToOrg +UserEndpoints#deleteProfilePhoto() codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 238 return=deleteProfilePhoto +UserEndpoints#deleteProfilePhotoById(String, String) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 245 return=deleteProfilePhotoById +UserEndpoints#getCurrentUser(ServerWebExchange) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 326 return=getCurrentUser +UserEndpoints#getProfilePhoto(ServerWebExchange) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 252 return=getProfilePhoto; 258 return=getProfilePhoto; 259 switchIfEmpty=getProfilePhotoNotFound +UserEndpoints#getProfilePhoto(ServerWebExchange, String) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 258 return=getProfilePhotoOfUser; 259 switchIfEmpty=getProfilePhotoOfUserNotFound +UserEndpoints#getUserDetail(String) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.lowcoder.domain.user.model.UserDetail 333 return=getUserDetail +UserEndpoints#getUserOrgs(ServerWebExchange, String, Integer, Integer) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest assembling org.lowcoder.api.usermanagement.view.OrgView 143 return=getUserOrgs; 149 return=getUserOrgs; 165 return=getUserOrgs; 170 return=getUserOrgs +UserEndpoints#getUserProfile(ServerWebExchange) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.lowcoder.api.usermanagement.view.UserProfileView,org.lowcoder.api.authentication.dto.RedirectView 131 return=getUserProfileRedirect; 135 switchIfEmpty=getUserProfile +UserEndpoints#lostPassword(LostPasswordRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 291 return=lostPasswordWithoutEmail; 293 return=lostPassword +UserEndpoints#markStatus(MarkUserStatusRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 187 return=markStatusWithUnknownType; 190 return=markStatus +UserEndpoints#newUserGuidanceShown() codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 178 return=newUserGuidanceShown +UserEndpoints#resetLostPassword(ResetLostPasswordRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 301 return=resetLostPasswordWithMissingField; 304 return=resetLostPasswordTooWeak; 307 return=resetLostPassword +UserEndpoints#resetPassword(ResetPasswordRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 278 return=resetPasswordOutsideEnterpriseMode; 281 return=resetPasswordWithoutUserId; 283 return=resetPassword +UserEndpoints#setPassword(String) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 314 return=setPasswordEmpty; 317 return=setPasswordTooWeak; 319 return=setPassword +UserEndpoints#update(String, String, UpdateUserRequest, ServerWebExchange) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 203 return=updateById +UserEndpoints#update(UpdateUserRequest, ServerWebExchange) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 197 return=update; 203 return=update +UserEndpoints#updatePassword(UpdatePasswordRequest) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through 265 return=updatePasswordWithEmptyPassword; 268 return=updatePasswordTooWeak; 270 return=updatePassword +UserEndpoints#uploadProfilePhoto(Mono) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.springframework.http.codec.multipart.FilePart 223 return=uploadProfilePhoto +UserEndpoints#uploadProfilePhotoById(String, String, Mono) codec WP4 org.lowcoder.api.contract.endpoint.UserEndpointsContractTest pass-through org.springframework.http.codec.multipart.FilePart 230 return=uploadProfilePhotoById diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1.json index fd8322591e..c4c206a27f 100644 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1.json +++ b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1.json @@ -1 +1 @@ -{"user":{"id":"User.id","createdBy":"User.createdBy","name":"User.name","email":"User.email","uiLanguage":"User.uiLanguage","avatar":"User.avatar","tpAvatarLink":"User.tpAvatarLink","superAdmin":true,"state":"INVITED","isEnabled":false,"activeAuthId":"User.activeAuthId","passwordResetToken":"KNOWN-EXPOSURE-User.passwordResetToken","passwordResetTokenExpiry":1767225660.123456789,"isAnonymous":true,"connections":[{"authId":"User.connections[0].authId","source":"User.connections[0].source","name":"User.connections[0].name","email":"User.connections[0].email","avatar":"User.connections[0].avatar","rawUserInfo":{"sub":"User.connections[0].rawUserInfo.sub","loginCount":40070},"tokens":["User.connections[0].tokens[0]","User.connections[0].tokens[1]"]},{"authId":"User.connections[1].authId","source":"User.connections[1].source","name":"User.connections[1].name","email":"User.connections[1].email","avatar":"User.connections[1].avatar","rawUserInfo":{"sub":"User.connections[1].rawUserInfo.sub","loginCount":40071},"tokens":["User.connections[1].tokens[0]","User.connections[1].tokens[1]"]}],"apiKeysList":[{"id":"User.apiKeysList[0].id","name":"User.apiKeysList[0].name","description":"User.apiKeysList[0].description","token":"KNOWN-EXPOSURE-User.apiKeysList[0].token"},{"id":"User.apiKeysList[1].id","name":"User.apiKeysList[1].name","description":"User.apiKeysList[1].description","token":"KNOWN-EXPOSURE-User.apiKeysList[1].token"}],"apiKeys":[{"id":"User.apiKeys[0].id","token":"KNOWN-EXPOSURE-User.apiKeys[0].token"},{"id":"User.apiKeys[1].id","token":"KNOWN-EXPOSURE-User.apiKeys[1].token"}],"hasSetNickname":true,"orgTransformedUserInfo":{"User.orgTransformedUserInfo.second":{"updateTime":3000000091,"extra":{"department":"User.orgTransformedUserInfo.second.extra.department","level":40091}},"User.orgTransformedUserInfo.first":{"updateTime":3000000090,"extra":{"department":"User.orgTransformedUserInfo.first.extra.department","level":40090}}}},"organization":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","clientSecret":"SECRET-Organization.authConfigs[1].clientSecret","authorizeUrl":"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=Organization.authConfigs[1].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&access_type=offline&scope=openid email profile&prompt=select_account"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","clientSecret":"SECRET-Organization.authConfigs[2].clientSecret","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true,"authorizeUrl":"Organization.authConfigs[2].authorizationEndpoint?response_type=code&client_id=Organization.authConfigs[2].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[2].scope&access_type=offline"},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","clientSecret":"SECRET-Organization.authConfigs[3].clientSecret","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope","authorizeUrl":"Organization.authConfigs[3].baseUrl/realms/Organization.authConfigs[3].realm/protocol/openid-connect/auth?response_type=code&client_id=Organization.authConfigs[3].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","clientSecret":"SECRET-Organization.authConfigs[4].clientSecret","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope","authorizeUrl":"Organization.authConfigs[4].baseUrl/oauth2/auth?response_type=code&client_id=Organization.authConfigs[4].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[4].scope"}]},"folderInfoViews":[{"orgId":"UserHomepageView.folderInfoViews[0].orgId","folderId":"UserHomepageView.folderInfoViews[0].folderId","folderGid":"UserHomepageView.folderInfoViews[0].folderGid","parentFolderId":"UserHomepageView.folderInfoViews[0].parentFolderId","parentFolderGid":"UserHomepageView.folderInfoViews[0].parentFolderGid","name":"UserHomepageView.folderInfoViews[0].name","title":"UserHomepageView.folderInfoViews[0].title","description":"UserHomepageView.folderInfoViews[0].description","category":"UserHomepageView.folderInfoViews[0].category","type":"UserHomepageView.folderInfoViews[0].type","image":"UserHomepageView.folderInfoViews[0].image","createAt":3000000043,"createBy":"UserHomepageView.folderInfoViews[0].createBy","subFolders":null,"subApplications":null,"createTime":1767225643123,"lastViewTime":1767225644123,"visible":true,"folder":true,"manageable":false},{"orgId":"UserHomepageView.folderInfoViews[1].orgId","folderId":"UserHomepageView.folderInfoViews[1].folderId","folderGid":"UserHomepageView.folderInfoViews[1].folderGid","parentFolderId":"UserHomepageView.folderInfoViews[1].parentFolderId","parentFolderGid":"UserHomepageView.folderInfoViews[1].parentFolderGid","name":"UserHomepageView.folderInfoViews[1].name","title":"UserHomepageView.folderInfoViews[1].title","description":"UserHomepageView.folderInfoViews[1].description","category":"UserHomepageView.folderInfoViews[1].category","type":"UserHomepageView.folderInfoViews[1].type","image":"UserHomepageView.folderInfoViews[1].image","createAt":3000000044,"createBy":"UserHomepageView.folderInfoViews[1].createBy","subFolders":null,"subApplications":null,"createTime":1767225644123,"lastViewTime":1767225645123,"visible":true,"folder":true,"manageable":false}],"homeApplicationViews":[{"orgId":"UserHomepageView.homeApplicationViews[0].orgId","applicationId":"UserHomepageView.homeApplicationViews[0].applicationId","applicationGid":"UserHomepageView.homeApplicationViews[0].applicationGid","name":"UserHomepageView.homeApplicationViews[0].name","createAt":3000000410,"createBy":"UserHomepageView.homeApplicationViews[0].createBy","role":"UserHomepageView.homeApplicationViews[0].role","applicationType":40410,"applicationStatus":"RECYCLED","containerSize":{"zeta":"first key, so that sorted output would differ from input order","int":1,"negativeInt":-40003,"intMax":2147483647,"intMaxPlusOne":2147483648,"intMinMinusOne":-2147483649,"longMax":9223372036854775807,"longMaxPlusOne":9223372036854775808,"longMinMinusOne":-9223372036854775809,"decimal":1.5,"trailingZeroDecimal":1.5,"zeroPointZero":0.0,"negativeZero":0,"exponent":100.0,"exponentUpperCase":100.0,"negativeExponent":0.0025,"longDecimal":0.1,"true":true,"false":false,"null":null,"emptyObject":{},"emptyArray":[],"nested":{"array":[1,"two",[3,{"four":4.0}],null,true,3000000001],"object":{"z":1,"a":{"deeper":[[],{}]}}},"unicode":"žluťoučký kůň 🐎 中文","escapes":"é \u0000 \n \t \" \\ / 😀","key with escaped name":"escaped key","alpha":"last key"},"folderId":"UserHomepageView.homeApplicationViews[0].folderId","folderIdFrom":"UserHomepageView.homeApplicationViews[0].folderIdFrom","lastViewTime":1767226010123,"lastModifyTime":1767226011123,"lastEditedAt":1767226012123,"publicToAll":true,"publicToMarketplace":false,"agencyProfile":true,"editingUserId":"UserHomepageView.homeApplicationViews[0].editingUserId","title":"UserHomepageView.homeApplicationViews[0].title","description":"UserHomepageView.homeApplicationViews[0].description","category":"UserHomepageView.homeApplicationViews[0].category","icon":"UserHomepageView.homeApplicationViews[0].icon","published":true,"publishedVersion":"UserHomepageView.homeApplicationViews[0].publishedVersion","lastPublishedTime":1767226013.123456789,"folder":false},{"orgId":"UserHomepageView.homeApplicationViews[1].orgId","applicationId":"UserHomepageView.homeApplicationViews[1].applicationId","applicationGid":"UserHomepageView.homeApplicationViews[1].applicationGid","name":"UserHomepageView.homeApplicationViews[1].name","createAt":3000000510,"createBy":"UserHomepageView.homeApplicationViews[1].createBy","role":"UserHomepageView.homeApplicationViews[1].role","applicationType":40510,"applicationStatus":"RECYCLED","containerSize":{"zeta":"first key, so that sorted output would differ from input order","int":1,"negativeInt":-40003,"intMax":2147483647,"intMaxPlusOne":2147483648,"intMinMinusOne":-2147483649,"longMax":9223372036854775807,"longMaxPlusOne":9223372036854775808,"longMinMinusOne":-9223372036854775809,"decimal":1.5,"trailingZeroDecimal":1.5,"zeroPointZero":0.0,"negativeZero":0,"exponent":100.0,"exponentUpperCase":100.0,"negativeExponent":0.0025,"longDecimal":0.1,"true":true,"false":false,"null":null,"emptyObject":{},"emptyArray":[],"nested":{"array":[1,"two",[3,{"four":4.0}],null,true,3000000001],"object":{"z":1,"a":{"deeper":[[],{}]}}},"unicode":"žluťoučký kůň 🐎 中文","escapes":"é \u0000 \n \t \" \\ / 😀","key with escaped name":"escaped key","alpha":"last key"},"folderId":"UserHomepageView.homeApplicationViews[1].folderId","folderIdFrom":"UserHomepageView.homeApplicationViews[1].folderIdFrom","lastViewTime":1767226110123,"lastModifyTime":1767226111123,"lastEditedAt":1767226112123,"publicToAll":true,"publicToMarketplace":false,"agencyProfile":true,"editingUserId":"UserHomepageView.homeApplicationViews[1].editingUserId","title":"UserHomepageView.homeApplicationViews[1].title","description":"UserHomepageView.homeApplicationViews[1].description","category":"UserHomepageView.homeApplicationViews[1].category","icon":"UserHomepageView.homeApplicationViews[1].icon","published":true,"publishedVersion":"UserHomepageView.homeApplicationViews[1].publishedVersion","lastPublishedTime":1767226113.123456789,"folder":false}]} \ No newline at end of file +{"user":{"id":"User.id","createdBy":"User.createdBy","name":"User.name","email":"User.email","uiLanguage":"User.uiLanguage","avatar":"User.avatar","tpAvatarLink":"User.tpAvatarLink","superAdmin":true,"state":"INVITED","isEnabled":false,"activeAuthId":"User.activeAuthId","passwordResetToken":"KNOWN-EXPOSURE-User.passwordResetToken","passwordResetTokenExpiry":1767225660.123456789,"isAnonymous":true,"connections":[{"authId":"User.connections[0].authId","source":"User.connections[0].source","name":"User.connections[0].name","email":"User.connections[0].email","avatar":"User.connections[0].avatar","rawUserInfo":{"sub":"User.connections[0].rawUserInfo.sub","loginCount":40070},"tokens":["User.connections[0].tokens[0]","User.connections[0].tokens[1]"]},{"authId":"User.connections[1].authId","source":"User.connections[1].source","name":"User.connections[1].name","email":"User.connections[1].email","avatar":"User.connections[1].avatar","rawUserInfo":{"sub":"User.connections[1].rawUserInfo.sub","loginCount":40071},"tokens":["User.connections[1].tokens[0]","User.connections[1].tokens[1]"]}],"apiKeysList":[{"id":"User.apiKeysList[0].id","name":"User.apiKeysList[0].name","description":"User.apiKeysList[0].description","token":"KNOWN-EXPOSURE-User.apiKeysList[0].token"},{"id":"User.apiKeysList[1].id","name":"User.apiKeysList[1].name","description":"User.apiKeysList[1].description","token":"KNOWN-EXPOSURE-User.apiKeysList[1].token"}],"apiKeys":[{"id":"User.apiKeys[0].id","token":"KNOWN-EXPOSURE-User.apiKeys[0].token"},{"id":"User.apiKeys[1].id","token":"KNOWN-EXPOSURE-User.apiKeys[1].token"}],"hasSetNickname":true,"orgTransformedUserInfo":{"User.orgTransformedUserInfo.second":{"updateTime":3000000091,"extra":{"department":"User.orgTransformedUserInfo.second.extra.department","level":40091}},"User.orgTransformedUserInfo.first":{"updateTime":3000000090,"extra":{"department":"User.orgTransformedUserInfo.first.extra.department","level":40090}}}},"organization":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123},"folderInfoViews":[{"orgId":"UserHomepageView.folderInfoViews[0].orgId","folderId":"UserHomepageView.folderInfoViews[0].folderId","folderGid":"UserHomepageView.folderInfoViews[0].folderGid","parentFolderId":"UserHomepageView.folderInfoViews[0].parentFolderId","parentFolderGid":"UserHomepageView.folderInfoViews[0].parentFolderGid","name":"UserHomepageView.folderInfoViews[0].name","title":"UserHomepageView.folderInfoViews[0].title","description":"UserHomepageView.folderInfoViews[0].description","category":"UserHomepageView.folderInfoViews[0].category","type":"UserHomepageView.folderInfoViews[0].type","image":"UserHomepageView.folderInfoViews[0].image","createAt":3000000043,"createBy":"UserHomepageView.folderInfoViews[0].createBy","subFolders":null,"subApplications":null,"createTime":1767225643123,"lastViewTime":1767225644123,"visible":true,"folder":true,"manageable":false},{"orgId":"UserHomepageView.folderInfoViews[1].orgId","folderId":"UserHomepageView.folderInfoViews[1].folderId","folderGid":"UserHomepageView.folderInfoViews[1].folderGid","parentFolderId":"UserHomepageView.folderInfoViews[1].parentFolderId","parentFolderGid":"UserHomepageView.folderInfoViews[1].parentFolderGid","name":"UserHomepageView.folderInfoViews[1].name","title":"UserHomepageView.folderInfoViews[1].title","description":"UserHomepageView.folderInfoViews[1].description","category":"UserHomepageView.folderInfoViews[1].category","type":"UserHomepageView.folderInfoViews[1].type","image":"UserHomepageView.folderInfoViews[1].image","createAt":3000000044,"createBy":"UserHomepageView.folderInfoViews[1].createBy","subFolders":null,"subApplications":null,"createTime":1767225644123,"lastViewTime":1767225645123,"visible":true,"folder":true,"manageable":false}],"homeApplicationViews":[{"orgId":"UserHomepageView.homeApplicationViews[0].orgId","applicationId":"UserHomepageView.homeApplicationViews[0].applicationId","applicationGid":"UserHomepageView.homeApplicationViews[0].applicationGid","name":"UserHomepageView.homeApplicationViews[0].name","createAt":3000000410,"createBy":"UserHomepageView.homeApplicationViews[0].createBy","role":"UserHomepageView.homeApplicationViews[0].role","applicationType":40410,"applicationStatus":"RECYCLED","containerSize":{"zeta":"first key, so that sorted output would differ from input order","int":1,"negativeInt":-40003,"intMax":2147483647,"intMaxPlusOne":2147483648,"intMinMinusOne":-2147483649,"longMax":9223372036854775807,"longMaxPlusOne":9223372036854775808,"longMinMinusOne":-9223372036854775809,"decimal":1.5,"trailingZeroDecimal":1.5,"zeroPointZero":0.0,"negativeZero":0,"exponent":100.0,"exponentUpperCase":100.0,"negativeExponent":0.0025,"longDecimal":0.1,"true":true,"false":false,"null":null,"emptyObject":{},"emptyArray":[],"nested":{"array":[1,"two",[3,{"four":4.0}],null,true,3000000001],"object":{"z":1,"a":{"deeper":[[],{}]}}},"unicode":"žluťoučký kůň 🐎 中文","escapes":"é \u0000 \n \t \" \\ / 😀","key with escaped name":"escaped key","alpha":"last key"},"folderId":"UserHomepageView.homeApplicationViews[0].folderId","folderIdFrom":"UserHomepageView.homeApplicationViews[0].folderIdFrom","lastViewTime":1767226010123,"lastModifyTime":1767226011123,"lastEditedAt":1767226012123,"publicToAll":true,"publicToMarketplace":false,"agencyProfile":true,"editingUserId":"UserHomepageView.homeApplicationViews[0].editingUserId","title":"UserHomepageView.homeApplicationViews[0].title","description":"UserHomepageView.homeApplicationViews[0].description","category":"UserHomepageView.homeApplicationViews[0].category","icon":"UserHomepageView.homeApplicationViews[0].icon","published":true,"publishedVersion":"UserHomepageView.homeApplicationViews[0].publishedVersion","lastPublishedTime":1767226013.123456789,"folder":false},{"orgId":"UserHomepageView.homeApplicationViews[1].orgId","applicationId":"UserHomepageView.homeApplicationViews[1].applicationId","applicationGid":"UserHomepageView.homeApplicationViews[1].applicationGid","name":"UserHomepageView.homeApplicationViews[1].name","createAt":3000000510,"createBy":"UserHomepageView.homeApplicationViews[1].createBy","role":"UserHomepageView.homeApplicationViews[1].role","applicationType":40510,"applicationStatus":"RECYCLED","containerSize":{"zeta":"first key, so that sorted output would differ from input order","int":1,"negativeInt":-40003,"intMax":2147483647,"intMaxPlusOne":2147483648,"intMinMinusOne":-2147483649,"longMax":9223372036854775807,"longMaxPlusOne":9223372036854775808,"longMinMinusOne":-9223372036854775809,"decimal":1.5,"trailingZeroDecimal":1.5,"zeroPointZero":0.0,"negativeZero":0,"exponent":100.0,"exponentUpperCase":100.0,"negativeExponent":0.0025,"longDecimal":0.1,"true":true,"false":false,"null":null,"emptyObject":{},"emptyArray":[],"nested":{"array":[1,"two",[3,{"four":4.0}],null,true,3000000001],"object":{"z":1,"a":{"deeper":[[],{}]}}},"unicode":"žluťoučký kůň 🐎 中文","escapes":"é \u0000 \n \t \" \\ / 😀","key with escaped name":"escaped key","alpha":"last key"},"folderId":"UserHomepageView.homeApplicationViews[1].folderId","folderIdFrom":"UserHomepageView.homeApplicationViews[1].folderIdFrom","lastViewTime":1767226110123,"lastModifyTime":1767226111123,"lastEditedAt":1767226112123,"publicToAll":true,"publicToMarketplace":false,"agencyProfile":true,"editingUserId":"UserHomepageView.homeApplicationViews[1].editingUserId","title":"UserHomepageView.homeApplicationViews[1].title","description":"UserHomepageView.homeApplicationViews[1].description","category":"UserHomepageView.homeApplicationViews[1].category","icon":"UserHomepageView.homeApplicationViews[1].icon","published":true,"publishedVersion":"UserHomepageView.homeApplicationViews[1].publishedVersion","lastPublishedTime":1767226113.123456789,"folder":false}]} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1Internal.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1Internal.json deleted file mode 100644 index 8d87e8d965..0000000000 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1Internal.json +++ /dev/null @@ -1 +0,0 @@ -{"user":{"id":"User.id","createdBy":"User.createdBy","name":"User.name","email":"User.email","uiLanguage":"User.uiLanguage","avatar":"User.avatar","tpAvatarLink":"User.tpAvatarLink","superAdmin":true,"state":"INVITED","isEnabled":false,"activeAuthId":"User.activeAuthId","passwordResetToken":"KNOWN-EXPOSURE-User.passwordResetToken","passwordResetTokenExpiry":1767225660.123456789,"isAnonymous":true,"connections":[{"authId":"User.connections[0].authId","source":"User.connections[0].source","name":"User.connections[0].name","email":"User.connections[0].email","avatar":"User.connections[0].avatar","rawUserInfo":{"sub":"User.connections[0].rawUserInfo.sub","loginCount":40070},"tokens":["User.connections[0].tokens[0]","User.connections[0].tokens[1]"]},{"authId":"User.connections[1].authId","source":"User.connections[1].source","name":"User.connections[1].name","email":"User.connections[1].email","avatar":"User.connections[1].avatar","rawUserInfo":{"sub":"User.connections[1].rawUserInfo.sub","loginCount":40071},"tokens":["User.connections[1].tokens[0]","User.connections[1].tokens[1]"]}],"apiKeysList":[{"id":"User.apiKeysList[0].id","name":"User.apiKeysList[0].name","description":"User.apiKeysList[0].description","token":"KNOWN-EXPOSURE-User.apiKeysList[0].token"},{"id":"User.apiKeysList[1].id","name":"User.apiKeysList[1].name","description":"User.apiKeysList[1].description","token":"KNOWN-EXPOSURE-User.apiKeysList[1].token"}],"apiKeys":[{"id":"User.apiKeys[0].id","token":"KNOWN-EXPOSURE-User.apiKeys[0].token"},{"id":"User.apiKeys[1].id","token":"KNOWN-EXPOSURE-User.apiKeys[1].token"}],"hasSetNickname":true,"orgTransformedUserInfo":{"User.orgTransformedUserInfo.second":{"updateTime":3000000091,"extra":{"department":"User.orgTransformedUserInfo.second.extra.department","level":40091}},"User.orgTransformedUserInfo.first":{"updateTime":3000000090,"extra":{"department":"User.orgTransformedUserInfo.first.extra.department","level":40090}}}},"organization":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","clientSecret":"SECRET-Organization.authConfigs[1].clientSecret"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","clientSecret":"SECRET-Organization.authConfigs[2].clientSecret","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","clientSecret":"SECRET-Organization.authConfigs[3].clientSecret","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","clientSecret":"SECRET-Organization.authConfigs[4].clientSecret","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope"}]},"folderInfoViews":[{"orgId":"UserHomepageView.folderInfoViews[0].orgId","folderId":"UserHomepageView.folderInfoViews[0].folderId","folderGid":"UserHomepageView.folderInfoViews[0].folderGid","parentFolderId":"UserHomepageView.folderInfoViews[0].parentFolderId","parentFolderGid":"UserHomepageView.folderInfoViews[0].parentFolderGid","name":"UserHomepageView.folderInfoViews[0].name","title":"UserHomepageView.folderInfoViews[0].title","description":"UserHomepageView.folderInfoViews[0].description","category":"UserHomepageView.folderInfoViews[0].category","type":"UserHomepageView.folderInfoViews[0].type","image":"UserHomepageView.folderInfoViews[0].image","createAt":3000000043,"createBy":"UserHomepageView.folderInfoViews[0].createBy","subFolders":null,"subApplications":null,"createTime":1767225643123,"lastViewTime":1767225644123,"visible":true,"folder":true,"manageable":false},{"orgId":"UserHomepageView.folderInfoViews[1].orgId","folderId":"UserHomepageView.folderInfoViews[1].folderId","folderGid":"UserHomepageView.folderInfoViews[1].folderGid","parentFolderId":"UserHomepageView.folderInfoViews[1].parentFolderId","parentFolderGid":"UserHomepageView.folderInfoViews[1].parentFolderGid","name":"UserHomepageView.folderInfoViews[1].name","title":"UserHomepageView.folderInfoViews[1].title","description":"UserHomepageView.folderInfoViews[1].description","category":"UserHomepageView.folderInfoViews[1].category","type":"UserHomepageView.folderInfoViews[1].type","image":"UserHomepageView.folderInfoViews[1].image","createAt":3000000044,"createBy":"UserHomepageView.folderInfoViews[1].createBy","subFolders":null,"subApplications":null,"createTime":1767225644123,"lastViewTime":1767225645123,"visible":true,"folder":true,"manageable":false}],"homeApplicationViews":[{"orgId":"UserHomepageView.homeApplicationViews[0].orgId","applicationId":"UserHomepageView.homeApplicationViews[0].applicationId","applicationGid":"UserHomepageView.homeApplicationViews[0].applicationGid","name":"UserHomepageView.homeApplicationViews[0].name","createAt":3000000410,"createBy":"UserHomepageView.homeApplicationViews[0].createBy","role":"UserHomepageView.homeApplicationViews[0].role","applicationType":40410,"applicationStatus":"RECYCLED","containerSize":{"zeta":"first key, so that sorted output would differ from input order","int":1,"negativeInt":-40003,"intMax":2147483647,"intMaxPlusOne":2147483648,"intMinMinusOne":-2147483649,"longMax":9223372036854775807,"longMaxPlusOne":9223372036854775808,"longMinMinusOne":-9223372036854775809,"decimal":1.5,"trailingZeroDecimal":1.5,"zeroPointZero":0.0,"negativeZero":0,"exponent":100.0,"exponentUpperCase":100.0,"negativeExponent":0.0025,"longDecimal":0.1,"true":true,"false":false,"null":null,"emptyObject":{},"emptyArray":[],"nested":{"array":[1,"two",[3,{"four":4.0}],null,true,3000000001],"object":{"z":1,"a":{"deeper":[[],{}]}}},"unicode":"žluťoučký kůň 🐎 中文","escapes":"é \u0000 \n \t \" \\ / 😀","key with escaped name":"escaped key","alpha":"last key"},"folderId":"UserHomepageView.homeApplicationViews[0].folderId","folderIdFrom":"UserHomepageView.homeApplicationViews[0].folderIdFrom","lastViewTime":1767226010123,"lastModifyTime":1767226011123,"lastEditedAt":1767226012123,"publicToAll":true,"publicToMarketplace":false,"agencyProfile":true,"editingUserId":"UserHomepageView.homeApplicationViews[0].editingUserId","title":"UserHomepageView.homeApplicationViews[0].title","description":"UserHomepageView.homeApplicationViews[0].description","category":"UserHomepageView.homeApplicationViews[0].category","icon":"UserHomepageView.homeApplicationViews[0].icon","published":true,"publishedVersion":"UserHomepageView.homeApplicationViews[0].publishedVersion","lastPublishedTime":1767226013.123456789,"folder":false},{"orgId":"UserHomepageView.homeApplicationViews[1].orgId","applicationId":"UserHomepageView.homeApplicationViews[1].applicationId","applicationGid":"UserHomepageView.homeApplicationViews[1].applicationGid","name":"UserHomepageView.homeApplicationViews[1].name","createAt":3000000510,"createBy":"UserHomepageView.homeApplicationViews[1].createBy","role":"UserHomepageView.homeApplicationViews[1].role","applicationType":40510,"applicationStatus":"RECYCLED","containerSize":{"zeta":"first key, so that sorted output would differ from input order","int":1,"negativeInt":-40003,"intMax":2147483647,"intMaxPlusOne":2147483648,"intMinMinusOne":-2147483649,"longMax":9223372036854775807,"longMaxPlusOne":9223372036854775808,"longMinMinusOne":-9223372036854775809,"decimal":1.5,"trailingZeroDecimal":1.5,"zeroPointZero":0.0,"negativeZero":0,"exponent":100.0,"exponentUpperCase":100.0,"negativeExponent":0.0025,"longDecimal":0.1,"true":true,"false":false,"null":null,"emptyObject":{},"emptyArray":[],"nested":{"array":[1,"two",[3,{"four":4.0}],null,true,3000000001],"object":{"z":1,"a":{"deeper":[[],{}]}}},"unicode":"žluťoučký kůň 🐎 中文","escapes":"é \u0000 \n \t \" \\ / 😀","key with escaped name":"escaped key","alpha":"last key"},"folderId":"UserHomepageView.homeApplicationViews[1].folderId","folderIdFrom":"UserHomepageView.homeApplicationViews[1].folderIdFrom","lastViewTime":1767226110123,"lastModifyTime":1767226111123,"lastEditedAt":1767226112123,"publicToAll":true,"publicToMarketplace":false,"agencyProfile":true,"editingUserId":"UserHomepageView.homeApplicationViews[1].editingUserId","title":"UserHomepageView.homeApplicationViews[1].title","description":"UserHomepageView.homeApplicationViews[1].description","category":"UserHomepageView.homeApplicationViews[1].category","icon":"UserHomepageView.homeApplicationViews[1].icon","published":true,"publishedVersion":"UserHomepageView.homeApplicationViews[1].publishedVersion","lastPublishedTime":1767226113.123456789,"folder":false}]} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1Public.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1Public.json deleted file mode 100644 index 58ffbd4c12..0000000000 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.home.UserHomepageView.S1Public.json +++ /dev/null @@ -1 +0,0 @@ -{"user":{"id":"User.id","createdBy":"User.createdBy","name":"User.name","email":"User.email","uiLanguage":"User.uiLanguage","avatar":"User.avatar","tpAvatarLink":"User.tpAvatarLink","superAdmin":true,"state":"INVITED","isEnabled":false,"activeAuthId":"User.activeAuthId","passwordResetToken":"KNOWN-EXPOSURE-User.passwordResetToken","passwordResetTokenExpiry":1767225660.123456789,"isAnonymous":true,"connections":[{"authId":"User.connections[0].authId","source":"User.connections[0].source","name":"User.connections[0].name","email":"User.connections[0].email","avatar":"User.connections[0].avatar","rawUserInfo":{"sub":"User.connections[0].rawUserInfo.sub","loginCount":40070},"tokens":["User.connections[0].tokens[0]","User.connections[0].tokens[1]"]},{"authId":"User.connections[1].authId","source":"User.connections[1].source","name":"User.connections[1].name","email":"User.connections[1].email","avatar":"User.connections[1].avatar","rawUserInfo":{"sub":"User.connections[1].rawUserInfo.sub","loginCount":40071},"tokens":["User.connections[1].tokens[0]","User.connections[1].tokens[1]"]}],"apiKeysList":[{"id":"User.apiKeysList[0].id","name":"User.apiKeysList[0].name","description":"User.apiKeysList[0].description","token":"KNOWN-EXPOSURE-User.apiKeysList[0].token"},{"id":"User.apiKeysList[1].id","name":"User.apiKeysList[1].name","description":"User.apiKeysList[1].description","token":"KNOWN-EXPOSURE-User.apiKeysList[1].token"}],"apiKeys":[{"id":"User.apiKeys[0].id","token":"KNOWN-EXPOSURE-User.apiKeys[0].token"},{"id":"User.apiKeys[1].id","token":"KNOWN-EXPOSURE-User.apiKeys[1].token"}],"hasSetNickname":true,"orgTransformedUserInfo":{"User.orgTransformedUserInfo.second":{"updateTime":3000000091,"extra":{"department":"User.orgTransformedUserInfo.second.extra.department","level":40091}},"User.orgTransformedUserInfo.first":{"updateTime":3000000090,"extra":{"department":"User.orgTransformedUserInfo.first.extra.department","level":40090}}}},"organization":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","authorizeUrl":"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=Organization.authConfigs[1].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&access_type=offline&scope=openid email profile&prompt=select_account"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true,"authorizeUrl":"Organization.authConfigs[2].authorizationEndpoint?response_type=code&client_id=Organization.authConfigs[2].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[2].scope&access_type=offline"},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope","authorizeUrl":"Organization.authConfigs[3].baseUrl/realms/Organization.authConfigs[3].realm/protocol/openid-connect/auth?response_type=code&client_id=Organization.authConfigs[3].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope","authorizeUrl":"Organization.authConfigs[4].baseUrl/oauth2/auth?response_type=code&client_id=Organization.authConfigs[4].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[4].scope"}]},"folderInfoViews":[{"orgId":"UserHomepageView.folderInfoViews[0].orgId","folderId":"UserHomepageView.folderInfoViews[0].folderId","folderGid":"UserHomepageView.folderInfoViews[0].folderGid","parentFolderId":"UserHomepageView.folderInfoViews[0].parentFolderId","parentFolderGid":"UserHomepageView.folderInfoViews[0].parentFolderGid","name":"UserHomepageView.folderInfoViews[0].name","title":"UserHomepageView.folderInfoViews[0].title","description":"UserHomepageView.folderInfoViews[0].description","category":"UserHomepageView.folderInfoViews[0].category","type":"UserHomepageView.folderInfoViews[0].type","image":"UserHomepageView.folderInfoViews[0].image","createAt":3000000043,"createBy":"UserHomepageView.folderInfoViews[0].createBy","subFolders":null,"subApplications":null,"createTime":1767225643123,"lastViewTime":1767225644123,"visible":true,"folder":true,"manageable":false},{"orgId":"UserHomepageView.folderInfoViews[1].orgId","folderId":"UserHomepageView.folderInfoViews[1].folderId","folderGid":"UserHomepageView.folderInfoViews[1].folderGid","parentFolderId":"UserHomepageView.folderInfoViews[1].parentFolderId","parentFolderGid":"UserHomepageView.folderInfoViews[1].parentFolderGid","name":"UserHomepageView.folderInfoViews[1].name","title":"UserHomepageView.folderInfoViews[1].title","description":"UserHomepageView.folderInfoViews[1].description","category":"UserHomepageView.folderInfoViews[1].category","type":"UserHomepageView.folderInfoViews[1].type","image":"UserHomepageView.folderInfoViews[1].image","createAt":3000000044,"createBy":"UserHomepageView.folderInfoViews[1].createBy","subFolders":null,"subApplications":null,"createTime":1767225644123,"lastViewTime":1767225645123,"visible":true,"folder":true,"manageable":false}],"homeApplicationViews":[{"orgId":"UserHomepageView.homeApplicationViews[0].orgId","applicationId":"UserHomepageView.homeApplicationViews[0].applicationId","applicationGid":"UserHomepageView.homeApplicationViews[0].applicationGid","name":"UserHomepageView.homeApplicationViews[0].name","createAt":3000000410,"createBy":"UserHomepageView.homeApplicationViews[0].createBy","role":"UserHomepageView.homeApplicationViews[0].role","applicationType":40410,"applicationStatus":"RECYCLED","containerSize":{"zeta":"first key, so that sorted output would differ from input order","int":1,"negativeInt":-40003,"intMax":2147483647,"intMaxPlusOne":2147483648,"intMinMinusOne":-2147483649,"longMax":9223372036854775807,"longMaxPlusOne":9223372036854775808,"longMinMinusOne":-9223372036854775809,"decimal":1.5,"trailingZeroDecimal":1.5,"zeroPointZero":0.0,"negativeZero":0,"exponent":100.0,"exponentUpperCase":100.0,"negativeExponent":0.0025,"longDecimal":0.1,"true":true,"false":false,"null":null,"emptyObject":{},"emptyArray":[],"nested":{"array":[1,"two",[3,{"four":4.0}],null,true,3000000001],"object":{"z":1,"a":{"deeper":[[],{}]}}},"unicode":"žluťoučký kůň 🐎 中文","escapes":"é \u0000 \n \t \" \\ / 😀","key with escaped name":"escaped key","alpha":"last key"},"folderId":"UserHomepageView.homeApplicationViews[0].folderId","folderIdFrom":"UserHomepageView.homeApplicationViews[0].folderIdFrom","lastViewTime":1767226010123,"lastModifyTime":1767226011123,"lastEditedAt":1767226012123,"publicToAll":true,"publicToMarketplace":false,"agencyProfile":true,"editingUserId":"UserHomepageView.homeApplicationViews[0].editingUserId","title":"UserHomepageView.homeApplicationViews[0].title","description":"UserHomepageView.homeApplicationViews[0].description","category":"UserHomepageView.homeApplicationViews[0].category","icon":"UserHomepageView.homeApplicationViews[0].icon","published":true,"publishedVersion":"UserHomepageView.homeApplicationViews[0].publishedVersion","lastPublishedTime":1767226013.123456789,"folder":false},{"orgId":"UserHomepageView.homeApplicationViews[1].orgId","applicationId":"UserHomepageView.homeApplicationViews[1].applicationId","applicationGid":"UserHomepageView.homeApplicationViews[1].applicationGid","name":"UserHomepageView.homeApplicationViews[1].name","createAt":3000000510,"createBy":"UserHomepageView.homeApplicationViews[1].createBy","role":"UserHomepageView.homeApplicationViews[1].role","applicationType":40510,"applicationStatus":"RECYCLED","containerSize":{"zeta":"first key, so that sorted output would differ from input order","int":1,"negativeInt":-40003,"intMax":2147483647,"intMaxPlusOne":2147483648,"intMinMinusOne":-2147483649,"longMax":9223372036854775807,"longMaxPlusOne":9223372036854775808,"longMinMinusOne":-9223372036854775809,"decimal":1.5,"trailingZeroDecimal":1.5,"zeroPointZero":0.0,"negativeZero":0,"exponent":100.0,"exponentUpperCase":100.0,"negativeExponent":0.0025,"longDecimal":0.1,"true":true,"false":false,"null":null,"emptyObject":{},"emptyArray":[],"nested":{"array":[1,"two",[3,{"four":4.0}],null,true,3000000001],"object":{"z":1,"a":{"deeper":[[],{}]}}},"unicode":"žluťoučký kůň 🐎 中文","escapes":"é \u0000 \n \t \" \\ / 😀","key with escaped name":"escaped key","alpha":"last key"},"folderId":"UserHomepageView.homeApplicationViews[1].folderId","folderIdFrom":"UserHomepageView.homeApplicationViews[1].folderIdFrom","lastViewTime":1767226110123,"lastModifyTime":1767226111123,"lastEditedAt":1767226112123,"publicToAll":true,"publicToMarketplace":false,"agencyProfile":true,"editingUserId":"UserHomepageView.homeApplicationViews[1].editingUserId","title":"UserHomepageView.homeApplicationViews[1].title","description":"UserHomepageView.homeApplicationViews[1].description","category":"UserHomepageView.homeApplicationViews[1].category","icon":"UserHomepageView.homeApplicationViews[1].icon","published":true,"publishedVersion":"UserHomepageView.homeApplicationViews[1].publishedVersion","lastPublishedTime":1767226113.123456789,"folder":false}]} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.UserEndpoints$ResetLostPasswordRequest.D1.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.UserEndpoints$ResetLostPasswordRequest.D1.json index e5aab79028..1635e6c7ec 100644 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.UserEndpoints$ResetLostPasswordRequest.D1.json +++ b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.UserEndpoints$ResetLostPasswordRequest.D1.json @@ -1,5 +1,5 @@ { "token" : "ResetLostPasswordRequest.token", "userEmail" : "ResetLostPasswordRequest.userEmail", - "newPassword" : "ResetLostPasswordRequest.newPassword" + "newPassword" : "ResetLostPasswordRequest.newPassword1" } diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.UserEndpoints$UpdatePasswordRequest.D1.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.UserEndpoints$UpdatePasswordRequest.D1.json index 99c3e1b34b..e40a0f0446 100644 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.UserEndpoints$UpdatePasswordRequest.D1.json +++ b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.UserEndpoints$UpdatePasswordRequest.D1.json @@ -1,4 +1,4 @@ { "oldPassword" : "UpdatePasswordRequest.oldPassword", - "newPassword" : "UpdatePasswordRequest.newPassword" + "newPassword" : "UpdatePasswordRequest.newPassword1" } diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1.json index b34926902c..1dd24e2149 100644 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1.json +++ b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1.json @@ -1 +1 @@ -{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","clientSecret":"SECRET-Organization.authConfigs[1].clientSecret","authorizeUrl":"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=Organization.authConfigs[1].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&access_type=offline&scope=openid email profile&prompt=select_account"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","clientSecret":"SECRET-Organization.authConfigs[2].clientSecret","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true,"authorizeUrl":"Organization.authConfigs[2].authorizationEndpoint?response_type=code&client_id=Organization.authConfigs[2].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[2].scope&access_type=offline"},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","clientSecret":"SECRET-Organization.authConfigs[3].clientSecret","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope","authorizeUrl":"Organization.authConfigs[3].baseUrl/realms/Organization.authConfigs[3].realm/protocol/openid-connect/auth?response_type=code&client_id=Organization.authConfigs[3].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","clientSecret":"SECRET-Organization.authConfigs[4].clientSecret","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope","authorizeUrl":"Organization.authConfigs[4].baseUrl/oauth2/auth?response_type=code&client_id=Organization.authConfigs[4].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[4].scope"}]},"role":"OrgAndVisitorRoleView.role"} \ No newline at end of file +{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123},"role":"OrgAndVisitorRoleView.role"} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1Internal.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1Internal.json deleted file mode 100644 index acd7c7ddf3..0000000000 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1Internal.json +++ /dev/null @@ -1 +0,0 @@ -{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","clientSecret":"SECRET-Organization.authConfigs[1].clientSecret"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","clientSecret":"SECRET-Organization.authConfigs[2].clientSecret","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","clientSecret":"SECRET-Organization.authConfigs[3].clientSecret","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","clientSecret":"SECRET-Organization.authConfigs[4].clientSecret","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope"}]},"role":"OrgAndVisitorRoleView.role"} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1Public.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1Public.json deleted file mode 100644 index 3d56783273..0000000000 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.OrgAndVisitorRoleView.S1Public.json +++ /dev/null @@ -1 +0,0 @@ -{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","authorizeUrl":"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=Organization.authConfigs[1].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&access_type=offline&scope=openid email profile&prompt=select_account"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true,"authorizeUrl":"Organization.authConfigs[2].authorizationEndpoint?response_type=code&client_id=Organization.authConfigs[2].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[2].scope&access_type=offline"},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope","authorizeUrl":"Organization.authConfigs[3].baseUrl/realms/Organization.authConfigs[3].realm/protocol/openid-connect/auth?response_type=code&client_id=Organization.authConfigs[3].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope","authorizeUrl":"Organization.authConfigs[4].baseUrl/oauth2/auth?response_type=code&client_id=Organization.authConfigs[4].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[4].scope"}]},"role":"OrgAndVisitorRoleView.role"} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1.json index b4ae3b444d..62139a06c5 100644 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1.json +++ b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1.json @@ -1 +1 @@ -{"id":"UserProfileView.id","orgAndRoles":[{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","clientSecret":"SECRET-Organization.authConfigs[1].clientSecret","authorizeUrl":"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=Organization.authConfigs[1].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&access_type=offline&scope=openid email profile&prompt=select_account"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","clientSecret":"SECRET-Organization.authConfigs[2].clientSecret","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true,"authorizeUrl":"Organization.authConfigs[2].authorizationEndpoint?response_type=code&client_id=Organization.authConfigs[2].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[2].scope&access_type=offline"},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","clientSecret":"SECRET-Organization.authConfigs[3].clientSecret","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope","authorizeUrl":"Organization.authConfigs[3].baseUrl/realms/Organization.authConfigs[3].realm/protocol/openid-connect/auth?response_type=code&client_id=Organization.authConfigs[3].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","clientSecret":"SECRET-Organization.authConfigs[4].clientSecret","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope","authorizeUrl":"Organization.authConfigs[4].baseUrl/oauth2/auth?response_type=code&client_id=Organization.authConfigs[4].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[4].scope"}]},"role":"UserProfileView.orgAndRoles[0].role"},{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","clientSecret":"SECRET-Organization.authConfigs[1].clientSecret","authorizeUrl":"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=Organization.authConfigs[1].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&access_type=offline&scope=openid email profile&prompt=select_account"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","clientSecret":"SECRET-Organization.authConfigs[2].clientSecret","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true,"authorizeUrl":"Organization.authConfigs[2].authorizationEndpoint?response_type=code&client_id=Organization.authConfigs[2].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[2].scope&access_type=offline"},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","clientSecret":"SECRET-Organization.authConfigs[3].clientSecret","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope","authorizeUrl":"Organization.authConfigs[3].baseUrl/realms/Organization.authConfigs[3].realm/protocol/openid-connect/auth?response_type=code&client_id=Organization.authConfigs[3].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","clientSecret":"SECRET-Organization.authConfigs[4].clientSecret","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope","authorizeUrl":"Organization.authConfigs[4].baseUrl/oauth2/auth?response_type=code&client_id=Organization.authConfigs[4].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[4].scope"}]},"role":"UserProfileView.orgAndRoles[1].role"}],"currentOrgId":"UserProfileView.currentOrgId","username":"UserProfileView.username","connections":[{"authId":"UserProfileView.connections[0].authId","source":"UserProfileView.connections[0].source","name":"UserProfileView.connections[0].name","email":"UserProfileView.connections[0].email","avatar":"UserProfileView.connections[0].avatar","rawUserInfo":{"sub":"UserProfileView.connections[0].rawUserInfo.sub","loginCount":40080},"tokens":["UserProfileView.connections[0].tokens[1]","UserProfileView.connections[0].tokens[0]"]},{"authId":"UserProfileView.connections[1].authId","source":"UserProfileView.connections[1].source","name":"UserProfileView.connections[1].name","email":"UserProfileView.connections[1].email","avatar":"UserProfileView.connections[1].avatar","rawUserInfo":{"sub":"UserProfileView.connections[1].rawUserInfo.sub","loginCount":40081},"tokens":["UserProfileView.connections[1].tokens[0]","UserProfileView.connections[1].tokens[1]"]}],"uiLanguage":"UserProfileView.uiLanguage","avatar":"UserProfileView.avatar","avatarUrl":"UserProfileView.avatarUrl","hasPassword":true,"hasSetNickname":false,"hasShownNewUserGuidance":true,"userStatus":{"newUserGuidance":true,"olderUserNonDevPopup":40130},"createdTimeMs":3000000130,"ip":"UserProfileView.ip","enabled":false,"anonymous":true,"orgDev":false,"isAnonymous":true,"isEnabled":false} \ No newline at end of file +{"id":"UserProfileView.id","orgAndRoles":[{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123},"role":"UserProfileView.orgAndRoles[0].role"},{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123},"role":"UserProfileView.orgAndRoles[1].role"}],"currentOrgId":"UserProfileView.currentOrgId","username":"UserProfileView.username","connections":[{"authId":"UserProfileView.connections[0].authId","source":"UserProfileView.connections[0].source","name":"UserProfileView.connections[0].name","email":"UserProfileView.connections[0].email","avatar":"UserProfileView.connections[0].avatar","rawUserInfo":{"sub":"UserProfileView.connections[0].rawUserInfo.sub","loginCount":40080},"tokens":["UserProfileView.connections[0].tokens[1]","UserProfileView.connections[0].tokens[0]"]},{"authId":"UserProfileView.connections[1].authId","source":"UserProfileView.connections[1].source","name":"UserProfileView.connections[1].name","email":"UserProfileView.connections[1].email","avatar":"UserProfileView.connections[1].avatar","rawUserInfo":{"sub":"UserProfileView.connections[1].rawUserInfo.sub","loginCount":40081},"tokens":["UserProfileView.connections[1].tokens[0]","UserProfileView.connections[1].tokens[1]"]}],"uiLanguage":"UserProfileView.uiLanguage","avatar":"UserProfileView.avatar","avatarUrl":"UserProfileView.avatarUrl","hasPassword":true,"hasSetNickname":false,"hasShownNewUserGuidance":true,"userStatus":{"newUserGuidance":true,"olderUserNonDevPopup":40130},"createdTimeMs":3000000130,"ip":"UserProfileView.ip","enabled":false,"anonymous":true,"orgDev":false,"isAnonymous":true,"isEnabled":false} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1Internal.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1Internal.json deleted file mode 100644 index 300e762a58..0000000000 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1Internal.json +++ /dev/null @@ -1 +0,0 @@ -{"id":"UserProfileView.id","orgAndRoles":[{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","clientSecret":"SECRET-Organization.authConfigs[1].clientSecret"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","clientSecret":"SECRET-Organization.authConfigs[2].clientSecret","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","clientSecret":"SECRET-Organization.authConfigs[3].clientSecret","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","clientSecret":"SECRET-Organization.authConfigs[4].clientSecret","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope"}]},"role":"UserProfileView.orgAndRoles[0].role"},{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","clientSecret":"SECRET-Organization.authConfigs[1].clientSecret"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","clientSecret":"SECRET-Organization.authConfigs[2].clientSecret","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","clientSecret":"SECRET-Organization.authConfigs[3].clientSecret","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","clientSecret":"SECRET-Organization.authConfigs[4].clientSecret","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope"}]},"role":"UserProfileView.orgAndRoles[1].role"}],"currentOrgId":"UserProfileView.currentOrgId","username":"UserProfileView.username","connections":[{"authId":"UserProfileView.connections[0].authId","source":"UserProfileView.connections[0].source","name":"UserProfileView.connections[0].name","email":"UserProfileView.connections[0].email","avatar":"UserProfileView.connections[0].avatar","rawUserInfo":{"sub":"UserProfileView.connections[0].rawUserInfo.sub","loginCount":40080},"tokens":["UserProfileView.connections[0].tokens[1]","UserProfileView.connections[0].tokens[0]"]},{"authId":"UserProfileView.connections[1].authId","source":"UserProfileView.connections[1].source","name":"UserProfileView.connections[1].name","email":"UserProfileView.connections[1].email","avatar":"UserProfileView.connections[1].avatar","rawUserInfo":{"sub":"UserProfileView.connections[1].rawUserInfo.sub","loginCount":40081},"tokens":["UserProfileView.connections[1].tokens[0]","UserProfileView.connections[1].tokens[1]"]}],"uiLanguage":"UserProfileView.uiLanguage","avatar":"UserProfileView.avatar","avatarUrl":"UserProfileView.avatarUrl","hasPassword":true,"hasSetNickname":false,"hasShownNewUserGuidance":true,"userStatus":{"newUserGuidance":true,"olderUserNonDevPopup":40130},"createdTimeMs":3000000130,"ip":"UserProfileView.ip","enabled":false,"anonymous":true,"orgDev":false,"isAnonymous":true,"isEnabled":false} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1Public.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1Public.json deleted file mode 100644 index 50cc5e211f..0000000000 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.api.usermanagement.view.UserProfileView.S1Public.json +++ /dev/null @@ -1 +0,0 @@ -{"id":"UserProfileView.id","orgAndRoles":[{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","authorizeUrl":"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=Organization.authConfigs[1].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&access_type=offline&scope=openid email profile&prompt=select_account"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true,"authorizeUrl":"Organization.authConfigs[2].authorizationEndpoint?response_type=code&client_id=Organization.authConfigs[2].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[2].scope&access_type=offline"},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope","authorizeUrl":"Organization.authConfigs[3].baseUrl/realms/Organization.authConfigs[3].realm/protocol/openid-connect/auth?response_type=code&client_id=Organization.authConfigs[3].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope","authorizeUrl":"Organization.authConfigs[4].baseUrl/oauth2/auth?response_type=code&client_id=Organization.authConfigs[4].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[4].scope"}]},"role":"UserProfileView.orgAndRoles[0].role"},{"org":{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","authorizeUrl":"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=Organization.authConfigs[1].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&access_type=offline&scope=openid email profile&prompt=select_account"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true,"authorizeUrl":"Organization.authConfigs[2].authorizationEndpoint?response_type=code&client_id=Organization.authConfigs[2].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[2].scope&access_type=offline"},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope","authorizeUrl":"Organization.authConfigs[3].baseUrl/realms/Organization.authConfigs[3].realm/protocol/openid-connect/auth?response_type=code&client_id=Organization.authConfigs[3].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope","authorizeUrl":"Organization.authConfigs[4].baseUrl/oauth2/auth?response_type=code&client_id=Organization.authConfigs[4].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[4].scope"}]},"role":"UserProfileView.orgAndRoles[1].role"}],"currentOrgId":"UserProfileView.currentOrgId","username":"UserProfileView.username","connections":[{"authId":"UserProfileView.connections[0].authId","source":"UserProfileView.connections[0].source","name":"UserProfileView.connections[0].name","email":"UserProfileView.connections[0].email","avatar":"UserProfileView.connections[0].avatar","rawUserInfo":{"sub":"UserProfileView.connections[0].rawUserInfo.sub","loginCount":40080},"tokens":["UserProfileView.connections[0].tokens[1]","UserProfileView.connections[0].tokens[0]"]},{"authId":"UserProfileView.connections[1].authId","source":"UserProfileView.connections[1].source","name":"UserProfileView.connections[1].name","email":"UserProfileView.connections[1].email","avatar":"UserProfileView.connections[1].avatar","rawUserInfo":{"sub":"UserProfileView.connections[1].rawUserInfo.sub","loginCount":40081},"tokens":["UserProfileView.connections[1].tokens[0]","UserProfileView.connections[1].tokens[1]"]}],"uiLanguage":"UserProfileView.uiLanguage","avatar":"UserProfileView.avatar","avatarUrl":"UserProfileView.avatarUrl","hasPassword":true,"hasSetNickname":false,"hasShownNewUserGuidance":true,"userStatus":{"newUserGuidance":true,"olderUserNonDevPopup":40130},"createdTimeMs":3000000130,"ip":"UserProfileView.ip","enabled":false,"anonymous":true,"orgDev":false,"isAnonymous":true,"isEnabled":false} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1.json index 963da4f602..22e1bb9af9 100644 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1.json +++ b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1.json @@ -1 +1 @@ -{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","clientSecret":"SECRET-Organization.authConfigs[1].clientSecret","authorizeUrl":"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=Organization.authConfigs[1].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&access_type=offline&scope=openid email profile&prompt=select_account"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","clientSecret":"SECRET-Organization.authConfigs[2].clientSecret","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true,"authorizeUrl":"Organization.authConfigs[2].authorizationEndpoint?response_type=code&client_id=Organization.authConfigs[2].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[2].scope&access_type=offline"},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","clientSecret":"SECRET-Organization.authConfigs[3].clientSecret","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope","authorizeUrl":"Organization.authConfigs[3].baseUrl/realms/Organization.authConfigs[3].realm/protocol/openid-connect/auth?response_type=code&client_id=Organization.authConfigs[3].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","clientSecret":"SECRET-Organization.authConfigs[4].clientSecret","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope","authorizeUrl":"Organization.authConfigs[4].baseUrl/oauth2/auth?response_type=code&client_id=Organization.authConfigs[4].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[4].scope"}]} \ No newline at end of file +{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1Internal.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1Internal.json deleted file mode 100644 index c02f5954dd..0000000000 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1Internal.json +++ /dev/null @@ -1 +0,0 @@ -{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","clientSecret":"SECRET-Organization.authConfigs[1].clientSecret"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","clientSecret":"SECRET-Organization.authConfigs[2].clientSecret","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","clientSecret":"SECRET-Organization.authConfigs[3].clientSecret","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","clientSecret":"SECRET-Organization.authConfigs[4].clientSecret","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope"}]} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1Public.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1Public.json deleted file mode 100644 index 6dfdbd41a1..0000000000 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S1Public.json +++ /dev/null @@ -1 +0,0 @@ -{"id":"Organization.id","createdBy":"Organization.createdBy","gid":"Organization.gid","slug":"Organization.slug","name":"Organization.name","isAutoGeneratedOrganization":true,"contactName":"Organization.contactName","contactEmail":"Organization.contactEmail","contactPhoneNumber":"Organization.contactPhoneNumber","isEmailDisabled":true,"source":"Organization.source","thirdPartyCompanyId":"Organization.thirdPartyCompanyId","state":"DELETED","commonSettings":{"maxRows":40100,"themeId":"Organization.commonSettings.themeId"},"logoUrl":"/api/assets/Organization.logoAssetId","createTime":1767225700123,"authConfigs":[{"authType":"FORM","id":"Organization.authConfigs[0].id","enable":true,"enableRegister":false,"source":"Organization.authConfigs[0].source","sourceName":"Organization.authConfigs[0].sourceName","authType":"FORM"},{"authType":"GITHUB","id":"Organization.authConfigs[1].id","source":"Organization.authConfigs[1].source","sourceName":"Organization.authConfigs[1].sourceName","enable":true,"enableRegister":false,"authType":"GOOGLE","clientId":"Organization.authConfigs[1].clientId","authorizeUrl":"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=Organization.authConfigs[1].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&access_type=offline&scope=openid email profile&prompt=select_account"},{"authType":"GENERIC","id":"Organization.authConfigs[2].id","source":"Organization.authConfigs[2].source","sourceName":"Organization.authConfigs[2].sourceName","enable":true,"enableRegister":false,"authType":"GENERIC","clientId":"Organization.authConfigs[2].clientId","sourceDescription":"Organization.authConfigs[2].sourceDescription","sourceIcon":"Organization.authConfigs[2].sourceIcon","sourceCategory":"Organization.authConfigs[2].sourceCategory","issuerUri":"Organization.authConfigs[2].issuerUri","authorizationEndpoint":"Organization.authConfigs[2].authorizationEndpoint","tokenEndpoint":"Organization.authConfigs[2].tokenEndpoint","userInfoEndpoint":"Organization.authConfigs[2].userInfoEndpoint","scope":"Organization.authConfigs[2].scope","sourceMappings":{"uid":"Organization.authConfigs[2].sourceMappings.uid","email":"Organization.authConfigs[2].sourceMappings.email"},"userInfoIntrospection":true,"userCanSelectAccounts":false,"postForUserEndpoint":true,"authorizeUrl":"Organization.authConfigs[2].authorizationEndpoint?response_type=code&client_id=Organization.authConfigs[2].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[2].scope&access_type=offline"},{"authType":"KEYCLOAK","id":"Organization.authConfigs[3].id","source":"Organization.authConfigs[3].source","sourceName":"Organization.authConfigs[3].sourceName","enable":true,"enableRegister":false,"authType":"KEYCLOAK","clientId":"Organization.authConfigs[3].clientId","baseUrl":"Organization.authConfigs[3].baseUrl","realm":"Organization.authConfigs[3].realm","scope":"Organization.authConfigs[3].scope","authorizeUrl":"Organization.authConfigs[3].baseUrl/realms/Organization.authConfigs[3].realm/protocol/openid-connect/auth?response_type=code&client_id=Organization.authConfigs[3].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[3].scope"},{"authType":"ORY","id":"Organization.authConfigs[4].id","source":"Organization.authConfigs[4].source","sourceName":"Organization.authConfigs[4].sourceName","enable":true,"enableRegister":false,"authType":"ORY","clientId":"Organization.authConfigs[4].clientId","baseUrl":"Organization.authConfigs[4].baseUrl","scope":"Organization.authConfigs[4].scope","authorizeUrl":"Organization.authConfigs[4].baseUrl/oauth2/auth?response_type=code&client_id=Organization.authConfigs[4].clientId&redirect_uri=$REDIRECT_URL&state=$STATE&scope=Organization.authConfigs[4].scope"}]} \ No newline at end of file diff --git a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S2.json b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S2.json index dd8b35a5d9..16ae6a752d 100644 --- a/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S2.json +++ b/server/api-service/lowcoder-server/src/test/resources/json-contract/types/org.lowcoder.domain.organization.model.Organization.S2.json @@ -1 +1 @@ -{"id":null,"createdBy":null,"gid":null,"slug":null,"name":null,"isAutoGeneratedOrganization":null,"contactName":null,"contactEmail":null,"contactPhoneNumber":null,"isEmailDisabled":false,"source":null,"thirdPartyCompanyId":null,"state":null,"commonSettings":{},"logoUrl":"","createTime":0,"authConfigs":[]} \ No newline at end of file +{"id":null,"createdBy":null,"gid":null,"slug":null,"name":null,"isAutoGeneratedOrganization":null,"contactName":null,"contactEmail":null,"contactPhoneNumber":null,"isEmailDisabled":false,"source":null,"thirdPartyCompanyId":null,"state":null,"commonSettings":{},"logoUrl":"","createTime":0} \ No newline at end of file From a7ea9c9fce58177007ca670029d947995ceb5693 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 15:14:17 +0100 Subject: [PATCH 05/20] test: add node-service data source harness and catalogue scenario Adds helpers to create, test and fetch dynamic config for node-service plugin data sources, loaders for recorded plugin fixtures, and the @node-service selection tag. A catalogue scenario asserts the data source types endpoint lists exactly the registered node plugins plus every Java-native type with a null definition. Unit tests cover the request shape of the new API helpers and the fixture loaders. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 12 +- e2e/README.md | 17 +- e2e/src/api/client.ts | 64 +++- e2e/src/constants.ts | 15 + e2e/src/datasource/node-plugins.ts | 82 +++++ e2e/src/dsl/builders.ts | 27 +- e2e/src/dsl/recorded.ts | 79 +++++ .../datasource/node-plugins-catalogue.spec.ts | 87 ++++++ e2e/tests/foundation/node-plugins.spec.ts | 280 ++++++++++++++++++ 9 files changed, 650 insertions(+), 13 deletions(-) create mode 100644 e2e/src/datasource/node-plugins.ts create mode 100644 e2e/tests/datasource/node-plugins-catalogue.spec.ts create mode 100644 e2e/tests/foundation/node-plugins.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index 52d5610bff..b7eaaff61a 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -28,7 +28,7 @@ Rules say when they apply. "Existing exception" means reviewed code that deviate | invitation, sharing | `tests/workspace/` | | app list, card menu, trash, publish | `tests/apps/` | | editor interaction (drag, resize, rename, property, JS query) | `tests/editor/` | -| PostgreSQL queries, tables | `tests/datasource/` | +| PostgreSQL and node-service data source queries, tables | `tests/datasource/` | | triggers, temporary state, local storage | `tests/logic/` | | modules | `tests/modules/` | | visual components, npm components, Extensions panel | `tests/components/` | @@ -129,7 +129,8 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). ## 7. Defects @@ -177,16 +178,17 @@ MUST NOT: | Need | Helper | File | |---|---|---| -| user, app, module, permissions, datasource | `registerUser`, `createApp`, `createModule`, `publishApp`, `updateApp`, `getAppDsl`, `setPublicToAll`, `grantAppPermission`, `createPostgresDatasource`, `createN8nDatasource`, `setNpmRegistry`, `createInvitation`, `acceptInvitation` | `src/api/client.ts` | +| user, app, module, permissions, datasource | `registerUser`, `createApp`, `createModule`, `publishApp`, `updateApp`, `getAppDsl`, `setPublicToAll`, `grantAppPermission`, `createPostgresDatasource`, `createN8nDatasource`, `createNodePluginDatasource`, `nodePluginDatasourceBody`, `supportedDatasourceTypes`, `testDatasourceRaw`, `pluginDynamicConfigRaw`, `setNpmRegistry`, `createInvitation`, `acceptInvitation` | `src/api/client.ts` | | component from its recording | `component`, `recordedItem`, `recordedHook`, `recordedHookOf`, `hook` | `src/dsl/builders.ts`, `src/dsl/recorded.ts` | | layout and app | `stackItems`, `containerOf`, `appDsl`, `button`, `text`, `input`, `table`, `barChart` | `src/dsl/builders.ts` | | events and actions | `eventHandler`, `executeQuery`, `setTempState`, `runScript`, `executeComp`, `triggerModuleEvent` | `src/dsl/builders.ts` | -| queries, state, logic | `postgresQuery`, `jsQuery`, `n8nWorkflowsQuery` (recordings in `fixtures/dsl/n8n/`, loaded by `recordedN8nQuery` and `recordedN8nDatasource`), `tempState`, `transformer`, `dataResponder` | `src/dsl/builders.ts` | +| queries, state, logic | `postgresQuery`, `jsQuery`, `n8nWorkflowsQuery` (recordings in `fixtures/dsl/n8n/`, loaded by `recordedN8nQuery` and `recordedN8nDatasource`), `nodePluginQuery` (recordings in `fixtures/dsl/plugins//`, loaded by `recordedPluginQuery` and `recordedPluginDatasource`, checked by `parsePluginRecording`), `tempState`, `transformer`, `dataResponder` | `src/dsl/builders.ts` | | modules | `moduleApp`, `moduleInstance`, `scenarioModuleDsl`, `waitForSavedInstance`, `HandlerRetryBudget` | `src/dsl/builders.ts`, `src/modules/moduleScenario.ts` | | bound text, nested override, seeded view | `boundText`, `withValueAt`, `openSeededView` | `src/components/scenario.ts` | | containers and slots | `containerWithChildren`, `slotChild`, `slotContainers`, `openSeededApp` | `src/simple-components/seed.ts` | | catalogue, saved-DSL polling | `INSERT_TYPES`, `HOOK_TYPES`, `searchTextOf`, `waitForSavedType`, `prepareForPublish` | `src/components/insert-catalog.ts`, `src/components/insert-all.ts` | | notes and products queries | `selectProductsQuery`, `selectNotesQuery`, `noteWriteQuery`, `insertUpdateDeleteQueries` | `src/datasource/notes-queries.ts` | +| node-service plugin ids and catalogue | `NODE_PLUGIN_IDS`, `nodePluginIdsOf`, `NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL` | `src/datasource/node-plugins.ts` | | negative and counter reads, local storage | `expectTextStays`, `countAfterEquals`, `parseCounter`, `rawLocalStorage` | `src/logic/helpers.ts` | | media | `PNG_RED`, `PNG_BLUE`, `WAV`, `WEBM`, `MP4`, `PDF`, `PDF_RAW_B64` | `src/media.ts` | | security actors, quarantine, answers, tokens | `Actor`, `adminOfApiUser`, `joinWorkspace`, `makeDeveloper`, `makeAdmin`, `grantApp`, `seedPrivateApp`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `securityTestDetails`, `securityCandidateDetails`, `expectAnswer`, `expectDeniedAs`, `forgeApiKeyToken`, `forgeUnsignedToken`, `withRandomSignature`, `tokenIsSignedWith`, `superAdminCredentials`, `SUPER_ADMIN_ENV`, `enterpriseAdmin` (ENTERPRISE stack: an actor the super admin makes admin of the one workspace), `echoTargetPath`, `echoReadPrefix`, `echoBaseUrl`, `recordsContain` (requests the SERVER makes, read back from the HTTP echo sidecar: the `echo` fixture gives a test its own target `url` and `received()`; a denial must follow a positive control that the echo does receive from that path; compare a secret with `recordsContain(...)` as a boolean, never as a matcher's value) (the `actor`, `superAdmin` and `echo` fixtures are in `src/fixtures.ts`; the raw-answer helper `apiRaw` and the other security API helpers are in `src/api/client.ts`) | `src/security/actors.ts`, `scene.ts`, `quarantine.ts`, `assertions.ts`, `tokens.ts`, `super-admin.ts`, `enterprise.ts`, `echo.ts` | @@ -194,7 +196,7 @@ MUST NOT: Accepted exception to the `test` import rule: stack-free unit specs that open no browser page (no `page`, no app) may import `test` from `@playwright/test`, because the network guard only guards browser contexts. Existing: -`foundation/builders.spec.ts`, `recorded.spec.ts`, `run-selection.spec.ts`, `media.spec.ts`, and the security specs +`foundation/builders.spec.ts`, `recorded.spec.ts`, `node-plugins.spec.ts`, `run-selection.spec.ts`, `media.spec.ts`, and the security specs `foundation/security-api-raw.spec.ts`, `security-echo.spec.ts` and `lifecycle-mail-sink.spec.ts` (start `scripts/echo-server.js` on loopback ports), `lifecycle-mail.spec.ts`, `security-quarantine.spec.ts`, `security-constants.spec.ts`, `security-tokens.spec.ts`, `security-assertions.spec.ts`, `security-super-admin.spec.ts`. Anything that opens a page or talks to the stack imports from `src/fixtures`. diff --git a/e2e/README.md b/e2e/README.md index 2f8e1afd6b..a40df18fd7 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL; the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue only, D3: which plugins the image serves and that each definition has a form and a query config; no plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -209,6 +209,7 @@ e2e/ fixtures/sql/init.sql PostgreSQL data: items, products, notes fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; no plugin is recorded yet, so the folder appears with the first recording src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -220,6 +221,7 @@ e2e/ pages/ page objects: AppList, AppView, Auth, Datasource, Editor, Extensions panel, Login, Property panel, Query panel, Setting, TableView, UserMenu logic/helpers.ts rawLocalStorage, countAfterEquals, parseCounter, expectTextStays, DEBOUNCE_SETTLE_MS datasource/notes-queries.ts query builders: shared read-only products, owner-scoped notes + datasource/node-plugins.ts `NODE_PLUGIN_IDS` (the 46 node plugin ids), `nodePluginIdsOf`, `NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL` components/ insert-all.ts (S1 helpers), insert-catalog.ts (112 types), scenario.ts (boundText, withValueAt, openSeededView) simple-components/seed.ts container and slot seeds, openSeededApp modules/moduleScenario.ts module scenario DSL, saved-instance polling, HandlerRetryBudget @@ -244,15 +246,16 @@ Test titles carry these ids. - S16 npm plugins in the Extensions panel; S17 AI Chat; S18 chat controller and iframe; S19 npm templates; S20 chat box. - L1 temporary states; L2 local storage; L3 query triggers. - D1 a PostgreSQL query feeds a text and a table, write queries re-read; D2 table with query data (sort, page, filter, edit). +- D3 the plugin catalogue of node-service: the image serves exactly the registered node plugins, each definition has a form and a query config, the Java-native types carry no definition (`@node-service`; the catalogue only, no plugin query runs). - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`, after this branch's security fixes; this is a static listing, not a Docker run. A combined final run against an image built from this branch (tag `secfix-combined-e2e`) has since confirmed pass/fail for every scenario named in the per-defect rows below: 693/696 default tests passed, the 3 failures pre-existing or unrelated suite drift (documented in their own rows below)): -default **696 tests in 104 files**; with `E2E_INCLUDE_QUARANTINE=1` **709 in 105**; with `E2E_INCLUDE_SUPERADMIN=1` **701 in 104**; with both of those **714 in 105**; -with `E2E_INCLUDE_INSERT_ALL=1` **808 in 105**; with all three opt-in variables **826 in 106** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: +default **713 tests in 106 files**; with `E2E_INCLUDE_QUARANTINE=1` **726 in 107**; with `E2E_INCLUDE_SUPERADMIN=1` **718 in 106**; with both of those **731 in 107**; +with `E2E_INCLUDE_INSERT_ALL=1` **825 in 107**; with all three opt-in variables **843 in 108** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111. On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 17 (the 14 unit tests of `foundation/node-plugins.spec.ts` and D3a to D3c; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -301,7 +304,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | editor/js-query.spec.ts | a JS query written in the editor runs | @core | 1 | | editor/drop-size.spec.ts | a component dropped right after ready has width above 0 (D-5) | @quarantine | 1 | -### datasource (10) +### datasource (13) | File | Proves | Tags | Tests | |---|---|---|---| @@ -309,6 +312,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/table.spec.ts | D2: editor-built table bound to a query; published table; sort, page, select, filter, notes edit/save | @core @slow | 3 | | datasource/query-feeds-components.spec.ts | D1: query feeds text and table, owner-scoped writes re-read, chart renders | @core @slow @npm | 1 | | datasource/notes-queries.spec.ts | unit tests of the query builders | none | 4 | +| datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -452,12 +456,13 @@ first makes sure some admin exists (accepting both answers), so none depends on SEC-R09d (D-38) left the quarantine: the check took the workspace of the first id of a `HashSet`; each id is now decided in its own workspace (Java unit and MongoDB integration tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)). Accounting of the earlier 3.0.0 run `E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --workers=4 --reporter=list --grep "@quarantine" tests/security` (measured before the `@superadmin` tag existed and before the reassessment, so it listed 44 tests, 19 of which have since left the quarantine): 44 listed, 43 failed, 1 passed (SEC-R09d); the two quarantined tests of `foundation/security-helpers.spec.ts` are outside that folder. -### foundation (264 default, 267 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) +### foundation (278 default, 281 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) | File | Proves | Tags | Tests | |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server | @node-service | 14 | | foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources) | none | 27 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | diff --git a/e2e/src/api/client.ts b/e2e/src/api/client.ts index bacfd64f20..8298508d45 100644 --- a/e2e/src/api/client.ts +++ b/e2e/src/api/client.ts @@ -1,5 +1,5 @@ import type { APIRequestContext, APIResponse } from "@playwright/test"; -import { recordedN8nDatasource } from "../dsl/recorded"; +import { recordedN8nDatasource, type RecordedPluginDatasource } from "../dsl/recorded"; import { API_ERRORS, API_OK, @@ -35,6 +35,7 @@ import { NEW_USER_GUIDANCE_STATUS, NPM_REGISTRIES_SETTING_KEY, orgCommonSettingsPath, + orgDatasourceTypesPath, orgMembersPath, orgRemoveMemberPath, orgRolePath, @@ -1033,3 +1034,64 @@ export async function createN8nDatasource( ); return data.id; } + +/** The definition a node plugin serves in the catalogue (`listPlugins`, `server/node-service/src/services/plugin.ts`): the form and query config; the fields a test reads are typed, the rest is open. */ +export interface NodePluginDefinition { + id?: string; + name?: string; + dataSourceConfig?: { type?: string; params?: unknown; extra?: unknown }; + /** `{ type: "query", ... }` or, for a plugin whose config is a function, `{ type: "dynamic" }`. */ + queryConfig?: { type?: string; [key: string]: unknown }; + shouldValidateDataSourceConfig?: boolean; + [key: string]: unknown; +} + +/** + * One entry of `GET /api/organizations/{orgId}/datasourceTypes`. `DatasourceMetaInfo.java` serialises its `type` as `id` and + * its `displayName` as `name` (`@JsonProperty`). `definition` is null for a Java-native type. + */ +export interface DatasourceTypeEntry { + id: string; + name?: string; + definition: NodePluginDefinition | null; +} + +/** The data source types the image serves, as the caller sees them in `orgId` (Java-native types, then every node plugin). */ +export async function supportedDatasourceTypes(request: APIRequestContext, orgId: string): Promise { + return unwrap(`list the data source types of ${orgId}`, await request.get(orgDatasourceTypesPath(orgId))); +} + +/** The `POST /api/datasources` body of a node-plugin data source: the recorded form body with the workspace set and `config` merged over its `datasourceConfig` (the target and the credentials). */ +export function nodePluginDatasourceBody( + recorded: RecordedPluginDatasource, + params: { orgId: string; name?: string; config: Record }, +): object { + return { + ...recorded, + name: params.name ?? recorded.name, + organizationId: params.orgId, + datasourceConfig: { ...recorded.datasourceConfig, ...params.config }, + }; +} + +/** Creates a data source of a node plugin from its recording; returns its id. */ +export async function createNodePluginDatasource( + request: APIRequestContext, + params: { orgId: string; name?: string; recorded: RecordedPluginDatasource; config: Record }, +): Promise { + const data = await unwrap<{ id: string }>( + `create ${params.recorded.type} datasource`, + await request.post(API_PATHS.DATASOURCES, { data: nodePluginDatasourceBody(params.recorded, params) }), + ); + return data.id; +} + +/** `POST /api/datasources/test` with a data source body (the connection test; only plugins that define a validator answer more than success). Raw answer. */ +export async function testDatasourceRaw(request: APIRequestContext, body: object): Promise { + return apiRaw(request, "POST", API_PATHS.DATASOURCE_TEST, { data: body }); +} + +/** `POST /api/datasources/getPluginDynamicConfig` with the list of requests (`GetPluginDynamicConfigRequestDTO`). Raw answer. */ +export async function pluginDynamicConfigRaw(request: APIRequestContext, dtos: object[]): Promise { + return apiRaw(request, "POST", API_PATHS.PLUGIN_DYNAMIC_CONFIG, { data: dtos }); +} diff --git a/e2e/src/constants.ts b/e2e/src/constants.ts index a4a81f1a11..62e55ac7b2 100644 --- a/e2e/src/constants.ts +++ b/e2e/src/constants.ts @@ -26,6 +26,10 @@ export const API_PATHS = { INVITATION: "/api/invitation", MARK_USER_STATUS: "/api/users/mark-status", DATASOURCES: "/api/datasources", + /** `POST /api/datasources/test`: the connection test of a data source body (`DatasourceEndpoints.java`, `@PostMapping("/test")`). */ + DATASOURCE_TEST: "/api/datasources/test", + /** `POST /api/datasources/getPluginDynamicConfig`: the dynamic form parameters of a node plugin (`DatasourceEndpoints.java`, `@PostMapping("/getPluginDynamicConfig")`). */ + PLUGIN_DYNAMIC_CONFIG: "/api/datasources/getPluginDynamicConfig", // Routes of the security helpers and scenarios (tests/security/): APPLICATION_RECORDS: "/api/application-records", APPLICATION_HISTORY_SNAPSHOTS: "/api/application/history-snapshots", @@ -202,6 +206,12 @@ export const TAGS = { * Every fixture that makes a user signs up, so no other test can run on that stack. */ SIGNUP_DISABLED: "@signup-disabled", + /** + * The tests of the data sources that run in node-service (the node plugins: the catalogue of the image, DuckDB, the + * plugins pointed at the echo sidecar) and the stack-free unit spec of their helpers. A selection tag + * (`--grep @node-service`), not an opt-in one: these tests stay in the default run. + */ + NODE_SERVICE: "@node-service", } as const; /** Environment variables that widen the run beyond the default selection (read by playwright.config.ts). */ @@ -676,6 +686,11 @@ export function datasourcesByOrgPath(): string { return `${API_PATHS.DATASOURCES}/listByOrg`; } +/** `GET /api/organizations/{orgId}/datasourceTypes`: the Java-native types plus every node plugin with its `definition` (`OrganizationEndpoints.java`, `@GetMapping("/{orgId}/datasourceTypes")`). */ +export function orgDatasourceTypesPath(orgId: string): string { + return `${orgPath(orgId)}/datasourceTypes`; +} + /** `GET /api/bundles/recycle/list`: the trash of bundles. */ export const BUNDLE_RECYCLE_LIST_PATH = "/api/bundles/recycle/list"; diff --git a/e2e/src/datasource/node-plugins.ts b/e2e/src/datasource/node-plugins.ts new file mode 100644 index 0000000000..4ec41c7296 --- /dev/null +++ b/e2e/src/datasource/node-plugins.ts @@ -0,0 +1,82 @@ +import type { DatasourceTypeEntry } from "../api/client"; + +/** + * The ids of the node plugins the node-service registry serves, as the registry lists them + * (`server/node-service/src/plugins/index.ts:50-126`, 46 entries). Note the ids that differ from their folder names: + * `OpenAI` (`openAi/index.ts`), `oss` (`aliyunOss/index.ts`) and `firebird` (`firebirdsql/index.ts:10`). The `graphql` type + * is a Java-native type (`DatasourceMetaInfoServiceImpl.java:142-146`); node-service's `graphql/` folder is a helper and + * is not registered. This is the set the catalogue test measures against the image; never edit it to make that test pass. + */ +export const NODE_PLUGIN_IDS: readonly string[] = [ + // Databases + "dynamodb", + "couchdb", + "duckdb", + "fauna", + "turso", + "firebird", + // Big Data + "athena", + "bigQuery", + // AI + "OpenAI", + "huggingFaceEndpoint", + "huggingFaceInference", + "did", + // DevOps + "appconfig", + "datadog", + "circleCi", + // App Development + "openApi", + "postmanEcho", + "lowcoder", + "github", + "gitlab", + "lambda", + "firebase", + "supabaseApi", + // Workflow + "n8n", + "boomi", + // Messaging + "twilio", + "sendGrid", + "oneSignal", + // Assets + "s3", + "googleCloudStorage", + "supabase", + "cloudinary", + "oss", + // Project Management + "asana", + "jira", + "notion", + "slack", + // Reports and Document Creation + "apiTemplate", + "carboneIo", + // CRM + "front", + // E-commerce + "stripe", + "shopify", + "woocommerce", + // Webscrapers + "serpApi", + "eodhdApi", + // RPA + "uiPath", +]; + +/** The value of a placeholder host in recorded data source bodies: the `.invalid` TLD (RFC 2606) never resolves, so a recording that was not given a real target fails instead of reaching a host. */ +export const NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL = "http://placeholder.invalid"; + +/** + * The ids of the catalogue entries that are node plugins: the ones that carry a `definition` (the Java-native types answer + * `definition: null`, `DatasourceMetaInfoServiceImpl.java:189-199`). Order as served. + */ +export function nodePluginIdsOf(types: readonly DatasourceTypeEntry[]): string[] { + return types.filter((entry) => entry.definition !== null && entry.definition !== undefined).map((entry) => entry.id); +} diff --git a/e2e/src/dsl/builders.ts b/e2e/src/dsl/builders.ts index 1a3fdb2e75..176df4b1a5 100644 --- a/e2e/src/dsl/builders.ts +++ b/e2e/src/dsl/builders.ts @@ -9,7 +9,7 @@ * * Typical use: `appDsl(stackItems([text(...), button(...)]), { queries: [...], tempStates: [...] })`. */ -import { recordedBaseHooks, recordedHook, recordedItem, recordedN8nQuery, type RecordedHook } from "./recorded"; +import { recordedBaseHooks, recordedHook, recordedItem, recordedN8nQuery, type RecordedHook, type RecordedPluginQuery } from "./recorded"; export interface GridPosition { x: number; @@ -464,6 +464,31 @@ export function n8nWorkflowsQuery( }; } +/** + * A query on a node-service data source (a node plugin), from the query the editor saved (`recordedPluginQuery(id)`): the + * recorded `compType` and `comp`, with `action` merged by key over the recorded action (the generated `actionName` and the + * action's other defaults stay). The recording is deep-copied, so a call never changes what the next call starts from. + * Starts `manual` like `n8nWorkflowsQuery`: a test runs it with `POST /api/query/execute` or a button. + */ +export function nodePluginQuery( + params: { + id: string; + name: string; + datasourceId: string; + recorded: RecordedPluginQuery; + action?: Record; + trigger?: PostgresQueryTrigger; + } & QueryOptions, +): object { + const recorded = structuredClone(params.recorded); + return { + compType: recorded.compType, + comp: { ...recorded.comp, action: { ...recorded.comp.action, ...structuredClone(params.action ?? {}) } }, + datasourceId: params.datasourceId, + ...queryDefaults({ ...params, trigger: params.trigger ?? "manual" }), + }; +} + // --------------------------------------------------------------------------------------------------------------- // State and logic items // --------------------------------------------------------------------------------------------------------------- diff --git a/e2e/src/dsl/recorded.ts b/e2e/src/dsl/recorded.ts index 50cb3d73da..1ca3a5c9d9 100644 --- a/e2e/src/dsl/recorded.ts +++ b/e2e/src/dsl/recorded.ts @@ -206,3 +206,82 @@ export function recordedN8nDatasource(): RecordedN8nDatasource { } return structuredClone(parsed) as unknown as RecordedN8nDatasource; } + +/** + * Folder of the recordings of the node-service data sources (`fixtures/dsl/plugins//`): per plugin the create request + * the data source form sent (`Datasource.json`) and the query the editor saved for one action (`Query.json`). A + * subfolder for the same reason as `RECORDED_N8N_DIR`. + */ +export const RECORDED_PLUGINS_DIR = join(RECORDED_DSL_DIR, "plugins"); + +/** A plugin id is a folder name: letters and digits only, so an id can never leave `RECORDED_PLUGINS_DIR`. */ +const PLUGIN_ID_PATTERN = /^[A-Za-z0-9]+$/; + +/** Recorded query of a node plugin (what the editor saved in the app DSL's `queries`), reduced to type and `comp`; ids, order and data source are set by `nodePluginQuery`. */ +export interface RecordedPluginQuery { + compType: string; + comp: { actionName: string; action: Record; [key: string]: unknown }; + [key: string]: unknown; +} + +/** Recorded body of the `POST /api/datasources` the form sends for a node plugin, reduced to name, type and settings; the workspace is set by `nodePluginDatasourceBody`. */ +export interface RecordedPluginDatasource { + name: string; + type: string; + datasourceConfig: Record; +} + +/** + * Parses the text of a node-plugin recording and checks what the readers rely on. With `expect.compType` the text must be a + * saved query: that `compType`, and a `comp` with a string `actionName` and an object `action`. With `expect.type` it must be + * a data source body: that `type`, a string `name` and an object `datasourceConfig`. `label` is the path of the recording + * below `RECORDED_DSL_DIR` without `.json`. Throws `RecordedFixtureError` naming the file; returns the parsed value. + */ +export function parsePluginRecording(label: string, text: string, expect: { compType?: string; type?: string }): Record { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch (error) { + throw new RecordedFixtureError(label, error instanceof Error ? error.message : String(error)); + } + if (!isObject(parsed)) throw new RecordedFixtureError(label, "is not a JSON object"); + if (expect.compType !== undefined) { + if (parsed.compType !== expect.compType) { + throw new RecordedFixtureError(label, `has compType ${JSON.stringify(parsed.compType)}, expected ${JSON.stringify(expect.compType)}`); + } + if (!isObject(parsed.comp) || typeof parsed.comp.actionName !== "string" || !isObject(parsed.comp.action)) { + throw new RecordedFixtureError(label, "has no `comp` with a string `actionName` and an `action` object"); + } + } + if (expect.type !== undefined) { + if (parsed.type !== expect.type) { + throw new RecordedFixtureError(label, `has type ${JSON.stringify(parsed.type)}, expected ${JSON.stringify(expect.type)}`); + } + if (typeof parsed.name !== "string" || !isObject(parsed.datasourceConfig)) { + throw new RecordedFixtureError(label, "has no string `name` and `datasourceConfig` object"); + } + } + return parsed; +} + +function loadPluginRecording(pluginId: string, suffix: "Query" | "Datasource", expect: { compType?: string; type?: string }): Record { + const label = `plugins/${pluginId}/${pluginId}${suffix}`; + if (!PLUGIN_ID_PATTERN.test(pluginId)) throw new RecordedFixtureError(label, "the plugin id is not a folder name (letters and digits only)"); + let text: string; + try { + text = readFileSync(join(RECORDED_PLUGINS_DIR, pluginId, `${pluginId}${suffix}.json`), "utf8"); + } catch (error) { + throw new RecordedFixtureError(label, error instanceof Error ? error.message : String(error)); + } + return parsePluginRecording(label, text, expect); +} + +/** The query the editor saved for plugin `pluginId`, as a fresh deep copy; its `compType` is the plugin id. Throws RecordedFixtureError when missing or malformed. */ +export function recordedPluginQuery(pluginId: string): RecordedPluginQuery { + return structuredClone(loadPluginRecording(pluginId, "Query", { compType: pluginId })) as unknown as RecordedPluginQuery; +} + +/** The create body the form sent for a data source of plugin `pluginId`, as a fresh deep copy; its `type` is the plugin id. Throws RecordedFixtureError when missing or malformed. */ +export function recordedPluginDatasource(pluginId: string): RecordedPluginDatasource { + return structuredClone(loadPluginRecording(pluginId, "Datasource", { type: pluginId })) as unknown as RecordedPluginDatasource; +} diff --git a/e2e/tests/datasource/node-plugins-catalogue.spec.ts b/e2e/tests/datasource/node-plugins-catalogue.spec.ts new file mode 100644 index 0000000000..ad9e625f6e --- /dev/null +++ b/e2e/tests/datasource/node-plugins-catalogue.spec.ts @@ -0,0 +1,87 @@ +import { supportedDatasourceTypes, type DatasourceTypeEntry } from "../../src/api/client"; +import { TAGS } from "../../src/constants"; +import { NODE_PLUGIN_IDS, nodePluginIdsOf } from "../../src/datasource/node-plugins"; +import { expect, test } from "../../src/fixtures"; + +/** + * D3: which node plugins the image under test serves. The catalogue (`GET /api/organizations/{orgId}/datasourceTypes`, + * `OrganizationController.getSupportedDatasourceTypes`) answers the Java-native types, which carry no definition, and every + * plugin of node-service's registry (`server/node-service/src/plugins/index.ts`) with its `definition`. For the plugins whose + * host is fixed to a vendor cloud this is the only coverage: their definition is served, nothing more. + * + * The three tests are structural assertions: they need no "before" state. + */ + +/** + * The Java-native types the catalogue lists, measured on `3.0.0-e2e` and `3.0.1-e2e` and matching + * `DatasourceMetaInfoServiceImpl.java:35-146` (`clickHouse` is capitalised like that and the lookup is case-sensitive; the + * special lookup of `lowcoderApi` at `:177` is not a catalogue entry). The Java plugins serve them, never node-service. + */ +const JAVA_NATIVE_TYPES = [ + "postgres", + "restApi", + "mongodb", + "mysql", + "es", + "redis", + "mssql", + "oracle", + "mariadb", + "smtp", + "clickHouse", + "snowflake", + "googleSheets", + "graphql", +] as const; + +/** What a plugin's query config may be: `listPlugins` keeps an object and replaces a function with `{ type: "dynamic" }` (`services/plugin.ts:162-176`). */ +const DYNAMIC_CONFIG_TYPE = "dynamic"; + +/** The problems of one served plugin definition, each prefixed with the plugin id; empty when the definition is complete. */ +function definitionProblems(entry: DatasourceTypeEntry): string[] { + const definition = entry.definition; + if (!definition) return [`${entry.id}: no definition`]; + const problems: string[] = []; + if (!Array.isArray(definition.dataSourceConfig?.params)) { + problems.push(`${entry.id}: dataSourceConfig.params is ${JSON.stringify(definition.dataSourceConfig?.params)}, not an array`); + } + const queryConfig = definition.queryConfig; + if (typeof queryConfig !== "object" || queryConfig === null || Array.isArray(queryConfig)) { + problems.push(`${entry.id}: queryConfig is ${JSON.stringify(queryConfig)}, not an object`); + } else if (typeof queryConfig.type !== "string" || queryConfig.type === "") { + problems.push(`${entry.id}: queryConfig has no string type (a query config is "query" or "${DYNAMIC_CONFIG_TYPE}")`); + } + return problems; +} + +test.describe("node-service plugin catalogue", { tag: [TAGS.NODE_SERVICE] }, () => { + test("D3a: the image serves exactly the registered node-service plugins", async ({ page, apiUser }) => { + const types = await supportedDatasourceTypes(page.request, apiUser.orgId); + const served = nodePluginIdsOf(types); + expect(served.length, "the catalogue lists no node plugin at all").toBeGreaterThan(0); + expect([...served].sort(), "the node plugins the catalogue serves").toEqual([...NODE_PLUGIN_IDS].sort()); + }); + + test("D3b: every node plugin definition has a data source form and a query config", async ({ page, apiUser }) => { + const types = await supportedDatasourceTypes(page.request, apiUser.orgId); + const plugins = types.filter((entry) => entry.definition); + expect(plugins.length, "the catalogue lists no node plugin at all").toBeGreaterThan(0); + expect(plugins.flatMap(definitionProblems), "the plugin definitions with a problem").toEqual([]); + }); + + test("D3c: Java-native types carry no node definition", async ({ page, apiUser }) => { + const types = await supportedDatasourceTypes(page.request, apiUser.orgId); + const nodePluginIds = new Set(NODE_PLUGIN_IDS); + const withoutDefinition = types.filter((entry) => entry.definition === null).map((entry) => entry.id); + // Every entry without a definition is a Java-native type and no node plugin id is among them; the explicit list below + // fails when a Java type is dropped or renamed, the derived one when an unexpected type appears. + expect([...withoutDefinition].sort(), "the catalogue entries with an explicit null definition").toEqual([...JAVA_NATIVE_TYPES].sort()); + expect(withoutDefinition.filter((id) => nodePluginIds.has(id)), "a node plugin id without a definition").toEqual([]); + for (const type of JAVA_NATIVE_TYPES) { + const entries = types.filter((entry) => entry.id === type); + expect(entries, `the catalogue lists the Java-native type ${type} once`).toHaveLength(1); + // An explicit null, not an absent key: `DatasourceMetaInfo.definition` is serialised as null. + expect(entries[0], `${type} carries an explicit null definition`).toHaveProperty("definition", null); + } + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts new file mode 100644 index 0000000000..8c491f74de --- /dev/null +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -0,0 +1,280 @@ +import { createServer, type IncomingMessage, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { expect, test } from "@playwright/test"; +import { createNodePluginDatasource, LowcoderApiError, nodePluginDatasourceBody, pluginDynamicConfigRaw, testDatasourceRaw } from "../../src/api/client"; +import { API_OK, API_PATHS, orgDatasourceTypesPath, TAGS } from "../../src/constants"; +import { nodePluginQuery } from "../../src/dsl/builders"; +import { + parsePluginRecording, + RecordedFixtureError, + recordedPluginDatasource, + recordedPluginQuery, + type RecordedPluginDatasource, + type RecordedPluginQuery, +} from "../../src/dsl/recorded"; +import { NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL, NODE_PLUGIN_IDS, nodePluginIdsOf } from "../../src/datasource/node-plugins"; + +/** + * Stack-free unit spec of the node-service data source helpers (parser, loaders, builder, body helper, catalogue filter). + * It carries the selection tag of the node-service tests although it is a unit spec (accepted exception to "unit tests are + * untagged", AGENTS.md section 6). + */ +const PLUGIN_ID = "demoplugin"; +const RECORDED_QUERY: RecordedPluginQuery = { + compType: PLUGIN_ID, + comp: { actionName: "run_it", action: { "query_@_sql": "select 1", "query_@_limit": 10, nested: { deep: ["a"] } }, headers: [] }, +}; +const RECORDED_DATASOURCE: RecordedPluginDatasource = { + name: PLUGIN_ID, + type: PLUGIN_ID, + datasourceConfig: { url: NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL, token: "placeholder", mode: "recorded" }, +}; +const BUILD_PARAMS = { id: "q1", name: "query1", datasourceId: "ds1" }; + +test.describe("node-service data source helpers", { tag: [TAGS.NODE_SERVICE] }, () => { + test("parsePluginRecording accepts a saved query and a data source body", () => { + expect(parsePluginRecording("plugins/x/xQuery", JSON.stringify(RECORDED_QUERY), { compType: PLUGIN_ID })).toEqual(RECORDED_QUERY); + expect(parsePluginRecording("plugins/x/xDatasource", JSON.stringify(RECORDED_DATASOURCE), { type: PLUGIN_ID })).toEqual(RECORDED_DATASOURCE); + }); + + test("parsePluginRecording rejects a wrong type, a missing actionName and malformed text with RecordedFixtureError naming the file", () => { + const label = "plugins/x/xQuery"; + const rejected: [string, string, { compType?: string; type?: string }, RegExp][] = [ + ["a wrong compType", JSON.stringify({ ...RECORDED_QUERY, compType: "other" }), { compType: PLUGIN_ID }, /compType "other", expected "demoplugin"/], + ["no comp.actionName", JSON.stringify({ compType: PLUGIN_ID, comp: { action: {} } }), { compType: PLUGIN_ID }, /string `actionName`/], + ["a numeric comp.actionName", JSON.stringify({ compType: PLUGIN_ID, comp: { actionName: 1, action: {} } }), { compType: PLUGIN_ID }, /string `actionName`/], + ["no comp.action", JSON.stringify({ compType: PLUGIN_ID, comp: { actionName: "a" } }), { compType: PLUGIN_ID }, /`action` object/], + ["a wrong type", JSON.stringify({ ...RECORDED_DATASOURCE, type: "other" }), { type: PLUGIN_ID }, /type "other", expected "demoplugin"/], + ["no datasourceConfig", JSON.stringify({ name: "n", type: PLUGIN_ID }), { type: PLUGIN_ID }, /`datasourceConfig` object/], + ["an array", "[]", { compType: PLUGIN_ID }, /not a JSON object/], + ["invalid JSON", "{", { compType: PLUGIN_ID }, /JSON/], + ]; + for (const [description, text, expectation, message] of rejected) { + let error: unknown; + try { + parsePluginRecording(label, text, expectation); + } catch (thrown) { + error = thrown; + } + expect(error, description).toBeInstanceOf(RecordedFixtureError); + expect((error as Error).message, `${description}: names the file`).toContain(label); + expect((error as Error).message, `${description}: names the reason`).toMatch(message); + } + }); + + test("recordedPluginQuery and recordedPluginDatasource throw RecordedFixtureError for a missing recording and for an id that is no folder name", () => { + for (const load of [recordedPluginQuery, recordedPluginDatasource]) { + expect(() => load("noSuchPlugin"), `${load.name}: no recording`).toThrow(RecordedFixtureError); + expect(() => load("../n8n/n8n"), `${load.name}: path traversal`).toThrow(/letters and digits only/); + expect(() => load(""), `${load.name}: empty id`).toThrow(RecordedFixtureError); + } + }); + + test("nodePluginQuery keeps the recording, merges the action by key and runs manually", () => { + const query = nodePluginQuery({ ...BUILD_PARAMS, recorded: RECORDED_QUERY, action: { "query_@_sql": "select 2", extra: true } }) as { + compType: string; + comp: { actionName: string; action: Record; headers: unknown[] }; + datasourceId: string; + id: string; + name: string; + triggerType: string; + }; + expect(query).toMatchObject({ compType: PLUGIN_ID, datasourceId: "ds1", id: "q1", name: "query1", triggerType: "manual" }); + expect(query.comp.actionName, "the recorded action name").toBe("run_it"); + expect(query.comp.headers, "the other comp keys").toEqual([]); + expect(query.comp.action["query_@_sql"], "the merged key").toBe("select 2"); + expect(query.comp.action.extra, "a key the recording lacks").toBe(true); + expect(query.comp.action["query_@_limit"], "a key the call leaves alone").toBe(10); + expect(nodePluginQuery({ ...BUILD_PARAMS, recorded: RECORDED_QUERY, trigger: "automatic" })).toMatchObject({ triggerType: "automatic" }); + }); + + test("nodePluginQuery changes neither the recording it was given nor the result of the next call", () => { + const before = structuredClone(RECORDED_QUERY); + const first = nodePluginQuery({ ...BUILD_PARAMS, recorded: RECORDED_QUERY, action: { "query_@_sql": "select 3", nested: { deep: ["b"] } } }) as { comp: { action: Record } }; + (first.comp.action.nested as { deep: string[] }).deep.push("mutated"); + expect(RECORDED_QUERY, "the recording").toEqual(before); + const second = nodePluginQuery({ ...BUILD_PARAMS, recorded: RECORDED_QUERY }) as { comp: { action: Record } }; + expect(second.comp.action["query_@_sql"], "no value of the first call").toBe("select 1"); + expect(second.comp.action.nested, "no nested value of the first call").toEqual({ deep: ["a"] }); + }); + + test("nodePluginDatasourceBody sets the workspace, merges the config and keeps the other recorded keys", () => { + const recorded = { ...RECORDED_DATASOURCE, extraKey: "kept" } as RecordedPluginDatasource; + const before = structuredClone(recorded); + const body = nodePluginDatasourceBody(recorded, { orgId: "org-1", config: { url: "http://e2e-echo:1/t", token: "secret" } }) as Record; + expect(body.organizationId, "the workspace").toBe("org-1"); + expect(body.name, "the recorded name").toBe(PLUGIN_ID); + expect(body.type, "the recorded type").toBe(PLUGIN_ID); + expect(body.extraKey, "another recorded key").toBe("kept"); + expect(body.datasourceConfig, "the config over the recorded settings").toEqual({ url: "http://e2e-echo:1/t", token: "secret", mode: "recorded" }); + expect(recorded, "the recording").toEqual(before); + expect(nodePluginDatasourceBody(recorded, { orgId: "org-1", name: "renamed", config: {} })).toMatchObject({ name: "renamed" }); + }); + + test("the recorded placeholder host is one that never resolves", () => { + expect(new URL(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL).hostname.endsWith(".invalid")).toBe(true); + }); + + test("nodePluginIdsOf keeps the entries with a definition, in order, and drops the null and absent ones", () => { + const types = [ + { id: "postgres", definition: null }, + { id: "duckdb", definition: { id: "duckdb" } }, + { id: "graphql", definition: null }, + { id: "n8n", definition: { id: "n8n", dataSourceConfig: { params: [] } } }, + { id: "restApi" } as unknown as { id: string; definition: null }, + ]; + expect(nodePluginIdsOf(types)).toEqual(["duckdb", "n8n"]); + expect(nodePluginIdsOf([]), "an empty catalogue").toEqual([]); + }); + + test("NODE_PLUGIN_IDS lists 46 distinct ids, with the ids that differ from their folder names", () => { + expect(NODE_PLUGIN_IDS, "the registry size").toHaveLength(46); + expect(new Set(NODE_PLUGIN_IDS).size, "distinct ids").toBe(NODE_PLUGIN_IDS.length); + expect(NODE_PLUGIN_IDS, "ids that differ from their folder names").toEqual(expect.arrayContaining(["OpenAI", "oss", "firebird"])); + expect(NODE_PLUGIN_IDS, "the Java-native graphql type is not a node plugin").not.toContain("graphql"); + }); + + test("the data source routes are the Java mappings", () => { + expect(orgDatasourceTypesPath("org-1")).toBe("/api/organizations/org-1/datasourceTypes"); + expect(API_PATHS.DATASOURCE_TEST).toBe("/api/datasources/test"); + expect(API_PATHS.PLUGIN_DYNAMIC_CONFIG).toBe("/api/datasources/getPluginDynamicConfig"); + }); +}); + +/** + * The three request helpers against a local server that records what it receives (the pattern of + * `lifecycle-helpers-local.spec.ts` and `security-api-raw.spec.ts`): no stack is needed to check the path, the method, the body + * and how each helper reads the answer. + */ +const SERVER_HOST = "127.0.0.1"; +const CREATED_ID = "ds-created"; +const DENIAL_STATUS = 403; +const DENIAL_CODE = 5308; +const REFUSAL_STATUS = 400; +const REFUSAL_CODE = 5000; +/** A data source named like this is answered with a refusal by the local server; `testDatasourceRaw` and `pluginDynamicConfigRaw` get their denial from a body that holds `denied: true`. */ +const REFUSED_NAME = "refused"; +const DYNAMIC_CONFIG_ANSWER = [{ key: "spec", value: 1 }]; + +interface Received { + method: string; + url: string; + contentType: string | undefined; + body: unknown; +} + +async function readText(request: IncomingMessage): Promise { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(chunk as Buffer); + return Buffer.concat(chunks).toString("utf8"); +} + +test.describe("node-service data source request helpers", { tag: [TAGS.NODE_SERVICE] }, () => { + let server: Server; + let baseURL: string; + const received: Received[] = []; + + test.beforeAll(async () => { + server = createServer(async (request, response) => { + const text = await readText(request); + const body: unknown = text === "" ? undefined : JSON.parse(text); + received.push({ method: request.method ?? "", url: request.url ?? "", contentType: request.headers["content-type"], body }); + const json = (status: number, payload: object) => response.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(payload)); + const refused = typeof body === "object" && body !== null && (body as { name?: unknown }).name === REFUSED_NAME; + const denied = JSON.stringify(body).includes('"denied":true'); + switch (request.url) { + case API_PATHS.DATASOURCES: + return refused ? json(REFUSAL_STATUS, { code: REFUSAL_CODE, message: "refused" }) : json(200, { code: API_OK, data: { id: CREATED_ID } }); + case API_PATHS.DATASOURCE_TEST: + return denied ? json(DENIAL_STATUS, { code: DENIAL_CODE, message: "no" }) : json(200, { code: API_OK, data: true }); + case API_PATHS.PLUGIN_DYNAMIC_CONFIG: + return denied ? json(DENIAL_STATUS, { code: DENIAL_CODE, message: "no" }) : json(200, { code: API_OK, data: DYNAMIC_CONFIG_ANSWER }); + default: + return json(404, { code: 404, message: `unexpected path ${request.url}` }); + } + }); + await new Promise((resolve) => server.listen(0, SERVER_HOST, resolve)); + baseURL = `http://${SERVER_HOST}:${(server.address() as AddressInfo).port}`; + }); + + test.afterAll(async () => { + await new Promise((resolve) => server.close(() => resolve())); + }); + + test.beforeEach(() => { + received.length = 0; + }); + + test("createNodePluginDatasource posts the merged body to the data sources route and returns the new id", async ({ playwright }) => { + const request = await playwright.request.newContext({ baseURL }); + try { + const id = await createNodePluginDatasource(request, { + orgId: "org-1", + recorded: RECORDED_DATASOURCE, + config: { url: "http://e2e-echo:1/t" }, + }); + expect(id, "the id of the answer").toBe(CREATED_ID); + expect(received, "one request").toHaveLength(1); + expect(received[0], "method, path and content type").toMatchObject({ method: "POST", url: API_PATHS.DATASOURCES, contentType: "application/json" }); + expect(received[0]?.body, "the body is the one `nodePluginDatasourceBody` builds").toEqual( + nodePluginDatasourceBody(RECORDED_DATASOURCE, { orgId: "org-1", config: { url: "http://e2e-echo:1/t" } }), + ); + expect(received[0]?.body, "the workspace and the merged config").toMatchObject({ + organizationId: "org-1", + type: PLUGIN_ID, + datasourceConfig: { url: "http://e2e-echo:1/t", token: "placeholder", mode: "recorded" }, + }); + } finally { + await request.dispose(); + } + }); + + test("createNodePluginDatasource throws LowcoderApiError naming the plugin when the server refuses", async ({ playwright }) => { + const request = await playwright.request.newContext({ baseURL }); + try { + const error = await createNodePluginDatasource(request, { orgId: "org-1", name: REFUSED_NAME, recorded: RECORDED_DATASOURCE, config: {} }).then( + () => undefined, + (thrown: unknown) => thrown, + ); + expect(error, "the refusal").toBeInstanceOf(LowcoderApiError); + expect((error as Error).message, "names the action").toContain(`create ${PLUGIN_ID} datasource`); + expect((error as Error).message, "carries the status and the body").toContain(`HTTP ${REFUSAL_STATUS}`); + expect((error as Error).message, "carries the code").toContain(String(REFUSAL_CODE)); + } finally { + await request.dispose(); + } + }); + + test("testDatasourceRaw posts the body to the test route and returns the raw answer, a denial without a throw", async ({ playwright }) => { + const request = await playwright.request.newContext({ baseURL }); + try { + const body = { name: PLUGIN_ID, type: PLUGIN_ID, organizationId: "org-1", datasourceConfig: { url: "x" } }; + const accepted = await testDatasourceRaw(request, body); + expect(received[0], "method, path and content type").toMatchObject({ method: "POST", url: API_PATHS.DATASOURCE_TEST, contentType: "application/json" }); + expect(received[0]?.body, "the body as given").toEqual(body); + expect(accepted, "the accepted answer").toMatchObject({ status: 200, code: API_OK, json: { data: true } }); + + const denied = await testDatasourceRaw(request, { ...body, denied: true }); + expect(denied, "the denial is returned, not thrown").toMatchObject({ status: DENIAL_STATUS, code: DENIAL_CODE }); + expect(received, "two requests, both to the test route").toHaveLength(2); + } finally { + await request.dispose(); + } + }); + + test("pluginDynamicConfigRaw posts the list of requests to the dynamic config route and returns the raw answer", async ({ playwright }) => { + const request = await playwright.request.newContext({ baseURL }); + try { + const dtos = [{ dataSourceId: "ds-1", pluginName: PLUGIN_ID, path: "extra", data: { url: "x" } }]; + const answer = await pluginDynamicConfigRaw(request, dtos); + expect(received[0], "method, path and content type").toMatchObject({ method: "POST", url: API_PATHS.PLUGIN_DYNAMIC_CONFIG, contentType: "application/json" }); + expect(received[0]?.body, "the list is sent as the body, not wrapped").toEqual(dtos); + expect(answer, "the answer").toMatchObject({ status: 200, code: API_OK, json: { data: DYNAMIC_CONFIG_ANSWER } }); + + const denied = await pluginDynamicConfigRaw(request, [{ denied: true }]); + expect(denied, "the denial is returned, not thrown").toMatchObject({ status: DENIAL_STATUS, code: DENIAL_CODE }); + } finally { + await request.dispose(); + } + }); +}); From cb8aed93de780d18bb2ae7823cc675630d250e24 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 15:32:04 +0100 Subject: [PATCH 06/20] test: add DuckDB node-service data source scenarios Adds recorded DuckDB data source and query fixtures and scenarios that run the embedded plugin through the app: a query result, a bound component after a click, BIGINT and HUGEINT arriving as exact strings, a failing statement and a syntax error. Rows currently arrive keyed by column position rather than column name; the scenarios characterise that behaviour and annotate it as a defect candidate. A unit test covers the new recording loaders. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 2 +- e2e/README.md | 19 +- .../dsl/plugins/duckdb/duckdbDatasource.json | 10 + .../dsl/plugins/duckdb/duckdbQuery.json | 15 ++ e2e/tests/datasource/plugin-duckdb.spec.ts | 172 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 20 ++ 6 files changed, 229 insertions(+), 9 deletions(-) create mode 100644 e2e/fixtures/dsl/plugins/duckdb/duckdbDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/duckdb/duckdbQuery.json create mode 100644 e2e/tests/datasource/plugin-duckdb.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index b7eaaff61a..e7f69c7fbc 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,7 +129,7 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). diff --git a/e2e/README.md b/e2e/README.md index a40df18fd7..d4f8f2a934 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue only, D3: which plugins the image serves and that each definition has a form and a query config; no plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins only DuckDB runs queries, D4, embedded in the app container with no network; no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -209,7 +209,7 @@ e2e/ fixtures/sql/init.sql PostgreSQL data: items, products, notes fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; no plugin is recorded yet, so the folder appears with the first recording + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb` src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -247,15 +247,16 @@ Test titles carry these ids. - L1 temporary states; L2 local storage; L3 query triggers. - D1 a PostgreSQL query feeds a text and a table, write queries re-read; D2 table with query data (sort, page, filter, edit). - D3 the plugin catalogue of node-service: the image serves exactly the registered node plugins, each definition has a form and a query config, the Java-native types carry no definition (`@node-service`; the catalogue only, no plugin query runs). +- D4 the DuckDB plugin of node-service, run in the app container with an in-memory database and no network: rows, the published view after a click, a BIGINT as a string, a fresh database per run, a syntax error as a failed query (`@node-service`). - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`, after this branch's security fixes; this is a static listing, not a Docker run. A combined final run against an image built from this branch (tag `secfix-combined-e2e`) has since confirmed pass/fail for every scenario named in the per-defect rows below: 693/696 default tests passed, the 3 failures pre-existing or unrelated suite drift (documented in their own rows below)): -default **713 tests in 106 files**; with `E2E_INCLUDE_QUARANTINE=1` **726 in 107**; with `E2E_INCLUDE_SUPERADMIN=1` **718 in 106**; with both of those **731 in 107**; -with `E2E_INCLUDE_INSERT_ALL=1` **825 in 107**; with all three opt-in variables **843 in 108** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: +default **719 tests in 107 files**; with `E2E_INCLUDE_QUARANTINE=1` **732 in 108**; with `E2E_INCLUDE_SUPERADMIN=1` **724 in 107**; with both of those **737 in 108**; +with `E2E_INCLUDE_INSERT_ALL=1` **831 in 108**; with all three opt-in variables **849 in 109** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 17 (the 14 unit tests of `foundation/node-plugins.spec.ts` and D3a to D3c; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 23 (the 15 unit tests of `foundation/node-plugins.spec.ts`, D3a to D3c and D4a to D4e; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -304,7 +305,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | editor/js-query.spec.ts | a JS query written in the editor runs | @core | 1 | | editor/drop-size.spec.ts | a component dropped right after ready has width above 0 (D-5) | @quarantine | 1 | -### datasource (13) +### datasource (18) | File | Proves | Tags | Tests | |---|---|---|---| @@ -312,6 +313,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/table.spec.ts | D2: editor-built table bound to a query; published table; sort, page, select, filter, notes edit/save | @core @slow | 3 | | datasource/query-feeds-components.spec.ts | D1: query feeds text and table, owner-scoped writes re-read, chart renders | @core @slow @npm | 1 | | datasource/notes-queries.spec.ts | unit tests of the query builders | none | 4 | +| datasource/plugin-duckdb.spec.ts | D4: DuckDB through the app container, database `:memory:`, no network. D4a a query answers rows, D4b the published view shows the result after a click, D4c a BIGINT and a HUGEINT arrive as exact strings, D4d each run is a fresh database (a table created by one run is gone in the next), D4e a syntax error is a failed query (`success: false`, `queryCode: FAILED`; the field `code` is 1 either way). D4a to D4c assert the measured row shape, keys are the column positions (NSD-3 candidate) | @node-service | 5 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -456,13 +458,13 @@ first makes sure some admin exists (accepting both answers), so none depends on SEC-R09d (D-38) left the quarantine: the check took the workspace of the first id of a `HashSet`; each id is now decided in its own workspace (Java unit and MongoDB integration tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)). Accounting of the earlier 3.0.0 run `E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --workers=4 --reporter=list --grep "@quarantine" tests/security` (measured before the `@superadmin` tag existed and before the reassessment, so it listed 44 tests, 19 of which have since left the quarantine): 44 listed, 43 failed, 1 passed (SEC-R09d); the two quarantined tests of `foundation/security-helpers.spec.ts` are outside that folder. -### foundation (278 default, 281 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) +### foundation (279 default, 282 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) | File | Proves | Tags | Tests | |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server | @node-service | 14 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb recordings (type, action, no session value) | @node-service | 15 | | foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources) | none | 27 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | @@ -502,6 +504,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | CD-7 | `setIn` with a bad path or on a scalar fails silently (query ends as success) | `logic/temporary-state.spec.ts` asserts today's behaviour, annotation `{type:"defect", description:"CD-7"}`, default run | | CD-8 | `transfer` list titles are in the wrong order: confirmed by code (`titles={[targetTitle, sourceTitle]}`, 2026-11-22 reading) | conditional `defect` annotation in `components/choices.spec.ts` (the annotation still says candidate) | | CD-9 | an icon switched from a name to an image URL keeps the old icon: confirmed (failed 3 of 3 on 3.0.1-e2e; code: the old icon is cached under the new URL and `undefined === undefined` keeps it) | `components/displays.spec.ts`, `@quarantine`, `defect` annotation (still named candidate there) | +| NSD-3 candidate | the DuckDB plugin answers rows keyed by the column position, not the column name (`SELECT 42 AS answer` arrives as `{"0": 42}`): `getRows()` answers arrays and `serializeBigInts` copies `Object.entries(row)`; measured on 3.0.0-e2e and 3.0.1-e2e. An app cannot read `row.answer`. The id is provisional until the owner assigns one | `datasource/plugin-duckdb.spec.ts` D4a to D4c assert today's keys (characterisation, default run), annotation `{type:"defect", description:"NSD-3 candidate"}`; they change when the plugin keys rows by name | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/fixtures/dsl/plugins/duckdb/duckdbDatasource.json b/e2e/fixtures/dsl/plugins/duckdb/duckdbDatasource.json new file mode 100644 index 0000000000..203737d9d1 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/duckdb/duckdbDatasource.json @@ -0,0 +1,10 @@ +{ + "name": "duckdb", + "type": "duckdb", + "datasourceConfig": { + "databaseFile": ":memory:", + "options": "{\"access_mode\": \"READ_WRITE\",\"max_memory\": \"512MB\",\"threads\": \"4\"}", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} diff --git a/e2e/fixtures/dsl/plugins/duckdb/duckdbQuery.json b/e2e/fixtures/dsl/plugins/duckdb/duckdbQuery.json new file mode 100644 index 0000000000..1a4a3a98be --- /dev/null +++ b/e2e/fixtures/dsl/plugins/duckdb/duckdbQuery.json @@ -0,0 +1,15 @@ +{ + "compType": "duckdb", + "comp": { + "actionName": "Query", + "action": { + "queryString": "SELECT 1" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/tests/datasource/plugin-duckdb.spec.ts b/e2e/tests/datasource/plugin-duckdb.spec.ts new file mode 100644 index 0000000000..55a30b9883 --- /dev/null +++ b/e2e/tests/datasource/plugin-duckdb.spec.ts @@ -0,0 +1,172 @@ +import { randomBytes } from "node:crypto"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, TAGS } from "../../src/constants"; +import { appDsl, button, nodePluginQuery, stackItems } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { boundText, boundTextTestId, openSeededView } from "../../src/components/scenario"; +import { expect, test } from "../../src/fixtures"; + +/** + * D4: the DuckDB plugin of node-service (`server/node-service/src/plugins/duckdb/index.ts`), run through the app container + * with no network: the data source is the recorded form body (database file `:memory:`, the form's default options), every + * query runs against a database that exists only for that one run. + * + * Limits of this file: no `INSTALL`/`LOAD` statement, no URL or file path in any SQL and no `read_*` table function. DuckDB can + * autoload extensions from a download host, and a file path would write into the app container that every test shares. + * + * Measured shape (images `3.0.0-e2e` and `3.0.1-e2e`): the plugin reads the rows with `getRows()`, which answers each row as an + * array, and `serializeBigInts` copies `Object.entries(row)`. A row therefore reaches the app keyed by the column POSITION + * (`{ "0": 42, "1": "e2e-..." }`), not by the column name. The tests below assert that measured shape, so they carry the + * `defect` annotation `COLUMN_KEY_DEFECT`; once rows are keyed by column name they fail and are rewritten to the names. + */ + +/** Candidate defect: rows are keyed by the column's position, so `SELECT 42 AS answer` cannot be read as `row.answer` in an app. */ +const COLUMN_KEY_DEFECT = { type: "defect", description: "NSD-3 candidate" } as const; +const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; +const COLUMN_KEY_DETAILS = { annotation: COLUMN_KEY_DEFECT }; + +const HTTP_OK = 200; +/** `QueryResultView.queryCode` of a failed query (`api/query/view/QueryResultView.java`); the field `code` is `1` whether or not the query succeeded. */ +const QUERY_CODE_FAILED = "FAILED"; +/** `queryCode` of a query that succeeded. */ +const QUERY_CODE_OK = "OK"; +const MARKER_BYTES = 4; + +/** The position keys of the first two columns of a row. */ +const FIRST_COLUMN = "0"; +const SECOND_COLUMN = "1"; + +/** The largest HUGEINT (2^127 - 1), far beyond the BIGINT range; a JavaScript number could not hold it. */ +const HUGEINT_VALUE = "170141183460469231731687303715884105727"; +const BIGINT_SQL = `SELECT 9007199254740993::BIGINT AS big, ${HUGEINT_VALUE}::HUGEINT AS huge`; +/** 2^53 + 1: the first integer a JavaScript number cannot hold, so a `number` would come back as 9007199254740992. */ +const BIGINT_VALUE = "9007199254740993"; +const CREATE_TABLE_SQL = "CREATE TABLE t AS SELECT 1 AS x"; +const SELECT_TABLE_SQL = "SELECT x FROM t"; +const SYNTAX_ERROR_SQL = "SELEC 1"; + +const BUTTON_TEST_ID = "e2e-duckdb-run"; +const RESULT_NAME = "label"; +const QUERY_ID = "q1"; +const QUERY_NAME = "q"; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +/** A DuckDB data source from the recording (the recorded `:memory:` file and options); returns its id. */ +async function duckdbDatasource(page: Page, apiUser: RegisteredUser): Promise { + return createNodePluginDatasource(page.request, { orgId: apiUser.orgId, recorded: recordedPluginDatasource("duckdb"), config: {} }); +} + +/** A saved app with one manual query per entry of `sqlByQueryId`, on a new DuckDB data source (not published: the draft runs with `viewMode: false`). */ +async function duckdbApp(page: Page, apiUser: RegisteredUser, sqlByQueryId: Record): Promise<{ appId: string }> { + const datasourceId = await duckdbDatasource(page, apiUser); + const queries = Object.entries(sqlByQueryId).map(([id, sql]) => + nodePluginQuery({ id, name: id, datasourceId, recorded: recordedPluginQuery("duckdb"), action: { queryString: sql } }), + ); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: "e2e-duckdb", dsl: appDsl([], { queries }) }); + return { appId }; +} + +async function runDraft(page: Page, appId: string, queryId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId, viewMode: false }); +} + +test.describe("DuckDB data source", NODE_SERVICE_DETAILS, () => { + test("D4a: a DuckDB query answers rows", COLUMN_KEY_DETAILS, async ({ page, apiUser }) => { + const marker = uniqueMarker(); + const { appId } = await duckdbApp(page, apiUser, { [QUERY_ID]: `SELECT 42 AS answer, 'e2e-' || '${marker}' AS label` }); + + const answer = await runDraft(page, appId, QUERY_ID); + + expect({ status: answer.status, code: answer.code }, "the query ran").toEqual({ status: HTTP_OK, code: API_OK }); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); + // An INTEGER column reaches the app as a JSON number; the keys are the column positions (NSD-3 candidate, see the file comment). + expect(envelopeOf(answer).data, "the rows, keyed by column position").toEqual([{ [FIRST_COLUMN]: 42, [SECOND_COLUMN]: `e2e-${marker}` }]); + }); + + test("D4b: the published view shows the DuckDB result after a click", COLUMN_KEY_DETAILS, async ({ page, apiUser }) => { + const marker = uniqueMarker(); + const datasourceId = await duckdbDatasource(page, apiUser); + // The text reads the second column by its position key (NSD-3 candidate); before the first run `q.data` is not a list. + const expression = `{{${QUERY_NAME}.data ? ${QUERY_NAME}.data[0]["${SECOND_COLUMN}"] : ""}}`; + const view = await openSeededView( + page, + apiUser.orgId, + "e2e-duckdb-view", + stackItems([ + button({ id: "b1", name: "button1", text: "Run", testId: BUTTON_TEST_ID, onClickQuery: QUERY_NAME }), + boundText({ id: "t1", name: RESULT_NAME, expression }), + ]), + { + queries: [ + nodePluginQuery({ + id: QUERY_ID, + name: QUERY_NAME, + datasourceId, + recorded: recordedPluginQuery("duckdb"), + action: { queryString: `SELECT 42 AS answer, 'e2e-' || '${marker}' AS label` }, + }), + ], + }, + ); + + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "before the click the text is empty").toHaveText(""); + await view.buttonByTestId(BUTTON_TEST_ID).click(); + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "after the click the text shows the DuckDB label").toHaveText(`e2e-${marker}`); + }); + + test("D4c: BIGINT and HUGEINT columns arrive as strings without precision loss", COLUMN_KEY_DETAILS, async ({ page, apiUser }) => { + const { appId } = await duckdbApp(page, apiUser, { [QUERY_ID]: BIGINT_SQL }); + + const answer = await runDraft(page, appId, QUERY_ID); + + expect({ status: answer.status, code: answer.code }, "the query ran").toEqual({ status: HTTP_OK, code: API_OK }); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); + // `serializeBigInts` turns a `bigint` into a string (designed behaviour), a HUGEINT included (measured); the keys are the column positions (NSD-3 candidate). + expect(envelopeOf(answer).data, "the BIGINT and the HUGEINT as exact strings").toEqual([{ [FIRST_COLUMN]: BIGINT_VALUE, [SECOND_COLUMN]: HUGEINT_VALUE }]); + }); + + test("D4d: each run is a fresh in-memory database", async ({ page, apiUser }) => { + const { appId } = await duckdbApp(page, apiUser, { create: CREATE_TABLE_SQL, read: SELECT_TABLE_SQL }); + + const created = await runDraft(page, appId, "create"); + expect({ status: created.status, code: created.code }, "the CREATE TABLE ran").toEqual({ status: HTTP_OK, code: API_OK }); + expect(envelopeOf(created).success, "the CREATE TABLE succeeded (positive control)").toBe(true); + expect(envelopeOf(created).queryCode, "the CREATE TABLE query code").toBe(QUERY_CODE_OK); + + const read = await runDraft(page, appId, "read"); + expect(envelopeOf(read).success, "the second run does not see the table").toBe(false); + expect(envelopeOf(read).queryCode, "the second run failed").toBe(QUERY_CODE_FAILED); + expect(envelopeOf(read).message, "the error names the table").toContain("Table with name t does not exist"); + }); + + test("D4e: a syntax error is a failed query", async ({ page, apiUser }) => { + const { appId } = await duckdbApp(page, apiUser, { [QUERY_ID]: SYNTAX_ERROR_SQL }); + + const answer = await runDraft(page, appId, QUERY_ID); + + // `code` is `1` for every query answer, success or not: the outcome is `success` and `queryCode`. + expect(answer.status, "the request itself is answered").toBe(HTTP_OK); + expect(envelopeOf(answer).success, "the query failed").toBe(false); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_FAILED); + expect(envelopeOf(answer).message, "the message names the syntax error").toContain(`syntax error at or near "SELEC"`); + expect(envelopeOf(answer).data, "no rows").toBeNull(); + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index 8c491f74de..fa0f2c18c7 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -1,11 +1,14 @@ +import { readFileSync } from "node:fs"; import { createServer, type IncomingMessage, type Server } from "node:http"; import type { AddressInfo } from "node:net"; +import { join } from "node:path"; import { expect, test } from "@playwright/test"; import { createNodePluginDatasource, LowcoderApiError, nodePluginDatasourceBody, pluginDynamicConfigRaw, testDatasourceRaw } from "../../src/api/client"; import { API_OK, API_PATHS, orgDatasourceTypesPath, TAGS } from "../../src/constants"; import { nodePluginQuery } from "../../src/dsl/builders"; import { parsePluginRecording, + RECORDED_PLUGINS_DIR, RecordedFixtureError, recordedPluginDatasource, recordedPluginQuery, @@ -111,6 +114,23 @@ test.describe("node-service data source helpers", { tag: [TAGS.NODE_SERVICE] }, expect(nodePluginDatasourceBody(recorded, { orgId: "org-1", name: "renamed", config: {} })).toMatchObject({ name: "renamed" }); }); + test("the duckdb recordings are the form's body and the editor's saved query, with no value of the recording session", () => { + const datasource = recordedPluginDatasource("duckdb"); + const query = recordedPluginQuery("duckdb"); + expect(datasource.type, "the data source type").toBe("duckdb"); + expect(datasource.datasourceConfig, "the form's defaults: an in-memory database and the options JSON").toMatchObject({ databaseFile: ":memory:" }); + expect(() => JSON.parse(String(datasource.datasourceConfig.options)), "the options are JSON text").not.toThrow(); + expect(query.compType, "the query type").toBe("duckdb"); + expect(query.comp.actionName, "the only action of the plugin").toBe("Query"); + expect(Object.keys(query.comp.action as Record), "the SQL parameter").toEqual(["queryString"]); + expect(Object.keys(query), "only what the builder keeps").toEqual(["compType", "comp"]); + expect(Object.keys(datasource), "no workspace id").toEqual(["name", "type", "datasourceConfig"]); + const text = ["duckdbDatasource.json", "duckdbQuery.json"].map((file) => readFileSync(join(RECORDED_PLUGINS_DIR, "duckdb", file), "utf8")).join("\n"); + expect(text, "a 24-hex id (workspace, data source, query)").not.toMatch(/\b[0-9a-f]{24}\b/); + expect(text, "an ISO timestamp").not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/); + expect(text, "an epoch of 10 digits or more (the saved query's order)").not.toMatch(/\b\d{10,}\b/); + }); + test("the recorded placeholder host is one that never resolves", () => { expect(new URL(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL).hostname.endsWith(".invalid")).toBe(true); }); From 3d1845eeb22022530182e5918116fd9fa6ab6371 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 15:52:19 +0100 Subject: [PATCH 07/20] test: add Turso and Slack node-service data source scenarios Adds recorded Turso and Slack data source and query fixtures and scenarios that point each plugin at the run's echo target: the Turso pipeline request shape and bearer token, raw result passthrough, a server error, an error result (the message currently prints as [object Object], annotated as a defect candidate), a bound component after a click, and the Slack webhook form payload. A unit test covers the new recordings. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 2 +- e2e/README.md | 17 +- .../dsl/plugins/slack/slackDatasource.json | 9 + .../dsl/plugins/slack/slackQuery.json | 16 ++ .../dsl/plugins/turso/tursoDatasource.json | 10 + .../dsl/plugins/turso/tursoQuery.json | 16 ++ .../datasource/plugin-turso-slack.spec.ts | 249 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 25 ++ 8 files changed, 336 insertions(+), 8 deletions(-) create mode 100644 e2e/fixtures/dsl/plugins/slack/slackDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/slack/slackQuery.json create mode 100644 e2e/fixtures/dsl/plugins/turso/tursoDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/turso/tursoQuery.json create mode 100644 e2e/tests/datasource/plugin-turso-slack.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index e7f69c7fbc..bedf073974 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,7 +129,7 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). diff --git a/e2e/README.md b/e2e/README.md index d4f8f2a934..76d7131068 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins only DuckDB runs queries, D4, embedded in the app container with no network; no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso and Slack run queries, D5, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -209,7 +209,7 @@ e2e/ fixtures/sql/init.sql PostgreSQL data: items, products, notes fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb` + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack` src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -248,15 +248,16 @@ Test titles carry these ids. - D1 a PostgreSQL query feeds a text and a table, write queries re-read; D2 table with query data (sort, page, filter, edit). - D3 the plugin catalogue of node-service: the image serves exactly the registered node plugins, each definition has a form and a query config, the Java-native types carry no definition (`@node-service`; the catalogue only, no plugin query runs). - D4 the DuckDB plugin of node-service, run in the app container with an in-memory database and no network: rows, the published view after a click, a BIGINT as a string, a fresh database per run, a syntax error as a failed query (`@node-service`). +- D5 the Turso and Slack plugins of node-service against the echo sidecar: a Turso query sends one Hrana pipeline and answers its rows, `includeRaw` answers values and raw, a non-OK answer and an `error` result fail the query (the latter prints `[object Object]`, NSD-1 candidate), the published view after a click; a Slack query posts the form payload to the webhook (`@node-service`; the request shape and the answer's path into the app, not the vendor service). - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`, after this branch's security fixes; this is a static listing, not a Docker run. A combined final run against an image built from this branch (tag `secfix-combined-e2e`) has since confirmed pass/fail for every scenario named in the per-defect rows below: 693/696 default tests passed, the 3 failures pre-existing or unrelated suite drift (documented in their own rows below)): -default **719 tests in 107 files**; with `E2E_INCLUDE_QUARANTINE=1` **732 in 108**; with `E2E_INCLUDE_SUPERADMIN=1` **724 in 107**; with both of those **737 in 108**; -with `E2E_INCLUDE_INSERT_ALL=1` **831 in 108**; with all three opt-in variables **849 in 109** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: +default **726 tests in 108 files**; with `E2E_INCLUDE_QUARANTINE=1` **739 in 109**; with `E2E_INCLUDE_SUPERADMIN=1` **731 in 108**; with both of those **744 in 109**; +with `E2E_INCLUDE_INSERT_ALL=1` **838 in 109**; with all three opt-in variables **856 in 110** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 23 (the 15 unit tests of `foundation/node-plugins.spec.ts`, D3a to D3c and D4a to D4e; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 30 (the 16 unit tests of `foundation/node-plugins.spec.ts`, D3a to D3c, D4a to D4e and D5a to D5f; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -305,7 +306,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | editor/js-query.spec.ts | a JS query written in the editor runs | @core | 1 | | editor/drop-size.spec.ts | a component dropped right after ready has width above 0 (D-5) | @quarantine | 1 | -### datasource (18) +### datasource (19) | File | Proves | Tags | Tests | |---|---|---|---| @@ -314,6 +315,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/query-feeds-components.spec.ts | D1: query feeds text and table, owner-scoped writes re-read, chart renders | @core @slow @npm | 1 | | datasource/notes-queries.spec.ts | unit tests of the query builders | none | 4 | | datasource/plugin-duckdb.spec.ts | D4: DuckDB through the app container, database `:memory:`, no network. D4a a query answers rows, D4b the published view shows the result after a click, D4c a BIGINT and a HUGEINT arrive as exact strings, D4d each run is a fresh database (a table created by one run is gone in the next), D4e a syntax error is a failed query (`success: false`, `queryCode: FAILED`; the field `code` is 1 either way). D4a to D4c assert the measured row shape, keys are the column positions (NSD-3 candidate) | @node-service | 5 | +| datasource/plugin-turso-slack.spec.ts | D5: Turso and Slack against the echo sidecar (the data source URL is the test's own echo target). D5a a Turso query sends one POST of `{requests: [execute, close]}` to `/v2/pipeline` with `Authorization: Bearer ` and answers the rows keyed by column name (an `integer` cell as a number), D5b `includeRaw` answers `{values, raw}`, D5c a 500 answer fails the query (`Endpoint returned 500`), D5d an `error` result fails the query with `Cannot parse result, received error: [object Object]` (NSD-1 candidate: the server's message is lost), D5e the published view shows the row after a click, D5f a Slack query posts `payload=` as `application/x-www-form-urlencoded;charset=UTF-8` to the webhook path and answers the webhook's text. Not covered: the `libsql://` rewrite (the echo does not speak TLS) | @node-service | 6 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -464,7 +466,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb recordings (type, action, no session value) | @node-service | 15 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso and slack recordings (type, action, placeholder host, no session value) | @node-service | 16 | | foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources) | none | 27 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | @@ -504,6 +506,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | CD-7 | `setIn` with a bad path or on a scalar fails silently (query ends as success) | `logic/temporary-state.spec.ts` asserts today's behaviour, annotation `{type:"defect", description:"CD-7"}`, default run | | CD-8 | `transfer` list titles are in the wrong order: confirmed by code (`titles={[targetTitle, sourceTitle]}`, 2026-11-22 reading) | conditional `defect` annotation in `components/choices.spec.ts` (the annotation still says candidate) | | CD-9 | an icon switched from a name to an image URL keeps the old icon: confirmed (failed 3 of 3 on 3.0.1-e2e; code: the old icon is cached under the new URL and `undefined === undefined` keeps it) | `components/displays.spec.ts`, `@quarantine`, `defect` annotation (still named candidate there) | +| NSD-1 candidate | the Turso plugin prints a pipeline `error` result as `${result.error}`, an object: a failed statement reaches the app as `Cannot parse result, received error: [object Object]` and the server's own message is lost; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-turso-slack.spec.ts` D5d asserts today's message (characterisation, default run), annotation `{type:"defect", description:"NSD-1 candidate"}`; it changes when the plugin prints the message | | NSD-3 candidate | the DuckDB plugin answers rows keyed by the column position, not the column name (`SELECT 42 AS answer` arrives as `{"0": 42}`): `getRows()` answers arrays and `serializeBigInts` copies `Object.entries(row)`; measured on 3.0.0-e2e and 3.0.1-e2e. An app cannot read `row.answer`. The id is provisional until the owner assigns one | `datasource/plugin-duckdb.spec.ts` D4a to D4c assert today's keys (characterisation, default run), annotation `{type:"defect", description:"NSD-3 candidate"}`; they change when the plugin keys rows by name | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | diff --git a/e2e/fixtures/dsl/plugins/slack/slackDatasource.json b/e2e/fixtures/dsl/plugins/slack/slackDatasource.json new file mode 100644 index 0000000000..9389e4bef4 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/slack/slackDatasource.json @@ -0,0 +1,9 @@ +{ + "name": "slack", + "type": "slack", + "datasourceConfig": { + "webhookURL": "http://placeholder.invalid", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} diff --git a/e2e/fixtures/dsl/plugins/slack/slackQuery.json b/e2e/fixtures/dsl/plugins/slack/slackQuery.json new file mode 100644 index 0000000000..09ed9c989c --- /dev/null +++ b/e2e/fixtures/dsl/plugins/slack/slackQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "slack", + "comp": { + "actionName": "Query", + "action": { + "message": "", + "channel": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/turso/tursoDatasource.json b/e2e/fixtures/dsl/plugins/turso/tursoDatasource.json new file mode 100644 index 0000000000..961574e58d --- /dev/null +++ b/e2e/fixtures/dsl/plugins/turso/tursoDatasource.json @@ -0,0 +1,10 @@ +{ + "name": "turso", + "type": "turso", + "datasourceConfig": { + "url": "http://placeholder.invalid", + "token": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} diff --git a/e2e/fixtures/dsl/plugins/turso/tursoQuery.json b/e2e/fixtures/dsl/plugins/turso/tursoQuery.json new file mode 100644 index 0000000000..ec76688b83 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/turso/tursoQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "turso", + "comp": { + "actionName": "Query", + "action": { + "queryString": "SELECT 1", + "includeRaw": false + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/tests/datasource/plugin-turso-slack.spec.ts b/e2e/tests/datasource/plugin-turso-slack.spec.ts new file mode 100644 index 0000000000..418d5beafe --- /dev/null +++ b/e2e/tests/datasource/plugin-turso-slack.spec.ts @@ -0,0 +1,249 @@ +import { randomBytes } from "node:crypto"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, TAGS } from "../../src/constants"; +import { appDsl, button, nodePluginQuery, stackItems } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { boundText, boundTextTestId, openSeededView } from "../../src/components/scenario"; +import { expect, test } from "../../src/fixtures"; +import type { EchoRecord, EchoTarget } from "../../src/security/echo"; + +/** + * D5: the Turso and Slack plugins of node-service (`server/node-service/src/plugins/turso/index.ts`, `slack/run.ts`), which + * talk plain HTTP to a configurable URL. The data source URL is the test's own target on the echo sidecar, so the tests prove + * the request the plugin builds and the path of the canned answer into the app. They are NOT a fidelity test of Turso or Slack. + * + * Not covered: the `libsql://` to `https://` rewrite of the Turso URL (the echo does not speak TLS). + */ +const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; + +/** Candidate defect: an `error` result of the pipeline is printed as `${result.error}` (an object), so the server's own message never reaches the app. */ +const ERROR_TEXT_DEFECT = { type: "defect", description: "NSD-1 candidate" } as const; +const ERROR_TEXT_DETAILS = { annotation: ERROR_TEXT_DEFECT }; +/** The message of the canned error result. */ +const ERROR_MESSAGE = "e2e-boom"; +/** What the plugin prints for it (measured on the images `3.0.0-e2e` and `3.0.1-e2e`): the object is printed as `[object Object]`. */ +const MEASURED_ERROR_TEXT = "Cannot parse result, received error: [object Object]"; + +/** The route the Turso plugin appends to the data source URL (Hrana over HTTP, pipeline endpoint). */ +const PIPELINE_PATH = "/v2/pipeline"; +/** The path below the target that the Slack data source URL points at. */ +const HOOK_PATH = "/hook"; +const HTTP_OK = 200; +const HTTP_SERVER_ERROR = 500; +const QUERY_CODE_OK = "OK"; +const QUERY_CODE_FAILED = "FAILED"; +const MARKER_BYTES = 4; +const JSON_CONTENT_TYPE = "application/json"; +const TEXT_CONTENT_TYPE = "text/plain"; +/** The content type node-fetch sets for a `URLSearchParams` body (measured on the images `3.0.0-e2e`: the charset suffix is part of it). */ +const FORM_CONTENT_TYPE = "application/x-www-form-urlencoded;charset=UTF-8"; +const SLACK_ANSWER = "ok"; + +const BUTTON_TEST_ID = "e2e-turso-run"; +const RESULT_NAME = "label"; +const SUCCESS_NAME = "succeeded"; +const QUERY_ID = "q1"; +const QUERY_NAME = "q"; + +const ROW_ID = 1; +const ROW_NAME = "alpha"; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +/** The `result` of the canned `execute` (columns `id` INTEGER and `name` TEXT, one row): `includeRaw` hands it to the app unchanged. */ +const EXECUTE_RESULT = { + cols: [ + { name: "id", decltype: "INTEGER" }, + { name: "name", decltype: "TEXT" }, + ], + rows: [[{ type: "integer", value: String(ROW_ID) }, { type: "text", value: ROW_NAME }]], + affected_row_count: 0, + last_insert_rowid: null, + replication_index: null, + rows_read: 1, + rows_written: 0, + query_duration_ms: 0, +}; + +/** The Hrana answer of a pipeline with one `execute` and its `close`. */ +function pipelineAnswer(): string { + return JSON.stringify({ + baton: null, + base_url: null, + results: [ + { type: "ok", response: { type: "execute", result: EXECUTE_RESULT } }, + { type: "ok", response: { type: "close" } }, + ], + }); +} + +async function cannedPipeline(echo: EchoTarget, answer: { status: number; body: string; contentType?: string } = { status: HTTP_OK, body: pipelineAnswer() }): Promise { + await echo.answer(PIPELINE_PATH, { contentType: JSON_CONTENT_TYPE, ...answer }); +} + +/** A Turso data source from the recording, pointed at the echo target; returns its id. */ +async function tursoDatasource(page: Page, apiUser: RegisteredUser, echo: EchoTarget, token: string): Promise { + return createNodePluginDatasource(page.request, { + orgId: apiUser.orgId, + recorded: recordedPluginDatasource("turso"), + config: { url: echo.url, token }, + }); +} + +/** A saved app with one manual Turso query (not published: the draft runs with `viewMode: false`). */ +async function tursoApp(page: Page, apiUser: RegisteredUser, echo: EchoTarget, token: string, action: Record): Promise<{ appId: string }> { + const datasourceId = await tursoDatasource(page, apiUser, echo, token); + const query = nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery("turso"), action }); + return createApp(page.request, { orgId: apiUser.orgId, name: "e2e-turso", dsl: appDsl([], { queries: [query] }) }); +} + +async function runDraft(page: Page, appId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId: QUERY_ID, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +function onlyRecord(records: EchoRecord[]): EchoRecord { + expect(records, "the echo received exactly one request").toHaveLength(1); + return records[0] as EchoRecord; +} + +test.describe("Turso data source against the echo", NODE_SERVICE_DETAILS, () => { + test("D5a: a Turso query sends one Hrana pipeline and answers its rows", async ({ page, apiUser, echo }) => { + const token = `e2e-token-${uniqueMarker()}`; + const sql = `SELECT id, name FROM t WHERE tag = 'e2e-${uniqueMarker()}'`; + await cannedPipeline(echo); + const { appId } = await tursoApp(page, apiUser, echo, token, { queryString: sql }); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); + const record = onlyRecord(await echo.received()); + expect(record.method, "the request method").toBe("POST"); + expect(record.path, "the request path").toBe(`${echo.path}${PIPELINE_PATH}`); + expect(record.headers.authorization, "the bearer token of the data source").toBe(`Bearer ${token}`); + expect(JSON.parse(record.body), "the complete pipeline: the execute of the SQL, then the close, nothing else").toEqual({ + requests: [{ type: "execute", stmt: { sql } }, { type: "close" }], + }); + // an `integer` cell becomes a number, a `text` cell stays text; the keys are the column names + expect(envelopeOf(answer).data, "the rows").toEqual([{ id: ROW_ID, name: ROW_NAME }]); + }); + + test("D5b: includeRaw answers the values and the raw result", async ({ page, apiUser, echo }) => { + await cannedPipeline(echo); + const { appId } = await tursoApp(page, apiUser, echo, "e2e-token", { queryString: "SELECT 1", includeRaw: true }); + + const answer = await runDraft(page, appId); + + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect((await echo.received()).length, "positive control: the request did reach the echo").toBe(1); + const data = envelopeOf(answer).data as { values?: unknown; raw?: unknown }; + expect(Object.keys(data).sort(), "both keys are present").toEqual(["raw", "values"]); + expect(data.values, "the values").toEqual([{ id: ROW_ID, name: ROW_NAME }]); + expect(data.raw, "the whole raw result, as the server sent it").toEqual(EXECUTE_RESULT); + }); + + test("D5c: a non-OK pipeline answer fails the query", async ({ page, apiUser, echo }) => { + await cannedPipeline(echo, { status: HTTP_SERVER_ERROR, body: "{}" }); + const { appId } = await tursoApp(page, apiUser, echo, "e2e-token", { queryString: "SELECT 1" }); + + const answer = await runDraft(page, appId); + + expect(answer.status, "the request itself is answered").toBe(HTTP_OK); + expect(envelopeOf(answer).success, "the query failed").toBe(false); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_FAILED); + expect(envelopeOf(answer).message, "the message names the status").toContain(`Endpoint returned ${HTTP_SERVER_ERROR}`); + expect((await echo.received()).length, "positive control: the request did reach the echo").toBe(1); + }); + + test("D5d: an error result fails the query", ERROR_TEXT_DETAILS, async ({ page, apiUser, echo }) => { + await cannedPipeline(echo, { status: HTTP_OK, body: JSON.stringify({ baton: null, base_url: null, results: [{ type: "error", error: { message: ERROR_MESSAGE } }, { type: "ok", response: { type: "close" } }] }) }); + const { appId } = await tursoApp(page, apiUser, echo, "e2e-token", { queryString: "SELECT 1" }); + + const answer = await runDraft(page, appId); + + expect(answer.status, "the request itself is answered").toBe(HTTP_OK); + expect(envelopeOf(answer).success, "the query failed").toBe(false); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_FAILED); + // The plugin prints `result.error`, which is an object: the server's message is lost (NSD-1 candidate, see ERROR_TEXT_DEFECT). + expect(envelopeOf(answer).message, "the measured message").toBe(MEASURED_ERROR_TEXT); + expect((await echo.received()).length, "positive control: the request did reach the echo").toBe(1); + }); + + test("D5e: the published view shows a Turso row after a click", async ({ page, apiUser, echo }) => { + await cannedPipeline(echo); + const datasourceId = await tursoDatasource(page, apiUser, echo, "e2e-token"); + // before the first run `q.data` is not a list + const expression = `{{${QUERY_NAME}.data ? ${QUERY_NAME}.data[0].name : ""}}`; + const view = await openSeededView( + page, + apiUser.orgId, + "e2e-turso-view", + stackItems([ + button({ id: "b1", name: "button1", text: "Run", testId: BUTTON_TEST_ID, onClickQuery: QUERY_NAME }), + boundText({ id: "t1", name: RESULT_NAME, expression }), + // `success` is an exposed value of every query (`q.success`); it also reads `true` before the first run (measured), so only the state after the click proves anything + boundText({ id: "t2", name: SUCCESS_NAME, expression: `{{String(${QUERY_NAME}.success)}}` }), + ]), + { queries: [nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery("turso"), action: { queryString: "SELECT 1" } })] }, + ); + + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "before the click the text is empty").toHaveText(""); + expect(await echo.received(), "before the click the echo holds nothing of this test").toEqual([]); + await view.buttonByTestId(BUTTON_TEST_ID).click(); + await expect(view.byTestId(boundTextTestId(SUCCESS_NAME)), "after the click the query succeeded").toHaveText("true"); + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "after the click the text shows the Turso row").toHaveText(ROW_NAME); + expect((await echo.received()).length, "the click sent one request to the echo").toBe(1); + }); +}); + +test.describe("Slack data source against the echo", NODE_SERVICE_DETAILS, () => { + test("D5f: a Slack query posts the payload to the webhook", async ({ page, apiUser, echo }) => { + const id = uniqueMarker(); + const channel = `#e2e-${id}`; + const message = `e2e-message-${id}`; + await echo.answer(HOOK_PATH, { status: HTTP_OK, contentType: TEXT_CONTENT_TYPE, body: SLACK_ANSWER }); + const datasourceId = await createNodePluginDatasource(page.request, { + orgId: apiUser.orgId, + recorded: recordedPluginDatasource("slack"), + config: { webhookURL: `${echo.url}${HOOK_PATH}` }, + }); + const query = nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery("slack"), action: { message, channel } }); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: "e2e-slack", dsl: appDsl([], { queries: [query] }) }); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); + const record = onlyRecord(await echo.received()); + expect(record.method, "the request method").toBe("POST"); + expect(record.path, "the request path").toBe(`${echo.path}${HOOK_PATH}`); + expect(String(record.headers["content-type"]), "the body is a form").toBe(FORM_CONTENT_TYPE); + const payload = new URLSearchParams(record.body).get("payload"); + expect(JSON.parse(payload ?? "null"), "the decoded payload").toEqual({ channel, text: message }); + expect(envelopeOf(answer).data, "the answer is the webhook's text").toBe(SLACK_ANSWER); + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index fa0f2c18c7..29ea57a6cd 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -131,6 +131,31 @@ test.describe("node-service data source helpers", { tag: [TAGS.NODE_SERVICE] }, expect(text, "an epoch of 10 digits or more (the saved query's order)").not.toMatch(/\b\d{10,}\b/); }); + test("the turso and slack recordings are the form's body and the editor's saved query, with no value of the recording session", () => { + const expectations = [ + { id: "turso", config: ["url", "token"], action: ["queryString", "includeRaw"] }, + { id: "slack", config: ["webhookURL"], action: ["message", "channel"] }, + ]; + for (const { id, config, action } of expectations) { + const datasource = recordedPluginDatasource(id); + const query = recordedPluginQuery(id); + expect(datasource.type, `${id}: the data source type`).toBe(id); + expect(Object.keys(datasource.datasourceConfig), `${id}: the form fields`).toEqual(expect.arrayContaining(config)); + for (const key of config.filter((name) => name === "url" || name === "webhookURL")) { + expect(datasource.datasourceConfig[key], `${id}: the placeholder host`).toBe(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL); + } + expect(query.compType, `${id}: the query type`).toBe(id); + expect(query.comp.actionName, `${id}: the only action of the plugin`).toBe("Query"); + expect(Object.keys(query.comp.action as Record), `${id}: the action's parameters`).toEqual(action); + expect(Object.keys(query), `${id}: only what the builder keeps`).toEqual(["compType", "comp"]); + expect(Object.keys(datasource), `${id}: no workspace id`).toEqual(["name", "type", "datasourceConfig"]); + const text = [`${id}Datasource.json`, `${id}Query.json`].map((file) => readFileSync(join(RECORDED_PLUGINS_DIR, id, file), "utf8")).join("\n"); + expect(text, `${id}: a 24-hex id`).not.toMatch(/\b[0-9a-f]{24}\b/); + expect(text, `${id}: an ISO timestamp`).not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/); + expect(text, `${id}: an epoch of 10 digits or more`).not.toMatch(/\b\d{10,}\b/); + } + }); + test("the recorded placeholder host is one that never resolves", () => { expect(new URL(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL).hostname.endsWith(".invalid")).toBe(true); }); From c933f913c7646b0addaa2e71a7361d4198b19738 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 16:12:20 +0100 Subject: [PATCH 08/20] test: add GitLab and Shopify GraphQL node-service data source scenarios Adds recorded GitLab and Shopify data source and query fixtures and scenarios that point each plugin at the run's echo target: the GitLab request body, headers and token, a GraphQL error answer, the Shopify request body, a bound component after a click, and a characterisation that the Shopify plugin drops the query headers (annotated as a defect candidate, with controls proving the header reaches the plugin and that the GitLab plugin forwards it). A unit test covers the new recordings. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 2 +- e2e/README.md | 17 +- .../dsl/plugins/gitlab/gitlabDatasource.json | 10 + .../dsl/plugins/gitlab/gitlabQuery.json | 27 ++ .../plugins/shopify/shopifyDatasource.json | 9 + .../dsl/plugins/shopify/shopifyQuery.json | 27 ++ e2e/tests/datasource/plugin-graphql.spec.ts | 241 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 24 ++ 8 files changed, 349 insertions(+), 8 deletions(-) create mode 100644 e2e/fixtures/dsl/plugins/gitlab/gitlabDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/gitlab/gitlabQuery.json create mode 100644 e2e/fixtures/dsl/plugins/shopify/shopifyDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/shopify/shopifyQuery.json create mode 100644 e2e/tests/datasource/plugin-graphql.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index bedf073974..80a95f699a 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,7 +129,7 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). diff --git a/e2e/README.md b/e2e/README.md index 76d7131068..9aae8611be 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso and Slack run queries, D5, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab and Shopify run queries, D5 and D6, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -209,7 +209,7 @@ e2e/ fixtures/sql/init.sql PostgreSQL data: items, products, notes fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack` + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify` src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -249,15 +249,16 @@ Test titles carry these ids. - D3 the plugin catalogue of node-service: the image serves exactly the registered node plugins, each definition has a form and a query config, the Java-native types carry no definition (`@node-service`; the catalogue only, no plugin query runs). - D4 the DuckDB plugin of node-service, run in the app container with an in-memory database and no network: rows, the published view after a click, a BIGINT as a string, a fresh database per run, a syntax error as a failed query (`@node-service`). - D5 the Turso and Slack plugins of node-service against the echo sidecar: a Turso query sends one Hrana pipeline and answers its rows, `includeRaw` answers values and raw, a non-OK answer and an `error` result fail the query (the latter prints `[object Object]`, NSD-1 candidate), the published view after a click; a Slack query posts the form payload to the webhook (`@node-service`; the request shape and the answer's path into the app, not the vendor service). +- D6 the GitLab and Shopify GraphQL plugins of node-service against the echo sidecar: a GitLab query posts the query, the variables and every header (data source, query and the access token), a GraphQL error answer fails the query, the published view after a click; a Shopify query reaches the endpoint, and the header the query sets does not (NSD-2 candidate) (`@node-service`; the request shape and the answer's path into the app, not the vendor service). - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`, after this branch's security fixes; this is a static listing, not a Docker run. A combined final run against an image built from this branch (tag `secfix-combined-e2e`) has since confirmed pass/fail for every scenario named in the per-defect rows below: 693/696 default tests passed, the 3 failures pre-existing or unrelated suite drift (documented in their own rows below)): -default **726 tests in 108 files**; with `E2E_INCLUDE_QUARANTINE=1` **739 in 109**; with `E2E_INCLUDE_SUPERADMIN=1` **731 in 108**; with both of those **744 in 109**; -with `E2E_INCLUDE_INSERT_ALL=1` **838 in 109**; with all three opt-in variables **856 in 110** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: +default **732 tests in 109 files**; with `E2E_INCLUDE_QUARANTINE=1` **745 in 110**; with `E2E_INCLUDE_SUPERADMIN=1` **737 in 109**; with both of those **750 in 110**; +with `E2E_INCLUDE_INSERT_ALL=1` **844 in 110**; with all three opt-in variables **862 in 111** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 30 (the 16 unit tests of `foundation/node-plugins.spec.ts`, D3a to D3c, D4a to D4e and D5a to D5f; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 36 (the 17 unit tests of `foundation/node-plugins.spec.ts`, D3a to D3c, D4a to D4e, D5a to D5f and D6a to D6e; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -306,7 +307,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | editor/js-query.spec.ts | a JS query written in the editor runs | @core | 1 | | editor/drop-size.spec.ts | a component dropped right after ready has width above 0 (D-5) | @quarantine | 1 | -### datasource (19) +### datasource (20) | File | Proves | Tags | Tests | |---|---|---|---| @@ -316,6 +317,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/notes-queries.spec.ts | unit tests of the query builders | none | 4 | | datasource/plugin-duckdb.spec.ts | D4: DuckDB through the app container, database `:memory:`, no network. D4a a query answers rows, D4b the published view shows the result after a click, D4c a BIGINT and a HUGEINT arrive as exact strings, D4d each run is a fresh database (a table created by one run is gone in the next), D4e a syntax error is a failed query (`success: false`, `queryCode: FAILED`; the field `code` is 1 either way). D4a to D4c assert the measured row shape, keys are the column positions (NSD-3 candidate) | @node-service | 5 | | datasource/plugin-turso-slack.spec.ts | D5: Turso and Slack against the echo sidecar (the data source URL is the test's own echo target). D5a a Turso query sends one POST of `{requests: [execute, close]}` to `/v2/pipeline` with `Authorization: Bearer ` and answers the rows keyed by column name (an `integer` cell as a number), D5b `includeRaw` answers `{values, raw}`, D5c a 500 answer fails the query (`Endpoint returned 500`), D5d an `error` result fails the query with `Cannot parse result, received error: [object Object]` (NSD-1 candidate: the server's message is lost), D5e the published view shows the row after a click, D5f a Slack query posts `payload=` as `application/x-www-form-urlencoded;charset=UTF-8` to the webhook path and answers the webhook's text. Not covered: the `libsql://` rewrite (the echo does not speak TLS) | @node-service | 6 | +| datasource/plugin-graphql.spec.ts | D6: GitLab and Shopify against the echo sidecar (the endpoint is the test's own echo target plus `/api/graphql`). D6a a GitLab query posts one JSON body `{query, variables: {n: 3}, operationName}` (the variable's text `3` arrives as the number 3) with `PRIVATE-TOKEN`, the data source header and the query header, and answers the `data` member, D6b a `{"errors":[...]}` answer fails the query with `: `, D6c a Shopify query posts `{query, variables: {}}` and answers the `data` member (control), D6d the header the Shopify query sets reaches the echo neither as name nor as value (NSD-2 candidate), D6e the published view shows the GitLab answer after a click | @node-service | 5 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -466,7 +468,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso and slack recordings (type, action, placeholder host, no session value) | @node-service | 16 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab and shopify recordings (type, action, placeholder host, no session value) | @node-service | 17 | | foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources) | none | 27 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | @@ -508,6 +510,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | CD-9 | an icon switched from a name to an image URL keeps the old icon: confirmed (failed 3 of 3 on 3.0.1-e2e; code: the old icon is cached under the new URL and `undefined === undefined` keeps it) | `components/displays.spec.ts`, `@quarantine`, `defect` annotation (still named candidate there) | | NSD-1 candidate | the Turso plugin prints a pipeline `error` result as `${result.error}`, an object: a failed statement reaches the app as `Cannot parse result, received error: [object Object]` and the server's own message is lost; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-turso-slack.spec.ts` D5d asserts today's message (characterisation, default run), annotation `{type:"defect", description:"NSD-1 candidate"}`; it changes when the plugin prints the message | | NSD-3 candidate | the DuckDB plugin answers rows keyed by the column position, not the column name (`SELECT 42 AS answer` arrives as `{"0": 42}`): `getRows()` answers arrays and `serializeBigInts` copies `Object.entries(row)`; measured on 3.0.0-e2e and 3.0.1-e2e. An app cannot read `row.answer`. The id is provisional until the owner assigns one | `datasource/plugin-duckdb.spec.ts` D4a to D4c assert today's keys (characterisation, default run), annotation `{type:"defect", description:"NSD-3 candidate"}`; they change when the plugin keys rows by name | +| NSD-2 candidate | the Shopify plugin reads the query's headers and passes `{}` on, and its data source has only `endpoint`: it cannot send Shopify's access token (`X-Shopify-Access-Token`); measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-graphql.spec.ts` D6d asserts today's behaviour after a control that the request did reach the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-2 candidate"}`; it changes when the query's headers are forwarded | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/fixtures/dsl/plugins/gitlab/gitlabDatasource.json b/e2e/fixtures/dsl/plugins/gitlab/gitlabDatasource.json new file mode 100644 index 0000000000..9826796a9c --- /dev/null +++ b/e2e/fixtures/dsl/plugins/gitlab/gitlabDatasource.json @@ -0,0 +1,10 @@ +{ + "name": "gitlab", + "type": "gitlab", + "datasourceConfig": { + "endpoint": "http://placeholder.invalid", + "token": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} diff --git a/e2e/fixtures/dsl/plugins/gitlab/gitlabQuery.json b/e2e/fixtures/dsl/plugins/gitlab/gitlabQuery.json new file mode 100644 index 0000000000..814512e621 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/gitlab/gitlabQuery.json @@ -0,0 +1,27 @@ +{ + "compType": "gitlab", + "comp": { + "actionName": "query", + "action": { + "query": "", + "variables": [ + { + "key": "", + "value": "" + } + ], + "headers": [ + { + "key": "", + "value": "" + } + ] + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/shopify/shopifyDatasource.json b/e2e/fixtures/dsl/plugins/shopify/shopifyDatasource.json new file mode 100644 index 0000000000..2a674c22ef --- /dev/null +++ b/e2e/fixtures/dsl/plugins/shopify/shopifyDatasource.json @@ -0,0 +1,9 @@ +{ + "name": "shopify", + "type": "shopify", + "datasourceConfig": { + "endpoint": "http://placeholder.invalid", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} diff --git a/e2e/fixtures/dsl/plugins/shopify/shopifyQuery.json b/e2e/fixtures/dsl/plugins/shopify/shopifyQuery.json new file mode 100644 index 0000000000..18cc701bc7 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/shopify/shopifyQuery.json @@ -0,0 +1,27 @@ +{ + "compType": "shopify", + "comp": { + "actionName": "query", + "action": { + "query": "", + "variables": [ + { + "key": "", + "value": "" + } + ], + "headers": [ + { + "key": "", + "value": "" + } + ] + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/tests/datasource/plugin-graphql.spec.ts b/e2e/tests/datasource/plugin-graphql.spec.ts new file mode 100644 index 0000000000..99b0340d57 --- /dev/null +++ b/e2e/tests/datasource/plugin-graphql.spec.ts @@ -0,0 +1,241 @@ +import { randomBytes } from "node:crypto"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, getAppDsl, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, TAGS } from "../../src/constants"; +import { appDsl, button, nodePluginQuery, stackItems } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { boundText, boundTextTestId, openSeededView } from "../../src/components/scenario"; +import { expect, test } from "../../src/fixtures"; +import { recordsContain, type EchoRecord, type EchoTarget } from "../../src/security/echo"; + +/** + * D6: the GitLab and Shopify plugins of node-service (`server/node-service/src/plugins/gitlab/index.ts`, `shopify/index.ts`), + * which both post a GraphQL query through the shared runner (`plugins/graphql/run.ts`, `graphql-request`) to a configurable + * endpoint. The endpoint is the test's own target on the echo sidecar, so the tests prove the request the plugin builds and the + * path of the canned answer into the app. They are NOT a fidelity test of GitLab or Shopify. + * + * Shopify: the plugin reads the query's headers and passes none on, and its data source has no token field, so it cannot send + * Shopify's access token (D6d, NSD-2 candidate). + */ +const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; + +/** Candidate defect: the Shopify plugin drops every header of the query and has no access token field. */ +const SHOPIFY_HEADERS_DEFECT = { type: "defect", description: "NSD-2 candidate" } as const; +const SHOPIFY_HEADERS_DETAILS = { annotation: SHOPIFY_HEADERS_DEFECT }; + +/** The path below the target that the endpoint points at. */ +const GRAPHQL_PATH = "/api/graphql"; +const HTTP_OK = 200; +const QUERY_CODE_OK = "OK"; +const QUERY_CODE_FAILED = "FAILED"; +const MARKER_BYTES = 4; +const JSON_CONTENT_TYPE = "application/json"; +/** The header name Shopify expects its token in; the plugin cannot send it. */ +const SHOPIFY_TOKEN_HEADER = "X-Shopify-Access-Token"; + +const BUTTON_TEST_ID = "e2e-graphql-run"; +const RESULT_NAME = "label"; +const SUCCESS_NAME = "succeeded"; +const QUERY_ID = "q1"; +const QUERY_NAME = "q"; + +const GITLAB_OPERATION = "Probe"; +const GITLAB_QUERY = "query Probe($n: Int) { currentUser { username } }"; +const SHOPIFY_QUERY = "query { shop { name } }"; +const GITLAB_USERNAME = "e2e"; +const SHOPIFY_SHOP_NAME = "e2e-shop"; +const GITLAB_DATA = { currentUser: { username: GITLAB_USERNAME } }; +const SHOPIFY_DATA = { shop: { name: SHOPIFY_SHOP_NAME } }; +const GRAPHQL_ERROR_MESSAGE = "e2e-gql-error"; +/** + * What the query reports for the canned error answer (measured on the images `3.0.0-e2e` and `3.0.1-e2e`): `graphql-request`'s + * `ClientError` message is the first error's message, a colon, and the JSON of the response and of the request it sent. + */ +const MEASURED_ERROR_MESSAGE = `${GRAPHQL_ERROR_MESSAGE}: ${JSON.stringify({ + response: { errors: [{ message: GRAPHQL_ERROR_MESSAGE }], status: HTTP_OK, headers: {} }, + request: { query: GITLAB_QUERY, variables: {} }, +})}`; +const VARIABLE_NAME = "n"; +const VARIABLE_VALUE = 3; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +function cannedData(data: unknown): { status: number; contentType: string; body: string } { + return { status: HTTP_OK, contentType: JSON_CONTENT_TYPE, body: JSON.stringify({ data }) }; +} + +/** A data source of plugin `pluginId` from its recording, with its endpoint at the echo target. */ +async function graphqlDatasource(page: Page, apiUser: RegisteredUser, echo: EchoTarget, pluginId: string, config: Record = {}): Promise { + return createNodePluginDatasource(page.request, { + orgId: apiUser.orgId, + recorded: recordedPluginDatasource(pluginId), + config: { endpoint: `${echo.url}${GRAPHQL_PATH}`, ...config }, + }); +} + +/** A saved app with one manual query of plugin `pluginId` (not published: the draft runs with `viewMode: false`). */ +async function graphqlApp(page: Page, apiUser: RegisteredUser, pluginId: string, datasourceId: string, action: Record): Promise<{ appId: string }> { + const query = nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery(pluginId), action }); + return createApp(page.request, { orgId: apiUser.orgId, name: `e2e-${pluginId}`, dsl: appDsl([], { queries: [query] }) }); +} + +async function runDraft(page: Page, appId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId: QUERY_ID, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +function onlyRecord(records: EchoRecord[]): EchoRecord { + expect(records, "the echo received exactly one request").toHaveLength(1); + return records[0] as EchoRecord; +} + +test.describe("GitLab data source against the echo", NODE_SERVICE_DETAILS, () => { + test("D6a: a GitLab query posts the query, the variables and every header", async ({ page, apiUser, echo }) => { + const id = uniqueMarker(); + const token = `e2e-token-${id}`; + const datasourceHeader = `e2e-ds-${id}`; + const queryHeader = `e2e-q-${id}`; + await echo.answer(GRAPHQL_PATH, cannedData(GITLAB_DATA)); + const datasourceId = await graphqlDatasource(page, apiUser, echo, "gitlab", { token, headers: [{ key: "X-E2E-DS", value: datasourceHeader }] }); + const { appId } = await graphqlApp(page, apiUser, "gitlab", datasourceId, { + query: GITLAB_QUERY, + variables: [{ key: VARIABLE_NAME, value: String(VARIABLE_VALUE) }], + headers: [{ key: "X-E2E-Q", value: queryHeader }], + }); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); + const record = onlyRecord(await echo.received()); + expect(record.method, "the request method").toBe("POST"); + expect(record.path, "the request path").toBe(`${echo.path}${GRAPHQL_PATH}`); + expect(String(record.headers["content-type"]), "the body is JSON").toBe(JSON_CONTENT_TYPE); + expect(record.headers["private-token"], "the access token of the data source").toBe(token); + expect(record.headers["x-e2e-ds"], "the header of the data source").toBe(datasourceHeader); + expect(record.headers["x-e2e-q"], "the header of the query").toBe(queryHeader); + // `operationName` is added by graphql-request from the query text; the variable's text "3" arrives as the JSON number 3 + expect(JSON.parse(record.body), "the complete request body").toEqual({ + query: GITLAB_QUERY, + variables: { [VARIABLE_NAME]: VARIABLE_VALUE }, + operationName: GITLAB_OPERATION, + }); + expect(envelopeOf(answer).data, "the answer is the data member of the canned reply").toEqual(GITLAB_DATA); + }); + + test("D6b: a GraphQL error answer fails the query", async ({ page, apiUser, echo }) => { + await echo.answer(GRAPHQL_PATH, { status: HTTP_OK, contentType: JSON_CONTENT_TYPE, body: JSON.stringify({ errors: [{ message: GRAPHQL_ERROR_MESSAGE }] }) }); + const datasourceId = await graphqlDatasource(page, apiUser, echo, "gitlab", { token: "e2e-token" }); + const { appId } = await graphqlApp(page, apiUser, "gitlab", datasourceId, { query: GITLAB_QUERY }); + + const answer = await runDraft(page, appId); + + expect(answer.status, "the request itself is answered").toBe(HTTP_OK); + expect(envelopeOf(answer).success, "the query failed").toBe(false); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_FAILED); + expect(envelopeOf(answer).message, "the message: the server's error, then graphql-request's JSON of the response and the request").toBe(MEASURED_ERROR_MESSAGE); + const record = onlyRecord(await echo.received()); + expect(JSON.parse(record.body), "the complete request body: no variables were set").toEqual({ query: GITLAB_QUERY, variables: {}, operationName: GITLAB_OPERATION }); + }); + + test("D6e: the published view shows a GitLab answer after a click", async ({ page, apiUser, echo }) => { + await echo.answer(GRAPHQL_PATH, cannedData(GITLAB_DATA)); + const datasourceId = await graphqlDatasource(page, apiUser, echo, "gitlab", { token: "e2e-token" }); + // before the first run `q.data` is not an object with `currentUser` + const expression = `{{${QUERY_NAME}.data ? ${QUERY_NAME}.data.currentUser.username : ""}}`; + const view = await openSeededView( + page, + apiUser.orgId, + "e2e-gitlab-view", + stackItems([ + button({ id: "b1", name: "button1", text: "Run", testId: BUTTON_TEST_ID, onClickQuery: QUERY_NAME }), + boundText({ id: "t1", name: RESULT_NAME, expression }), + // `success` also reads `true` before the first run (measured for the other node plugins), so only the state after the click proves anything + boundText({ id: "t2", name: SUCCESS_NAME, expression: `{{String(${QUERY_NAME}.success)}}` }), + ]), + { queries: [nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery("gitlab"), action: { query: GITLAB_QUERY } })] }, + ); + + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "before the click the text is empty").toHaveText(""); + expect(await echo.received(), "before the click the echo holds nothing of this test").toEqual([]); + await view.buttonByTestId(BUTTON_TEST_ID).click(); + await expect(view.byTestId(boundTextTestId(SUCCESS_NAME)), "after the click the query succeeded").toHaveText("true"); + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "after the click the text shows the GitLab answer").toHaveText(GITLAB_USERNAME); + const record = onlyRecord(await echo.received()); + expect(JSON.parse(record.body), "the click sent the complete request body").toEqual({ query: GITLAB_QUERY, variables: {}, operationName: GITLAB_OPERATION }); + }); +}); + +test.describe("Shopify data source against the echo", NODE_SERVICE_DETAILS, () => { + test("D6c: a Shopify query reaches the endpoint", async ({ page, apiUser, echo }) => { + await echo.answer(GRAPHQL_PATH, cannedData(SHOPIFY_DATA)); + const datasourceId = await graphqlDatasource(page, apiUser, echo, "shopify"); + const { appId } = await graphqlApp(page, apiUser, "shopify", datasourceId, { query: SHOPIFY_QUERY }); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); + const record = onlyRecord(await echo.received()); + expect(record.method, "the request method").toBe("POST"); + expect(record.path, "the request path").toBe(`${echo.path}${GRAPHQL_PATH}`); + expect(JSON.parse(record.body), "the complete request body: no variables were set").toEqual({ query: SHOPIFY_QUERY, variables: {} }); + expect(envelopeOf(answer).data, "the answer is the data member of the canned reply").toEqual(SHOPIFY_DATA); + }); + + test("D6d: a Shopify query header never reaches the endpoint", SHOPIFY_HEADERS_DETAILS, async ({ page, apiUser, echo }) => { + const marker = `e2e-shopify-token-${uniqueMarker()}`; + await echo.answer(GRAPHQL_PATH, cannedData(SHOPIFY_DATA)); + const datasourceId = await graphqlDatasource(page, apiUser, echo, "shopify"); + const { appId } = await graphqlApp(page, apiUser, "shopify", datasourceId, { + query: SHOPIFY_QUERY, + headers: [{ key: SHOPIFY_TOKEN_HEADER, value: marker }], + }); + + // control 1: the marker header is in the saved query, so it exists when the plugin is called + const saved = (await getAppDsl(page.request, appId)).applicationDSL as { queries?: { comp?: { action?: { headers?: unknown } } }[] }; + expect(saved.queries?.[0]?.comp?.action?.headers, "the saved Shopify query holds the marker header").toEqual([{ key: SHOPIFY_TOKEN_HEADER, value: marker }]); + + const answer = await runDraft(page, appId); + + // control 2: the query ran and the request did reach the echo, so the absence below is not an unreached echo + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); + const shopifyRecords = await echo.received(); + const record = onlyRecord(shopifyRecords); + expect(JSON.parse(record.body), "the request body is the query").toEqual({ query: SHOPIFY_QUERY, variables: {} }); + // The plugin reads the query's headers and passes `{}` on (NSD-2 candidate, see SHOPIFY_HEADERS_DEFECT): neither the header name nor its value arrives. + expect(recordsContain(shopifyRecords, marker), "the header value reached the endpoint").toBe(false); + expect(Object.keys(record.headers).map((name) => name.toLowerCase()), "the header name reached the endpoint").not.toContain(SHOPIFY_TOKEN_HEADER.toLowerCase()); + + // control 3: the very same header, set on a GitLab query of the same app machinery, does reach the echo, so only the Shopify plugin drops it + const gitlabId = await graphqlDatasource(page, apiUser, echo, "gitlab", { token: "e2e-token" }); + const gitlab = await graphqlApp(page, apiUser, "gitlab", gitlabId, { query: GITLAB_QUERY, headers: [{ key: SHOPIFY_TOKEN_HEADER, value: marker }] }); + expectRan(await runDraft(page, gitlab.appId)); + const all = await echo.received(); + expect(all, "the echo now holds the Shopify and the GitLab request").toHaveLength(2); + expect(all[1]?.headers[SHOPIFY_TOKEN_HEADER.toLowerCase()], "the GitLab plugin forwards the same header").toBe(marker); + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index 29ea57a6cd..388506287a 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -156,6 +156,30 @@ test.describe("node-service data source helpers", { tag: [TAGS.NODE_SERVICE] }, } }); + test("the gitlab and shopify recordings are the form's body and the editor's saved query, with no value of the recording session", () => { + // the form drops empty key/value rows, so the gitlab body has no `headers` (a filled row is `[{ key, value }]`, measured in the form) + const expectations = [ + { id: "gitlab", config: ["endpoint", "token"] }, + { id: "shopify", config: ["endpoint"] }, + ]; + for (const { id, config } of expectations) { + const datasource = recordedPluginDatasource(id); + const query = recordedPluginQuery(id); + expect(datasource.type, `${id}: the data source type`).toBe(id); + expect(Object.keys(datasource.datasourceConfig).slice(0, config.length), `${id}: the form fields`).toEqual(config); + expect(datasource.datasourceConfig.endpoint, `${id}: the placeholder host`).toBe(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL); + expect(query.compType, `${id}: the query type`).toBe(id); + expect(query.comp.actionName, `${id}: the only action of the plugin`).toBe("query"); + expect(Object.keys(query.comp.action as Record), `${id}: the action's parameters`).toEqual(["query", "variables", "headers"]); + expect(Object.keys(query), `${id}: only what the builder keeps`).toEqual(["compType", "comp"]); + expect(Object.keys(datasource), `${id}: no workspace id`).toEqual(["name", "type", "datasourceConfig"]); + const text = [`${id}Datasource.json`, `${id}Query.json`].map((file) => readFileSync(join(RECORDED_PLUGINS_DIR, id, file), "utf8")).join("\n"); + expect(text, `${id}: a 24-hex id`).not.toMatch(/\b[0-9a-f]{24}\b/); + expect(text, `${id}: an ISO timestamp`).not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/); + expect(text, `${id}: an epoch of 10 digits or more`).not.toMatch(/\b\d{10,}\b/); + } + }); + test("the recorded placeholder host is one that never resolves", () => { expect(new URL(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL).hostname.endsWith(".invalid")).toBe(true); }); From 46b02565c872ddf1a55773d82ce53948762a0e42 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 16:29:49 +0100 Subject: [PATCH 09/20] test: add generic OpenAPI node-service data source scenarios Adds a recorded OpenAPI data source and query plus a canned OpenAPI document and scenarios that serve it from the run's echo target: the dynamic config answer and spec fetch, the operation request with its query parameter and API key header, the key coming from the data source configuration, a 404 answer reported as success (annotated as a defect candidate), a bound component after a click, and the in-memory dynamic config cache. A unit test covers the new recording. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 4 +- e2e/README.md | 15 +- .../plugins/openApi/openApiDatasource.json | 28 ++ .../dsl/plugins/openApi/openApiQuery.json | 15 + e2e/src/datasource/node-plugins.ts | 39 ++- e2e/tests/datasource/plugin-openapi.spec.ts | 273 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 37 ++- 7 files changed, 400 insertions(+), 11 deletions(-) create mode 100644 e2e/fixtures/dsl/plugins/openApi/openApiDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/openApi/openApiQuery.json create mode 100644 e2e/tests/datasource/plugin-openapi.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index 80a95f699a..14cd656870 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,7 +129,7 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). @@ -188,7 +188,7 @@ MUST NOT: | containers and slots | `containerWithChildren`, `slotChild`, `slotContainers`, `openSeededApp` | `src/simple-components/seed.ts` | | catalogue, saved-DSL polling | `INSERT_TYPES`, `HOOK_TYPES`, `searchTextOf`, `waitForSavedType`, `prepareForPublish` | `src/components/insert-catalog.ts`, `src/components/insert-all.ts` | | notes and products queries | `selectProductsQuery`, `selectNotesQuery`, `noteWriteQuery`, `insertUpdateDeleteQueries` | `src/datasource/notes-queries.ts` | -| node-service plugin ids and catalogue | `NODE_PLUGIN_IDS`, `nodePluginIdsOf`, `NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL` | `src/datasource/node-plugins.ts` | +| node-service plugin ids and catalogue | `NODE_PLUGIN_IDS`, `nodePluginIdsOf`, `NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL`, `OPEN_API_FIXTURE_SPEC` (canned OpenAPI document for the generic `openApi` plugin) | `src/datasource/node-plugins.ts` | | negative and counter reads, local storage | `expectTextStays`, `countAfterEquals`, `parseCounter`, `rawLocalStorage` | `src/logic/helpers.ts` | | media | `PNG_RED`, `PNG_BLUE`, `WAV`, `WEBM`, `MP4`, `PDF`, `PDF_RAW_B64` | `src/media.ts` | | security actors, quarantine, answers, tokens | `Actor`, `adminOfApiUser`, `joinWorkspace`, `makeDeveloper`, `makeAdmin`, `grantApp`, `seedPrivateApp`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `securityTestDetails`, `securityCandidateDetails`, `expectAnswer`, `expectDeniedAs`, `forgeApiKeyToken`, `forgeUnsignedToken`, `withRandomSignature`, `tokenIsSignedWith`, `superAdminCredentials`, `SUPER_ADMIN_ENV`, `enterpriseAdmin` (ENTERPRISE stack: an actor the super admin makes admin of the one workspace), `echoTargetPath`, `echoReadPrefix`, `echoBaseUrl`, `recordsContain` (requests the SERVER makes, read back from the HTTP echo sidecar: the `echo` fixture gives a test its own target `url` and `received()`; a denial must follow a positive control that the echo does receive from that path; compare a secret with `recordsContain(...)` as a boolean, never as a matcher's value) (the `actor`, `superAdmin` and `echo` fixtures are in `src/fixtures.ts`; the raw-answer helper `apiRaw` and the other security API helpers are in `src/api/client.ts`) | `src/security/actors.ts`, `scene.ts`, `quarantine.ts`, `assertions.ts`, `tokens.ts`, `super-admin.ts`, `enterprise.ts`, `echo.ts` | diff --git a/e2e/README.md b/e2e/README.md index 9aae8611be..164abcfeeb 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab and Shopify run queries, D5 and D6, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify and the generic Open API plugin run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), D5 to D7, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -209,7 +209,7 @@ e2e/ fixtures/sql/init.sql PostgreSQL data: items, products, notes fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify` + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition) src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -250,15 +250,16 @@ Test titles carry these ids. - D4 the DuckDB plugin of node-service, run in the app container with an in-memory database and no network: rows, the published view after a click, a BIGINT as a string, a fresh database per run, a syntax error as a failed query (`@node-service`). - D5 the Turso and Slack plugins of node-service against the echo sidecar: a Turso query sends one Hrana pipeline and answers its rows, `includeRaw` answers values and raw, a non-OK answer and an `error` result fail the query (the latter prints `[object Object]`, NSD-1 candidate), the published view after a click; a Slack query posts the form payload to the webhook (`@node-service`; the request shape and the answer's path into the app, not the vendor service). - D6 the GitLab and Shopify GraphQL plugins of node-service against the echo sidecar: a GitLab query posts the query, the variables and every header (data source, query and the access token), a GraphQL error answer fails the query, the published view after a click; a Shopify query reaches the endpoint, and the header the query sets does not (NSD-2 candidate) (`@node-service`; the request shape and the answer's path into the app, not the vendor service). +- D7 the generic Open API plugin of node-service against the echo sidecar: the data source form's dynamic config reads the OpenAPI document from its URL (the echo serves a canned document) and answers the spec and the key field, an operation runs against the server URL with the key in the header the document names, the key comes from the data source (no key, no header), an error status answers its body as a successful result (NSD-4 candidate), the published view after a click, the dynamic config answer is cached in memory per request body, with no expiry (observation) (`@node-service`). - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`, after this branch's security fixes; this is a static listing, not a Docker run. A combined final run against an image built from this branch (tag `secfix-combined-e2e`) has since confirmed pass/fail for every scenario named in the per-defect rows below: 693/696 default tests passed, the 3 failures pre-existing or unrelated suite drift (documented in their own rows below)): -default **732 tests in 109 files**; with `E2E_INCLUDE_QUARANTINE=1` **745 in 110**; with `E2E_INCLUDE_SUPERADMIN=1` **737 in 109**; with both of those **750 in 110**; -with `E2E_INCLUDE_INSERT_ALL=1` **844 in 110**; with all three opt-in variables **862 in 111** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: +default **739 tests in 110 files**; with `E2E_INCLUDE_QUARANTINE=1` **752 in 111**; with `E2E_INCLUDE_SUPERADMIN=1` **744 in 110**; with both of those **757 in 111**; +with `E2E_INCLUDE_INSERT_ALL=1` **851 in 111**; with all three opt-in variables **869 in 112** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 36 (the 17 unit tests of `foundation/node-plugins.spec.ts`, D3a to D3c, D4a to D4e, D5a to D5f and D6a to D6e; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 43 (the 18 unit tests of `foundation/node-plugins.spec.ts`, D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e and D7a to D7f; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -318,6 +319,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/plugin-duckdb.spec.ts | D4: DuckDB through the app container, database `:memory:`, no network. D4a a query answers rows, D4b the published view shows the result after a click, D4c a BIGINT and a HUGEINT arrive as exact strings, D4d each run is a fresh database (a table created by one run is gone in the next), D4e a syntax error is a failed query (`success: false`, `queryCode: FAILED`; the field `code` is 1 either way). D4a to D4c assert the measured row shape, keys are the column positions (NSD-3 candidate) | @node-service | 5 | | datasource/plugin-turso-slack.spec.ts | D5: Turso and Slack against the echo sidecar (the data source URL is the test's own echo target). D5a a Turso query sends one POST of `{requests: [execute, close]}` to `/v2/pipeline` with `Authorization: Bearer ` and answers the rows keyed by column name (an `integer` cell as a number), D5b `includeRaw` answers `{values, raw}`, D5c a 500 answer fails the query (`Endpoint returned 500`), D5d an `error` result fails the query with `Cannot parse result, received error: [object Object]` (NSD-1 candidate: the server's message is lost), D5e the published view shows the row after a click, D5f a Slack query posts `payload=` as `application/x-www-form-urlencoded;charset=UTF-8` to the webhook path and answers the webhook's text. Not covered: the `libsql://` rewrite (the echo does not speak TLS) | @node-service | 6 | | datasource/plugin-graphql.spec.ts | D6: GitLab and Shopify against the echo sidecar (the endpoint is the test's own echo target plus `/api/graphql`). D6a a GitLab query posts one JSON body `{query, variables: {n: 3}, operationName}` (the variable's text `3` arrives as the number 3) with `PRIVATE-TOKEN`, the data source header and the query header, and answers the `data` member, D6b a `{"errors":[...]}` answer fails the query with `: `, D6c a Shopify query posts `{query, variables: {}}` and answers the `data` member (control), D6d the header the Shopify query sets reaches the echo neither as name nor as value (NSD-2 candidate), D6e the published view shows the GitLab answer after a click | @node-service | 5 | +| datasource/plugin-openapi.spec.ts | D7: the generic Open API plugin against the echo sidecar (spec URL `/spec.json`, server URL `/api`; the document is `OPEN_API_FIXTURE_SPEC`: `GET /items`, operation `listItems`, parameter `q`, API key header `X-E2E-Key`, placeholder server). D7a the dynamic config call (`path` `$.dataSourceConfig.extra`) answers `[{data: {spec}, extraParams}]` with the key field `E2EKeyAuth.value` labelled `X-E2E-Key` and fetches the document with exactly one GET, D7b `listItems` sends `GET /api/items?q=` with `x-e2e-key` and answers the canned `[{id: 1}]`, D7c a data source with an empty `dynamicParamsConfig` sends no key header, D7d a canned 404 `{"message":"e2e-missing"}` is answered as `success: true`, `queryCode: "OK"`, data the 404 body (NSD-4 candidate), D7e the published view shows the first item's id only after the click (echo 0 requests before, exactly 1 after), D7f the same dynamic config request answers from the cache after the document changed on the echo (one fetch), while a request with another body fetches again; the cache is an in-process object keyed on path, query and body with no expiry (observation) | @node-service | 6 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -468,7 +470,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab and shopify recordings (type, action, placeholder host, no session value) | @node-service | 17 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value) | @node-service | 18 | | foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources) | none | 27 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | @@ -511,6 +513,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-1 candidate | the Turso plugin prints a pipeline `error` result as `${result.error}`, an object: a failed statement reaches the app as `Cannot parse result, received error: [object Object]` and the server's own message is lost; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-turso-slack.spec.ts` D5d asserts today's message (characterisation, default run), annotation `{type:"defect", description:"NSD-1 candidate"}`; it changes when the plugin prints the message | | NSD-3 candidate | the DuckDB plugin answers rows keyed by the column position, not the column name (`SELECT 42 AS answer` arrives as `{"0": 42}`): `getRows()` answers arrays and `serializeBigInts` copies `Object.entries(row)`; measured on 3.0.0-e2e and 3.0.1-e2e. An app cannot read `row.answer`. The id is provisional until the owner assigns one | `datasource/plugin-duckdb.spec.ts` D4a to D4c assert today's keys (characterisation, default run), annotation `{type:"defect", description:"NSD-3 candidate"}`; they change when the plugin keys rows by name | | NSD-2 candidate | the Shopify plugin reads the query's headers and passes `{}` on, and its data source has only `endpoint`: it cannot send Shopify's access token (`X-Shopify-Access-Token`); measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-graphql.spec.ts` D6d asserts today's behaviour after a control that the request did reach the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-2 candidate"}`; it changes when the query's headers are forwarded | +| NSD-4 candidate | the generic Open API plugin returns the body of an error status answer as the query result (`runOpenApi` catch, `e.response.body`): a canned 404 `{"message":"e2e-missing"}` is reported as `success: true`, `queryCode: "OK"`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi.spec.ts` D7d asserts today's behaviour after a control that the request reached the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-4 candidate"}`; it changes when an error status fails the query | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/fixtures/dsl/plugins/openApi/openApiDatasource.json b/e2e/fixtures/dsl/plugins/openApi/openApiDatasource.json new file mode 100644 index 0000000000..b9aaf08885 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/openApi/openApiDatasource.json @@ -0,0 +1,28 @@ +{ + "name": "openApi", + "type": "openApi", + "datasourceConfig": { + "extra": { + "spec": "{\"openapi\":\"3.0.0\",\"info\":{\"title\":\"e2e items\",\"version\":\"1.0.0\"},\"servers\":[{\"url\":\"http://placeholder.invalid\"}],\"security\":[{\"E2EKeyAuth\":[]}],\"paths\":{\"/items\":{\"get\":{\"operationId\":\"listItems\",\"summary\":\"List the items\",\"parameters\":[{\"name\":\"q\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\"}}],\"responses\":{\"200\":{\"description\":\"the items\"}}}}},\"components\":{\"securitySchemes\":{\"E2EKeyAuth\":{\"type\":\"apiKey\",\"in\":\"header\",\"name\":\"X-E2E-Key\"}}}}" + }, + "dynamicParamsDef": [ + { + "type": "groupTitle", + "key": "E2EKeyAuth", + "label": "Api Key Auth" + }, + { + "type": "password", + "key": "E2EKeyAuth.value", + "label": "X-E2E-Key" + } + ], + "url": "http://placeholder.invalid/spec.json", + "serverURL": "http://placeholder.invalid", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT", + "dynamicParamsConfig": { + "E2EKeyAuth.value": "placeholder" + } + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/openApi/openApiQuery.json b/e2e/fixtures/dsl/plugins/openApi/openApiQuery.json new file mode 100644 index 0000000000..6c8c63e974 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/openApi/openApiQuery.json @@ -0,0 +1,15 @@ +{ + "compType": "openApi", + "comp": { + "actionName": "listItems", + "action": { + "query_@_q": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/src/datasource/node-plugins.ts b/e2e/src/datasource/node-plugins.ts index 4ec41c7296..5d388e2bb4 100644 --- a/e2e/src/datasource/node-plugins.ts +++ b/e2e/src/datasource/node-plugins.ts @@ -70,7 +70,7 @@ export const NODE_PLUGIN_IDS: readonly string[] = [ "uiPath", ]; -/** The value of a placeholder host in recorded data source bodies: the `.invalid` TLD (RFC 2606) never resolves, so a recording that was not given a real target fails instead of reaching a host. */ +/** The value of a placeholder host in recorded data source bodies: the `.invalid` TLD (RFC 2606). A placeholder host is never relied on to fail: it may resolve in an environment with a DNS search domain (measured), so every request a test makes is pointed at the echo target (or another deterministic target) and a recording holds placeholder values only. */ export const NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL = "http://placeholder.invalid"; /** @@ -80,3 +80,40 @@ export const NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL = "http://placeholder.invalid"; export function nodePluginIdsOf(types: readonly DatasourceTypeEntry[]): string[] { return types.filter((entry) => entry.definition !== null && entry.definition !== undefined).map((entry) => entry.id); } + +/** The name of the API key security scheme of `OPEN_API_FIXTURE_SPEC`; the data source form stores the key under `.value`. */ +export const OPEN_API_FIXTURE_SCHEME = "E2EKeyAuth"; + +/** The header the API key of `OPEN_API_FIXTURE_SPEC` travels in; the form labels the key field with it. */ +export const OPEN_API_FIXTURE_KEY_HEADER = "X-E2E-Key"; + +/** The operation of `OPEN_API_FIXTURE_SPEC`. */ +export const OPEN_API_FIXTURE_OPERATION = "listItems"; + +/** + * A minimal OpenAPI 3.0 document for the generic `openApi` plugin: `GET /items` (operation `listItems`, query parameter `q`) + * secured by an API key in the header `X-E2E-Key`. Its one server is the placeholder host, which no test relies on to fail: + * every request is pointed at the echo through the data source's `serverURL`. The tests serve it from the echo as a canned + * answer; the plugin's form fetches it for real while it builds its dynamic config. + */ +export const OPEN_API_FIXTURE_SPEC = { + openapi: "3.0.0", + info: { title: "e2e items", version: "1.0.0" }, + servers: [{ url: NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL }], + security: [{ [OPEN_API_FIXTURE_SCHEME]: [] }], + paths: { + "/items": { + get: { + operationId: OPEN_API_FIXTURE_OPERATION, + summary: "List the items", + parameters: [{ name: "q", in: "query", required: false, schema: { type: "string" } }], + responses: { "200": { description: "the items" } }, + }, + }, + }, + components: { + securitySchemes: { + [OPEN_API_FIXTURE_SCHEME]: { type: "apiKey", in: "header", name: OPEN_API_FIXTURE_KEY_HEADER }, + }, + }, +} as const; diff --git a/e2e/tests/datasource/plugin-openapi.spec.ts b/e2e/tests/datasource/plugin-openapi.spec.ts new file mode 100644 index 0000000000..b40990b9bd --- /dev/null +++ b/e2e/tests/datasource/plugin-openapi.spec.ts @@ -0,0 +1,273 @@ +import { randomBytes } from "node:crypto"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, pluginDynamicConfigRaw, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, TAGS } from "../../src/constants"; +import { appDsl, button, nodePluginQuery, stackItems } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { + OPEN_API_FIXTURE_KEY_HEADER, + OPEN_API_FIXTURE_OPERATION, + OPEN_API_FIXTURE_SCHEME, + OPEN_API_FIXTURE_SPEC, +} from "../../src/datasource/node-plugins"; +import { boundText, boundTextTestId, openSeededView } from "../../src/components/scenario"; +import { expect, test } from "../../src/fixtures"; +import type { EchoRecord, EchoTarget } from "../../src/security/echo"; + +/** + * D7: the generic `openApi` plugin of node-service (`server/node-service/src/plugins/openApi/index.ts`). Its data source form + * fetches the OpenAPI document from the `url` field for real, while the form builds its dynamic config (`extra`, answered by + * `POST /api/datasources/getPluginDynamicConfig`); the plugin then runs an operation against `serverURL` (or the document's own + * server) with `swagger-client`. Here the document is a canned answer of the test's own echo target (`OPEN_API_FIXTURE_SPEC`) + * and the server URL is the same target, so the tests prove the requests the plugin makes and the path of the answer into the + * app. They are NOT a fidelity test of any OpenAPI service. + * + * No test runs an operation without a server URL: that request would go to the document's own server, the placeholder host, + * and a placeholder host is never relied on to fail: measured on one development machine, the app container's DNS search domain + * answered it, with an HTML 404 reported as a successful query. The server URL override is proven + * by the one request that reaches the echo. + */ +const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; + +/** Candidate defect: an error status answer with a body is returned as the query's successful result. */ +const ERROR_STATUS_SUCCESS_DEFECT = { type: "defect", description: "NSD-4 candidate" } as const; +const ERROR_STATUS_DETAILS = { annotation: ERROR_STATUS_SUCCESS_DEFECT }; + +/** + * Observation: node-service keeps the dynamic config answers in a module-level object keyed on the request path, query and JSON + * body (`routes/apiRouter.ts`, `cacheMiddleware`) with no expiry or eviction in that code, so an unchanged request never fetches + * the document again until the process restarts. The tests rely on the key being the body only: each uses its own spec URL. + */ +const CACHE_OBSERVATION = { type: "observation", description: "dynamic config answers are cached in memory per request body, with no expiry" } as const; +const CACHE_DETAILS = { annotation: CACHE_OBSERVATION }; + +const SPEC_PATH = "/spec.json"; +const API_PATH = "/api"; +const ITEMS_PATH = `${API_PATH}/items`; +const HTTP_OK = 200; +const HTTP_NOT_FOUND = 404; +const JSON_CONTENT_TYPE = "application/json"; +const QUERY_CODE_OK = "OK"; +const MARKER_BYTES = 4; +/** The `path` of the request the data source form sends for its dynamic config (`pluginDataSourceForm.tsx`, `fetchDynamicPluginConfig`). */ +const DYNAMIC_CONFIG_PATH = "$.dataSourceConfig.extra"; +/** The query parameter of the operation, as the editor names an action parameter: `_@_` (`util.ts`, `ConfigKeySplit`). */ +const QUERY_PARAM_KEY = "query_@_q"; +const KEY_CONFIG_NAME = `${OPEN_API_FIXTURE_SCHEME}.value`; +const OPERATION_RENAMED = "renamedItems"; + +const ITEMS = [{ id: 1 }]; +const MISSING_BODY = { message: "e2e-missing" }; + +const BUTTON_TEST_ID = "e2e-openapi-run"; +const RESULT_NAME = "label"; +const SUCCESS_NAME = "succeeded"; +const QUERY_ID = "q1"; +const QUERY_NAME = "q"; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +function canned(status: number, body: unknown): { status: number; contentType: string; body: string } { + return { status, contentType: JSON_CONTENT_TYPE, body: JSON.stringify(body) }; +} + +/** The request body of the form's dynamic config call: `url` (and optionally `serverURL`) next to the form's two defaults, as recorded from the form. */ +function dynamicConfigRequest(echo: EchoTarget, extraFields: Record = {}): object[] { + return [ + { + pluginName: "openApi", + path: DYNAMIC_CONFIG_PATH, + dataSourceConfig: { url: `${echo.url}${SPEC_PATH}`, ...extraFields, authConfigType: "NO_AUTH", sslCertVerificationType: "VERIFY_CA_CERT" }, + }, + ]; +} + +interface DynamicConfigEntry { + data?: { spec?: string }; + extraParams?: unknown; +} + +function dynamicEntriesOf(answer: RawAnswer): DynamicConfigEntry[] { + return (answer.json as { data?: DynamicConfigEntry[] }).data ?? []; +} + +function onlyRecord(records: EchoRecord[]): EchoRecord { + expect(records, "the echo received exactly one request").toHaveLength(1); + return records[0] as EchoRecord; +} + +/** A data source from the recording whose spec URL and server URL are the echo target's; `config` is merged over it. */ +async function openApiDatasource(page: Page, apiUser: RegisteredUser, echo: EchoTarget, config: Record): Promise { + return createNodePluginDatasource(page.request, { + orgId: apiUser.orgId, + recorded: recordedPluginDatasource("openApi"), + config: { url: `${echo.url}${SPEC_PATH}`, ...config }, + }); +} + +/** A saved app with one manual `listItems` query (not published: the draft runs with `viewMode: false`). */ +async function openApiApp(page: Page, apiUser: RegisteredUser, datasourceId: string, marker: string): Promise<{ appId: string }> { + const query = nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery("openApi"), action: { [QUERY_PARAM_KEY]: marker } }); + return createApp(page.request, { orgId: apiUser.orgId, name: "e2e-openapi", dsl: appDsl([], { queries: [query] }) }); +} + +async function runDraft(page: Page, appId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId: QUERY_ID, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +test.describe("generic openApi data source against the echo", NODE_SERVICE_DETAILS, () => { + test("D7a: the data source form's dynamic config reads the spec from its URL", async ({ page, apiUser, echo }) => { + expect(apiUser.orgId, "the test is signed in (the route needs a session)").not.toBe(""); + await echo.answer(SPEC_PATH, canned(HTTP_OK, OPEN_API_FIXTURE_SPEC)); + expect(await echo.received(), "before the request the echo holds nothing of this test").toEqual([]); + + const answer = await pluginDynamicConfigRaw(page.request, dynamicConfigRequest(echo)); + + expectRan(answer); + const entries = dynamicEntriesOf(answer); + expect(entries, "one answer per request").toHaveLength(1); + expect(JSON.parse(entries[0]?.data?.spec ?? "null"), "the stored spec is the document the echo served").toEqual(OPEN_API_FIXTURE_SPEC); + expect(entries[0]?.extraParams, "the form's key field, built from the document's security scheme").toEqual([ + { type: "groupTitle", key: OPEN_API_FIXTURE_SCHEME, label: "Api Key Auth" }, + { type: "password", key: KEY_CONFIG_NAME, label: OPEN_API_FIXTURE_KEY_HEADER }, + ]); + const record = onlyRecord(await echo.received()); + expect(record.method, "the document is fetched with GET").toBe("GET"); + expect(record.path, "the document's path, no query").toBe(`${echo.path}${SPEC_PATH}`); + expect(record.body, "no body").toBe(""); + }); + + test("D7b: an operation runs against the server URL with the key header", async ({ page, apiUser, echo }) => { + const id = uniqueMarker(); + const marker = `e2e-q-${id}`; + const key = `e2e-key-${id}`; + await echo.answer(ITEMS_PATH, canned(HTTP_OK, ITEMS)); + const datasourceId = await openApiDatasource(page, apiUser, echo, { serverURL: `${echo.url}${API_PATH}`, dynamicParamsConfig: { [KEY_CONFIG_NAME]: key } }); + const { appId } = await openApiApp(page, apiUser, datasourceId, marker); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); + // positive control for the server URL override: the one request went to the echo (the document's own server is the placeholder host, which is never contacted) + const record = onlyRecord(await echo.received()); + expect(record.method, "the operation's method").toBe("GET"); + expect(record.path, "the server URL, the operation's path and the query parameter").toBe(`${echo.path}${ITEMS_PATH}?q=${marker}`); + expect(record.body, "no body").toBe(""); + expect(record.headers["x-e2e-key"], "the key of the data source, in the header the document names").toBe(key); + expect(record.headers.accept, "swagger-client asks for JSON").toBe(JSON_CONTENT_TYPE); + expect(envelopeOf(answer).data, "the answer is the body of the echo's canned reply").toEqual(ITEMS); + }); + + test("D7c: the key header comes from the data source, not from the recording", async ({ page, apiUser, echo }) => { + const marker = `e2e-q-${uniqueMarker()}`; + await echo.answer(ITEMS_PATH, canned(HTTP_OK, ITEMS)); + // no key configured: the recorded placeholder key is replaced by an empty config + const datasourceId = await openApiDatasource(page, apiUser, echo, { serverURL: `${echo.url}${API_PATH}`, dynamicParamsConfig: {} }); + const { appId } = await openApiApp(page, apiUser, datasourceId, marker); + + const answer = await runDraft(page, appId); + + expectRan(answer); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); + const record = onlyRecord(await echo.received()); + expect(record.path, "the request reached the echo (control: the header's absence below is not an unreached echo)").toBe(`${echo.path}${ITEMS_PATH}?q=${marker}`); + expect(Object.keys(record.headers), "no key header without a configured key").not.toContain("x-e2e-key"); + }); + + test("D7d: an error status answers its body as a successful result", ERROR_STATUS_DETAILS, async ({ page, apiUser, echo }) => { + const marker = `e2e-q-${uniqueMarker()}`; + await echo.answer(ITEMS_PATH, canned(HTTP_NOT_FOUND, MISSING_BODY)); + const datasourceId = await openApiDatasource(page, apiUser, echo, { serverURL: `${echo.url}${API_PATH}`, dynamicParamsConfig: { [KEY_CONFIG_NAME]: "e2e-key" } }); + const { appId } = await openApiApp(page, apiUser, datasourceId, marker); + + const answer = await runDraft(page, appId); + + // control: the request reached the echo and the echo answered 404 (the canned answer of this path) + const record = onlyRecord(await echo.received()); + expect(record.path, "the operation's request reached the echo").toBe(`${echo.path}${ITEMS_PATH}?q=${marker}`); + expectRan(answer); + // Measured on the images `3.0.0-e2e` and `3.0.1-e2e`: `runOpenApi` returns the body of an error answer as the result (NSD-4 + // candidate, see ERROR_STATUS_SUCCESS_DEFECT), so the 404 is reported as a successful query. + expect(envelopeOf(answer).success, "the 404 is reported as success").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code of the 404").toBe(QUERY_CODE_OK); + expect(envelopeOf(answer).data, "the result is the error body").toEqual(MISSING_BODY); + }); + + test("D7e: the published view shows the items after a click", async ({ page, apiUser, echo }) => { + const marker = `e2e-q-${uniqueMarker()}`; + await echo.answer(ITEMS_PATH, canned(HTTP_OK, ITEMS)); + const datasourceId = await openApiDatasource(page, apiUser, echo, { serverURL: `${echo.url}${API_PATH}`, dynamicParamsConfig: { [KEY_CONFIG_NAME]: "e2e-key" } }); + // before the first run `q.data` is not an array + const expression = `{{${QUERY_NAME}.data ? ${QUERY_NAME}.data[0].id : ""}}`; + const view = await openSeededView( + page, + apiUser.orgId, + "e2e-openapi-view", + stackItems([ + button({ id: "b1", name: "button1", text: "Run", testId: BUTTON_TEST_ID, onClickQuery: QUERY_NAME }), + boundText({ id: "t1", name: RESULT_NAME, expression }), + // `success` also reads `true` before the first run (measured for the other node plugins), so only the state after the click proves anything + boundText({ id: "t2", name: SUCCESS_NAME, expression: `{{String(${QUERY_NAME}.success)}}` }), + ]), + { queries: [nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery("openApi"), action: { [QUERY_PARAM_KEY]: marker } })] }, + ); + + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "before the click the text is empty").toHaveText(""); + expect(await echo.received(), "before the click the echo holds nothing of this test").toEqual([]); + await view.buttonByTestId(BUTTON_TEST_ID).click(); + await expect(view.byTestId(boundTextTestId(SUCCESS_NAME)), "after the click the query succeeded").toHaveText("true"); + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "after the click the text shows the id of the first item").toHaveText(String(ITEMS[0]?.id)); + const record = onlyRecord(await echo.received()); + expect(record.path, "the click sent the operation's request").toBe(`${echo.path}${ITEMS_PATH}?q=${marker}`); + }); +}); + +test.describe("generic openApi dynamic config cache", NODE_SERVICE_DETAILS, () => { + test("D7f: the dynamic config answer is cached per request body", CACHE_DETAILS, async ({ page, apiUser, echo }) => { + expect(apiUser.orgId, "the test is signed in (the route needs a session)").not.toBe(""); + await echo.answer(SPEC_PATH, canned(HTTP_OK, OPEN_API_FIXTURE_SPEC)); + const first = await pluginDynamicConfigRaw(page.request, dynamicConfigRequest(echo)); + expectRan(first); + expect(dynamicEntriesOf(first)[0]?.data?.spec, "the first answer holds the operation").toContain(OPEN_API_FIXTURE_OPERATION); + expect(await echo.received(), "the first request fetched the document once").toHaveLength(1); + + // the document changes on the echo: its operation is renamed + const renamed = JSON.stringify(OPEN_API_FIXTURE_SPEC).replace(OPEN_API_FIXTURE_OPERATION, OPERATION_RENAMED); + await echo.answer(SPEC_PATH, { status: HTTP_OK, contentType: JSON_CONTENT_TYPE, body: renamed }); + + const second = await pluginDynamicConfigRaw(page.request, dynamicConfigRequest(echo)); + + expectRan(second); + expect(second.json, "the same request body is answered from the cache: the identical answer").toEqual(first.json); + expect(dynamicEntriesOf(second)[0]?.data?.spec, "the cached answer still holds the old operation").toContain(OPEN_API_FIXTURE_OPERATION); + expect(await echo.received(), "the second request did not fetch the document").toHaveLength(1); + + // control: another request body is not cached, so it fetches the changed document and the rename shows + const other = await pluginDynamicConfigRaw(page.request, dynamicConfigRequest(echo, { serverURL: `${echo.url}${API_PATH}` })); + expectRan(other); + expect(dynamicEntriesOf(other)[0]?.data?.spec, "a new request body reads the changed document").toContain(OPERATION_RENAMED); + expect(dynamicEntriesOf(other)[0]?.data?.spec, "and no longer holds the old operation").not.toContain(OPEN_API_FIXTURE_OPERATION); + expect(await echo.received(), "the new request body fetched the document again").toHaveLength(2); + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index 388506287a..ed5793b0a8 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -15,7 +15,15 @@ import { type RecordedPluginDatasource, type RecordedPluginQuery, } from "../../src/dsl/recorded"; -import { NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL, NODE_PLUGIN_IDS, nodePluginIdsOf } from "../../src/datasource/node-plugins"; +import { + NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL, + NODE_PLUGIN_IDS, + nodePluginIdsOf, + OPEN_API_FIXTURE_KEY_HEADER, + OPEN_API_FIXTURE_OPERATION, + OPEN_API_FIXTURE_SCHEME, + OPEN_API_FIXTURE_SPEC, +} from "../../src/datasource/node-plugins"; /** * Stack-free unit spec of the node-service data source helpers (parser, loaders, builder, body helper, catalogue filter). @@ -180,7 +188,32 @@ test.describe("node-service data source helpers", { tag: [TAGS.NODE_SERVICE] }, } }); - test("the recorded placeholder host is one that never resolves", () => { + test("the openApi recordings are the form's body, with the spec it stored, and the editor's saved query, with no value of the recording session", () => { + const datasource = recordedPluginDatasource("openApi"); + const query = recordedPluginQuery("openApi"); + const config = datasource.datasourceConfig; + expect(datasource.type, "the data source type").toBe("openApi"); + expect(Object.keys(datasource), "no workspace id").toEqual(["name", "type", "datasourceConfig"]); + expect(config.url, "the placeholder spec URL").toBe(`${NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL}/spec.json`); + expect(config.serverURL, "the placeholder server URL").toBe(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL); + expect(Object.keys(config.extra as Record), "the dynamic config's data is the spec").toEqual(["spec"]); + expect(JSON.parse((config.extra as { spec: string }).spec), "the stored spec is the fixture spec").toEqual(OPEN_API_FIXTURE_SPEC); + expect(config.dynamicParamsDef, "the key field the form built from the security scheme").toEqual([ + { type: "groupTitle", key: OPEN_API_FIXTURE_SCHEME, label: "Api Key Auth" }, + { type: "password", key: `${OPEN_API_FIXTURE_SCHEME}.value`, label: OPEN_API_FIXTURE_KEY_HEADER }, + ]); + expect(Object.keys(config.dynamicParamsConfig as Record), "the key is stored under .value").toEqual([`${OPEN_API_FIXTURE_SCHEME}.value`]); + expect(query.compType, "the query type").toBe("openApi"); + expect(query.comp.actionName, "the operation").toBe(OPEN_API_FIXTURE_OPERATION); + expect(query.comp.action, "the operation's parameter, empty").toEqual({ "query_@_q": "" }); + expect(Object.keys(query), "only what the builder keeps").toEqual(["compType", "comp"]); + const text = ["openApiDatasource.json", "openApiQuery.json"].map((file) => readFileSync(join(RECORDED_PLUGINS_DIR, "openApi", file), "utf8")).join("\n"); + expect(text, "a 24-hex id").not.toMatch(/\b[0-9a-f]{24}\b/); + expect(text, "an echo address").not.toContain("e2e-echo"); + expect(text, "an epoch of 10 digits or more").not.toMatch(/\b\d{10,}\b/); + }); + + test("the recorded placeholder host is under the reserved .invalid TLD", () => { expect(new URL(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL).hostname.endsWith(".invalid")).toBe(true); }); From a3532345131de0b9e8bd3224a790a8f7b7049422 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 17:24:18 +0100 Subject: [PATCH 10/20] test: add CouchDB, Jira, Datadog, WooCommerce and Supabase API scenarios Adds recorded data source and query fixtures for five OpenAPI-based node-service plugins and scenarios that point each at the run's echo target: the request path, query and credential headers for each plugin, CouchDB credential selection, WooCommerce server URL normalisation and refused API versions, and queries submitted together against two server URLs. A WooCommerce server URL that already ends in /wp-json/wc/v3/ is requested at a doubled path; this is characterised and annotated as a defect candidate. The echo sidecar gains an optional barrier on a canned answer: requests are recorded on arrival and answered together once a set number are waiting, or answered 504 if the group does not fill in time. Existing answers are unchanged. Unit tests cover the barrier, its cleanup between groups, and invalid settings. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 4 +- e2e/README.md | 23 +- .../plugins/couchdb/couchdbDatasource.json | 12 + .../dsl/plugins/couchdb/couchdbQuery.json | 21 + .../plugins/datadog/datadogDatasource.json | 11 + .../dsl/plugins/datadog/datadogQuery.json | 15 + .../dsl/plugins/jira/jiraDatasource.json | 11 + e2e/fixtures/dsl/plugins/jira/jiraQuery.json | 15 + .../supabaseApi/supabaseApiDatasource.json | 10 + .../plugins/supabaseApi/supabaseApiQuery.json | 13 + .../woocommerce/woocommerceDatasource.json | 11 + .../plugins/woocommerce/woocommerceQuery.json | 44 ++ e2e/scripts/echo-server.js | 68 ++- e2e/src/datasource/node-plugins.ts | 27 ++ e2e/src/fixtures.ts | 2 +- e2e/src/security/echo.ts | 6 + .../plugin-openapi-wrappers-data.spec.ts | 423 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 51 +++ e2e/tests/foundation/security-echo.spec.ts | 74 +++ 19 files changed, 825 insertions(+), 16 deletions(-) create mode 100644 e2e/fixtures/dsl/plugins/couchdb/couchdbDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/couchdb/couchdbQuery.json create mode 100644 e2e/fixtures/dsl/plugins/datadog/datadogDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/datadog/datadogQuery.json create mode 100644 e2e/fixtures/dsl/plugins/jira/jiraDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/jira/jiraQuery.json create mode 100644 e2e/fixtures/dsl/plugins/supabaseApi/supabaseApiDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/supabaseApi/supabaseApiQuery.json create mode 100644 e2e/fixtures/dsl/plugins/woocommerce/woocommerceDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/woocommerce/woocommerceQuery.json create mode 100644 e2e/tests/datasource/plugin-openapi-wrappers-data.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index 14cd656870..c3d49f3c19 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,7 +129,7 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). @@ -188,7 +188,7 @@ MUST NOT: | containers and slots | `containerWithChildren`, `slotChild`, `slotContainers`, `openSeededApp` | `src/simple-components/seed.ts` | | catalogue, saved-DSL polling | `INSERT_TYPES`, `HOOK_TYPES`, `searchTextOf`, `waitForSavedType`, `prepareForPublish` | `src/components/insert-catalog.ts`, `src/components/insert-all.ts` | | notes and products queries | `selectProductsQuery`, `selectNotesQuery`, `noteWriteQuery`, `insertUpdateDeleteQueries` | `src/datasource/notes-queries.ts` | -| node-service plugin ids and catalogue | `NODE_PLUGIN_IDS`, `nodePluginIdsOf`, `NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL`, `OPEN_API_FIXTURE_SPEC` (canned OpenAPI document for the generic `openApi` plugin) | `src/datasource/node-plugins.ts` | +| node-service plugin ids and catalogue | `NODE_PLUGIN_IDS`, `nodePluginIdsOf`, `NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL`, `OPEN_API_FIXTURE_SPEC` (canned OpenAPI document for the generic `openApi` plugin), `parseBasicAuthorization` (decodes a Basic `Authorization` header an echo record holds) | `src/datasource/node-plugins.ts` | | negative and counter reads, local storage | `expectTextStays`, `countAfterEquals`, `parseCounter`, `rawLocalStorage` | `src/logic/helpers.ts` | | media | `PNG_RED`, `PNG_BLUE`, `WAV`, `WEBM`, `MP4`, `PDF`, `PDF_RAW_B64` | `src/media.ts` | | security actors, quarantine, answers, tokens | `Actor`, `adminOfApiUser`, `joinWorkspace`, `makeDeveloper`, `makeAdmin`, `grantApp`, `seedPrivateApp`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `securityTestDetails`, `securityCandidateDetails`, `expectAnswer`, `expectDeniedAs`, `forgeApiKeyToken`, `forgeUnsignedToken`, `withRandomSignature`, `tokenIsSignedWith`, `superAdminCredentials`, `SUPER_ADMIN_ENV`, `enterpriseAdmin` (ENTERPRISE stack: an actor the super admin makes admin of the one workspace), `echoTargetPath`, `echoReadPrefix`, `echoBaseUrl`, `recordsContain` (requests the SERVER makes, read back from the HTTP echo sidecar: the `echo` fixture gives a test its own target `url` and `received()`; a denial must follow a positive control that the echo does receive from that path; compare a secret with `recordsContain(...)` as a boolean, never as a matcher's value) (the `actor`, `superAdmin` and `echo` fixtures are in `src/fixtures.ts`; the raw-answer helper `apiRaw` and the other security API helpers are in `src/api/client.ts`) | `src/security/actors.ts`, `scene.ts`, `quarantine.ts`, `assertions.ts`, `tokens.ts`, `super-admin.ts`, `enterprise.ts`, `echo.ts` | diff --git a/e2e/README.md b/e2e/README.md index 164abcfeeb..df3bb21db9 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify and the generic Open API plugin run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), D5 to D7, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce and Supabase Management API run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), D5 to D8, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -47,7 +47,7 @@ lifecycle (insert, save, publish, load) is covered by S1 when `@insert-all` runs does not apply to these requests (they are made by the backend), so the echo is the only host the tests point the backend at; the sidecar starts in every run, also on the enterprise profile; an echo test that finds nothing proves nothing unless a positive control shows that the echo does receive from that path (every denial row of `outbound*.spec.ts` has one). The app and runner containers resolve `e2e-echo` through `--add-host e2e-echo:` (read with `docker inspect` after the sidecar starts), not DNS: measured with the sidecar stopped, `getent hosts e2e-echo` in the app container printed the sidecar's network IP and `curl` failed with "No route to host" (the runner got ECONNREFUSED on the same IP); without the entry the name resolved to a LAN address on the measuring host. -- **Canned answers** (the same sidecar): `POST /__e2e/answers { prefix, status, contentType, body }` makes requests whose path starts with `prefix` (any method, query string ignored) get that answer instead of `{}`; they are still recorded. One entry per prefix (the latest wins), the longest matching prefix answers, 10000 entries at most (the oldest dropped); an invalid entry (prefix not starting with `/`, status outside 100-599, a non-string body or content type, a body over 65536 bytes) is 400 and changes nothing. `EchoTarget.answer(subPath, { status, body, contentType })` of the `echo` fixture sets one below the test's own target; it uses Node's `fetch` (a canned answer may hold a token). `src/lifecycle/mock-idp.ts` builds a mock Generic OAuth provider on it (token and user-info endpoints on the test's target); the server calls them itself, the browser never visits the provider, so a test signs in with the client's own call `POST /api/auth/tp/login` and a made-up code. +- **Canned answers** (the same sidecar): `POST /__e2e/answers { prefix, status, contentType, body }` makes requests whose path starts with `prefix` (any method, query string ignored) get that answer instead of `{}`; they are still recorded. One entry per prefix (the latest wins), the longest matching prefix answers, 10000 entries at most (the oldest dropped); an invalid entry (prefix not starting with `/`, status outside 100-599, a non-string body or content type, a body over 65536 bytes) is 400 and changes nothing. An entry may carry `barrier: { prefix, count, timeoutMs }` (prefix starting with `/`, integer count 2 to 100, integer timeoutMs 1 to 30000, else 400): the answer is withheld until `count` requests answered by entries with that barrier prefix are waiting at once, then all are answered together; if the group does not fill within `timeoutMs` of its first waiting request, they all get 504 `barrier timeout`. So receiving the canned answers proves the requests were waiting at the echo together. `EchoTarget.answer(subPath, { status, body, contentType, barrier: { subPath, count, timeoutMs } })` of the `echo` fixture sets one below the test's own target (the barrier's `subPath` is below the target too); it uses Node's `fetch` (a canned answer may hold a token). `src/lifecycle/mock-idp.ts` builds a mock Generic OAuth provider on it (token and user-info endpoints on the test's target); the server calls them itself, the browser never visits the provider, so a test signs in with the client's own call `POST /api/auth/tp/login` and a made-up code. - **Mail sink** (the same sidecar, SMTP on port 2525; the app gets `LOWCODER_ADMIN_SMTP_HOST=e2e-echo`, port 2525, no login, no STARTTLS): accepts every mail the SERVER sends (password reset, invitation) and delivers it nowhere. One record `{ from, to[], data }` per message (`data` is the message as latin1 text, dot-stuffing undone; the 65536-byte cut counts the bytes as sent, before dot-stuffing is undone; 10000 records kept); `GET /__e2e/mails?to=

` answers those sent to an address @@ -209,7 +209,7 @@ e2e/ fixtures/sql/init.sql PostgreSQL data: items, products, notes fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition) + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb`, `jira`, `datadog`, `woocommerce`, `supabaseApi` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each) src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -251,15 +251,16 @@ Test titles carry these ids. - D5 the Turso and Slack plugins of node-service against the echo sidecar: a Turso query sends one Hrana pipeline and answers its rows, `includeRaw` answers values and raw, a non-OK answer and an `error` result fail the query (the latter prints `[object Object]`, NSD-1 candidate), the published view after a click; a Slack query posts the form payload to the webhook (`@node-service`; the request shape and the answer's path into the app, not the vendor service). - D6 the GitLab and Shopify GraphQL plugins of node-service against the echo sidecar: a GitLab query posts the query, the variables and every header (data source, query and the access token), a GraphQL error answer fails the query, the published view after a click; a Shopify query reaches the endpoint, and the header the query sets does not (NSD-2 candidate) (`@node-service`; the request shape and the answer's path into the app, not the vendor service). - D7 the generic Open API plugin of node-service against the echo sidecar: the data source form's dynamic config reads the OpenAPI document from its URL (the echo serves a canned document) and answers the spec and the key field, an operation runs against the server URL with the key in the header the document names, the key comes from the data source (no key, no header), an error status answers its body as a successful result (NSD-4 candidate), the published view after a click, the dynamic config answer is cached in memory per request body, with no expiry (observation) (`@node-service`). +- D8 the Open API wrapper plugins of node-service with a server URL (CouchDB, Jira, Datadog, WooCommerce, Supabase Management API) against the echo sidecar: one read-only operation each reaches the server URL (the target's path survives as the base path) with its credentials and answers the canned data, CouchDB JWT credential alone and with a Basic one (observation), WooCommerce server URL forms and refusal of v1/v2, a trailing slash after the API path doubles it (NSD-5 candidate), concurrent queries against two server URLs each reach their own server (`@node-service`). - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`, after this branch's security fixes; this is a static listing, not a Docker run. A combined final run against an image built from this branch (tag `secfix-combined-e2e`) has since confirmed pass/fail for every scenario named in the per-defect rows below: 693/696 default tests passed, the 3 failures pre-existing or unrelated suite drift (documented in their own rows below)): -default **739 tests in 110 files**; with `E2E_INCLUDE_QUARANTINE=1` **752 in 111**; with `E2E_INCLUDE_SUPERADMIN=1` **744 in 110**; with both of those **757 in 111**; -with `E2E_INCLUDE_INSERT_ALL=1` **851 in 111**; with all three opt-in variables **869 in 112** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: +default **754 tests in 111 files**; with `E2E_INCLUDE_QUARANTINE=1` **767 in 112**; with `E2E_INCLUDE_SUPERADMIN=1` **759 in 111**; with both of those **772 in 112**; +with `E2E_INCLUDE_INSERT_ALL=1` **866 in 112**; with all three opt-in variables **884 in 113** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 43 (the 18 unit tests of `foundation/node-plugins.spec.ts`, D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e and D7a to D7f; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 56 (the 20 unit tests of `foundation/node-plugins.spec.ts`, D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f and D8a to D8i; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -308,7 +309,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | editor/js-query.spec.ts | a JS query written in the editor runs | @core | 1 | | editor/drop-size.spec.ts | a component dropped right after ready has width above 0 (D-5) | @quarantine | 1 | -### datasource (20) +### datasource (31) | File | Proves | Tags | Tests | |---|---|---|---| @@ -320,6 +321,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/plugin-turso-slack.spec.ts | D5: Turso and Slack against the echo sidecar (the data source URL is the test's own echo target). D5a a Turso query sends one POST of `{requests: [execute, close]}` to `/v2/pipeline` with `Authorization: Bearer ` and answers the rows keyed by column name (an `integer` cell as a number), D5b `includeRaw` answers `{values, raw}`, D5c a 500 answer fails the query (`Endpoint returned 500`), D5d an `error` result fails the query with `Cannot parse result, received error: [object Object]` (NSD-1 candidate: the server's message is lost), D5e the published view shows the row after a click, D5f a Slack query posts `payload=` as `application/x-www-form-urlencoded;charset=UTF-8` to the webhook path and answers the webhook's text. Not covered: the `libsql://` rewrite (the echo does not speak TLS) | @node-service | 6 | | datasource/plugin-graphql.spec.ts | D6: GitLab and Shopify against the echo sidecar (the endpoint is the test's own echo target plus `/api/graphql`). D6a a GitLab query posts one JSON body `{query, variables: {n: 3}, operationName}` (the variable's text `3` arrives as the number 3) with `PRIVATE-TOKEN`, the data source header and the query header, and answers the `data` member, D6b a `{"errors":[...]}` answer fails the query with `: `, D6c a Shopify query posts `{query, variables: {}}` and answers the `data` member (control), D6d the header the Shopify query sets reaches the echo neither as name nor as value (NSD-2 candidate), D6e the published view shows the GitLab answer after a click | @node-service | 5 | | datasource/plugin-openapi.spec.ts | D7: the generic Open API plugin against the echo sidecar (spec URL `/spec.json`, server URL `/api`; the document is `OPEN_API_FIXTURE_SPEC`: `GET /items`, operation `listItems`, parameter `q`, API key header `X-E2E-Key`, placeholder server). D7a the dynamic config call (`path` `$.dataSourceConfig.extra`) answers `[{data: {spec}, extraParams}]` with the key field `E2EKeyAuth.value` labelled `X-E2E-Key` and fetches the document with exactly one GET, D7b `listItems` sends `GET /api/items?q=` with `x-e2e-key` and answers the canned `[{id: 1}]`, D7c a data source with an empty `dynamicParamsConfig` sends no key header, D7d a canned 404 `{"message":"e2e-missing"}` is answered as `success: true`, `queryCode: "OK"`, data the 404 body (NSD-4 candidate), D7e the published view shows the first item's id only after the click (echo 0 requests before, exactly 1 after), D7f the same dynamic config request answers from the cache after the document changed on the echo (one fetch), while a request with another body fetches again; the cache is an in-process object keyed on path, query and body with no expiry (observation) | @node-service | 6 | +| datasource/plugin-openapi-wrappers-data.spec.ts | D8: CouchDB, Jira, Datadog, WooCommerce and the Supabase Management API against the echo sidecar (server URL ``, one read-only operation of each bundled document). D8a couchdb `GET /_all_dbs` with `Authorization: Basic` of the configured user and password, D8b jira `GET /rest/api/3/myself` with Basic, D8c datadog `GET /api/v1/validate` with `dd-api-key` and `dd-application-key`, D8d woocommerce `GET /wp-json/wc/v3/products?context=view&order=asc&orderby=date&status=any&type=simple&stock_status=instock` with Basic, D8e supabaseApi `GET /v1/projects` with `Authorization: Bearer `; each asserts echo empty before, exactly one request (method, full path and query, no body, the complete header set) and the canned body as the query's data; D8f couchdb: a JWT credential alone is sent as `Authorization`, with a Basic credential too only the Basic one is (observation), each request asserted completely; D8g woocommerce: a plain, a slash-terminated and an already `/wp-json/wc/v3` server URL each give the API path once, `/wc/v1` and `/wc/v2` are refused with `only woocommerce api v3 is supported` and send nothing; D8h woocommerce: a server URL ending in `/wp-json/wc/v3/` gets the API path twice (NSD-5 candidate); D8i couchdb, woocommerce and datadog: 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 11 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -464,13 +466,13 @@ first makes sure some admin exists (accepting both answers), so none depends on SEC-R09d (D-38) left the quarantine: the check took the workspace of the first id of a `HashSet`; each id is now decided in its own workspace (Java unit and MongoDB integration tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)). Accounting of the earlier 3.0.0 run `E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --workers=4 --reporter=list --grep "@quarantine" tests/security` (measured before the `@superadmin` tag existed and before the reassessment, so it listed 44 tests, 19 of which have since left the quarantine): 44 listed, 43 failed, 1 passed (SEC-R09d); the two quarantined tests of `foundation/security-helpers.spec.ts` are outside that folder. -### foundation (279 default, 282 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) +### foundation (283 default, 286 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) | File | Proves | Tags | Tests | |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value) | @node-service | 18 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), and `parseBasicAuthorization` | @node-service | 20 | | foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources) | none | 27 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | @@ -483,7 +485,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | foundation/d3-threshold-reporter.spec.ts | D-3 gate verdicts of the reporter | none | 9 | | foundation/security-helpers.spec.ts | the security helpers of `src/api/client.ts`, `src/security/actors.ts` and `src/security/scene.ts` against the stack (`apiRaw`, `actor`, `joinWorkspace`, `makeDeveloper`, grants, folders, datasources, API keys, bundles, `publishBundle`, `setBundlePublicToAll`, `signIn`, `getApp`, `listGroupMembers`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `adminOfApiUser`, the `superAdmin` fixture, ...); 2 tests are `@quarantine` (D-45 API-key delete, D-46 bundle recycle) | none, @superadmin for 1, @quarantine for 2 | 37 default + 1 `@superadmin` + 2 quarantined | | foundation/security-pages.spec.ts | the page objects `SettingPage` (settings sidebar, members rows and role selects, provider page) and `DatasourcePage` (the form's save answer) as admin, developer and plain member, and `AppViewPage.openAndAwaitQuery` (the status of the query a seeded app runs on load) | none | 4 | -| foundation/security-echo.spec.ts | the echo sidecar (`scripts/echo-server.js` started on a loopback port: record and read back, per-target prefixes, control paths, body cut, canned answers) and `src/security/echo.ts`, `n8nDatasourceBody`, `npmRegistryPath` (no stack) | none | 17 | +| foundation/security-echo.spec.ts | the echo sidecar (`scripts/echo-server.js` started on a loopback port: record and read back, per-target prefixes, control paths, body cut, canned answers, barriers) and `src/security/echo.ts`, `n8nDatasourceBody`, `npmRegistryPath` (no stack) | none | 19 | | foundation/security-api-raw.spec.ts | `apiRaw` against a local server: status, code, body, params, request and response headers; `executeAppQueryRaw`'s path (no stack) | none | 8 | | foundation/security-quarantine.spec.ts | `securityTestDetails`, `securityCandidateDetails`, `lifecycleTestDetails`, `lifecycleCandidateDetails` and the two quarantine maps (no stack) | none | 16 | | foundation/lifecycle-pages.spec.ts | `ProfilePage`, `ProfileModal`, `UserMenu` (profile, create and switch workspace), `ApiKeysCard`, `WorkspacesPage`, `GroupsPage`, `ShareDialog`, `SettingPage` (invite link, operations), `PasswordRecoveryPage`, `LoginPage.forgotPasswordLink`, the invite dialog of `SettingPage` (send, notice), `ProvidersPage`, `ProfilePage.infoCount`, `SettingPage.openDetailOf`, the navigation and tour locators of `AppListPage` (`tourClose` on a UI sign-up) | none | 14 | @@ -514,6 +516,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-3 candidate | the DuckDB plugin answers rows keyed by the column position, not the column name (`SELECT 42 AS answer` arrives as `{"0": 42}`): `getRows()` answers arrays and `serializeBigInts` copies `Object.entries(row)`; measured on 3.0.0-e2e and 3.0.1-e2e. An app cannot read `row.answer`. The id is provisional until the owner assigns one | `datasource/plugin-duckdb.spec.ts` D4a to D4c assert today's keys (characterisation, default run), annotation `{type:"defect", description:"NSD-3 candidate"}`; they change when the plugin keys rows by name | | NSD-2 candidate | the Shopify plugin reads the query's headers and passes `{}` on, and its data source has only `endpoint`: it cannot send Shopify's access token (`X-Shopify-Access-Token`); measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-graphql.spec.ts` D6d asserts today's behaviour after a control that the request did reach the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-2 candidate"}`; it changes when the query's headers are forwarded | | NSD-4 candidate | the generic Open API plugin returns the body of an error status answer as the query result (`runOpenApi` catch, `e.response.body`): a canned 404 `{"message":"e2e-missing"}` is reported as `success: true`, `queryCode: "OK"`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi.spec.ts` D7d asserts today's behaviour after a control that the request reached the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-4 candidate"}`; it changes when an error status fails the query | +| NSD-5 candidate | the WooCommerce plugin appends `wp-json/wc/v3` to a server URL unless it ends exactly in `/wc/v3`, so a server URL copied with a trailing slash (`/wp-json/wc/v3/`) is requested at `/wp-json/wc/v3/wp-json/wc/v3/products`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-data.spec.ts` D8h asserts today's behaviour (characterisation, default run), annotation `{type:"defect", description:"NSD-5 candidate"}`; it changes when a trailing slash is accepted | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/fixtures/dsl/plugins/couchdb/couchdbDatasource.json b/e2e/fixtures/dsl/plugins/couchdb/couchdbDatasource.json new file mode 100644 index 0000000000..a40517e3ff --- /dev/null +++ b/e2e/fixtures/dsl/plugins/couchdb/couchdbDatasource.json @@ -0,0 +1,12 @@ +{ + "name": "couchdb", + "type": "couchdb", + "datasourceConfig": { + "serverURL": "http://placeholder.invalid", + "BasicAuth.username": "placeholder", + "BasicAuth.password": "placeholder", + "JwtAuth.value": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/couchdb/couchdbQuery.json b/e2e/fixtures/dsl/plugins/couchdb/couchdbQuery.json new file mode 100644 index 0000000000..8d763edee6 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/couchdb/couchdbQuery.json @@ -0,0 +1,21 @@ +{ + "compType": "couchdb", + "comp": { + "actionName": "allDBs", + "action": { + "query_@_descending": "", + "query_@_endkey": "", + "query_@_end_key": "", + "query_@_limit": "", + "query_@_skip": "", + "query_@_startkey": "", + "query_@_start_key": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/datadog/datadogDatasource.json b/e2e/fixtures/dsl/plugins/datadog/datadogDatasource.json new file mode 100644 index 0000000000..96e5ae9fa9 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/datadog/datadogDatasource.json @@ -0,0 +1,11 @@ +{ + "name": "datadog", + "type": "datadog", + "datasourceConfig": { + "serverURL": "http://placeholder.invalid", + "apiKeyAuth.value": "placeholder", + "appKeyAuth.value": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/datadog/datadogQuery.json b/e2e/fixtures/dsl/plugins/datadog/datadogQuery.json new file mode 100644 index 0000000000..86d3c51768 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/datadog/datadogQuery.json @@ -0,0 +1,15 @@ +{ + "compType": "datadog", + "comp": { + "actionName": "get_api_v1_validate", + "action": { + "header_@_Accept": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/jira/jiraDatasource.json b/e2e/fixtures/dsl/plugins/jira/jiraDatasource.json new file mode 100644 index 0000000000..8df7976362 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/jira/jiraDatasource.json @@ -0,0 +1,11 @@ +{ + "name": "jira", + "type": "jira", + "datasourceConfig": { + "serverUrl": "http://placeholder.invalid", + "basicAuth.username": "placeholder", + "basicAuth.password": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/jira/jiraQuery.json b/e2e/fixtures/dsl/plugins/jira/jiraQuery.json new file mode 100644 index 0000000000..c9ca3cbc24 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/jira/jiraQuery.json @@ -0,0 +1,15 @@ +{ + "compType": "jira", + "comp": { + "actionName": "getCurrentUser", + "action": { + "query_@_expand": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/supabaseApi/supabaseApiDatasource.json b/e2e/fixtures/dsl/plugins/supabaseApi/supabaseApiDatasource.json new file mode 100644 index 0000000000..1d363292fe --- /dev/null +++ b/e2e/fixtures/dsl/plugins/supabaseApi/supabaseApiDatasource.json @@ -0,0 +1,10 @@ +{ + "name": "supabaseApi", + "type": "supabaseApi", + "datasourceConfig": { + "serverURL": "http://placeholder.invalid", + "bearerAuth.value": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/supabaseApi/supabaseApiQuery.json b/e2e/fixtures/dsl/plugins/supabaseApi/supabaseApiQuery.json new file mode 100644 index 0000000000..5cb87ac311 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/supabaseApi/supabaseApiQuery.json @@ -0,0 +1,13 @@ +{ + "compType": "supabaseApi", + "comp": { + "actionName": "v1_list_all_projects", + "action": {}, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/woocommerce/woocommerceDatasource.json b/e2e/fixtures/dsl/plugins/woocommerce/woocommerceDatasource.json new file mode 100644 index 0000000000..fc462b0c2b --- /dev/null +++ b/e2e/fixtures/dsl/plugins/woocommerce/woocommerceDatasource.json @@ -0,0 +1,11 @@ +{ + "name": "woocommerce", + "type": "woocommerce", + "datasourceConfig": { + "serverURL": "http://placeholder.invalid", + "basicAuth.username": "placeholder", + "basicAuth.password": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/woocommerce/woocommerceQuery.json b/e2e/fixtures/dsl/plugins/woocommerce/woocommerceQuery.json new file mode 100644 index 0000000000..3a370d4a54 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/woocommerce/woocommerceQuery.json @@ -0,0 +1,44 @@ +{ + "compType": "woocommerce", + "comp": { + "actionName": "get_products", + "action": { + "query_@_context": "view", + "query_@_page": "", + "query_@_per_page": "", + "query_@_search": "", + "query_@_after": "", + "query_@_before": "", + "query_@_modified_after": "", + "query_@_modified_before": "", + "query_@_dates_are_gmt": "", + "query_@_exclude": "[]", + "query_@_include": "[]", + "query_@_offset": "", + "query_@_order": "asc", + "query_@_orderby": "date", + "query_@_parent": "[]", + "query_@_parent_exclude": "[]", + "query_@_slug": "", + "query_@_status": "any", + "query_@_type": "simple", + "query_@_sku": "", + "query_@_featured": "", + "query_@_category": "", + "query_@_tag": "", + "query_@_shipping_class": "", + "query_@_attribute": "", + "query_@_attribute_term": "", + "query_@_on_sale": "", + "query_@_min_price": "", + "query_@_max_price": "", + "query_@_stock_status": "instock" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/scripts/echo-server.js b/e2e/scripts/echo-server.js index cc1cdd6859..cdb9b69aa6 100644 --- a/e2e/scripts/echo-server.js +++ b/e2e/scripts/echo-server.js @@ -16,6 +16,11 @@ * the longest matching prefix answers, at most MAX_RECORDS entries are kept (the oldest are dropped). The control answer is 204; an * invalid entry (prefix not starting with "/", status outside 100-599, a non-string body or content type, body over MAX_BODY_BYTES) is 400. * Every other path keeps the `{}` answer, so the outbound tests are unaffected. + * An entry may also carry `barrier: { prefix, count, timeoutMs }` (prefix starting with "/", integer count 2-MAX_BARRIER_COUNT, integer + * timeoutMs 1-MAX_BARRIER_TIMEOUT_MS; anything else is 400). The answer is then WITHHELD (the request is recorded on arrival) until `count` + * requests answered by entries with that same barrier prefix are waiting at once; then all of them are answered together. If the count is + * not reached within timeoutMs of the first waiting request, every waiting request is answered 504 `barrier timeout` instead. So a + * test that gets the canned answers has proved that `count` requests were waiting at the echo at the same time; a group that never fills fails loudly. * * It is also the run's mail sink: a minimal SMTP listener on MAIL_PORT (default 2525) accepts every message the SERVER * sends (password reset, invitation) and delivers it nowhere. @@ -43,6 +48,9 @@ const HEALTH_PATH = "/__e2e/health"; const REQUESTS_PATH = "/__e2e/requests"; const MAILS_PATH = "/__e2e/mails"; const ANSWERS_PATH = "/__e2e/answers"; +const MAX_BARRIER_COUNT = 100; +const MAX_BARRIER_TIMEOUT_MS = 30000; +const STATUS_GATEWAY_TIMEOUT = 504; const STATUS_NO_CONTENT = 204; const STATUS_BAD_REQUEST = 400; const MIN_HTTP_STATUS = 100; @@ -61,14 +69,64 @@ const TERMINATOR_HOLD_BACK_BYTES = DATA_TERMINATOR.length - 1; const records = []; /** @type {{ from: string, to: string[], data: string }[]} */ const mails = []; -/** @type {Map} canned answers by path prefix, oldest first */ +/** @type {Map} canned answers by path prefix, oldest first */ const answers = new Map(); +/** @type {Map} requests held at a barrier, by barrier prefix */ +const barrierGroups = new Map(); function send(response, status, contentType, text) { response.writeHead(status, { "content-type": contentType }); response.end(text); } +function validBarrier(barrier) { + return ( + barrier !== null && + typeof barrier === "object" && + typeof barrier.prefix === "string" && + barrier.prefix.startsWith("/") && + Number.isInteger(barrier.count) && + barrier.count >= 2 && + barrier.count <= MAX_BARRIER_COUNT && + Number.isInteger(barrier.timeoutMs) && + barrier.timeoutMs >= 1 && + barrier.timeoutMs <= MAX_BARRIER_TIMEOUT_MS + ); +} + +/** Holds a request whose canned answer has a barrier; answers the whole group when it is full, or 504 when its timeout runs out first. */ +function holdAtBarrier(response, canned) { + const { prefix, count, timeoutMs } = canned.barrier; + let group = barrierGroups.get(prefix); + if (!group) { + group = { waiting: [], timer: setTimeout(() => releaseBarrier(prefix, false), timeoutMs) }; + barrierGroups.set(prefix, group); + } + group.waiting.push({ response, canned }); + if (group.waiting.length >= count) { + releaseBarrier(prefix, true); + } +} + +function releaseBarrier(prefix, full) { + const group = barrierGroups.get(prefix); + if (!group) { + return; + } + clearTimeout(group.timer); + barrierGroups.delete(prefix); + for (const { response, canned } of group.waiting) { + if (response.writableEnded) { + continue; + } + if (full) { + send(response, canned.status, canned.contentType, canned.body); + } else { + send(response, STATUS_GATEWAY_TIMEOUT, "text/plain", "barrier timeout"); + } + } +} + /** Validates and stores one canned answer; returns whether it was valid. */ function storeAnswer(text) { let entry; @@ -87,12 +145,13 @@ function storeAnswer(text) { entry.status <= MAX_HTTP_STATUS && typeof entry.contentType === "string" && typeof entry.body === "string" && - Buffer.byteLength(entry.body) <= MAX_BODY_BYTES; + Buffer.byteLength(entry.body) <= MAX_BODY_BYTES && + (entry.barrier === undefined || validBarrier(entry.barrier)); if (!valid) { return false; } answers.delete(entry.prefix); - answers.set(entry.prefix, { status: entry.status, contentType: entry.contentType, body: entry.body }); + answers.set(entry.prefix, { status: entry.status, contentType: entry.contentType, body: entry.body, barrier: entry.barrier }); if (answers.size > MAX_RECORDS) { answers.delete(answers.keys().next().value); } @@ -165,6 +224,9 @@ function handleRecorded(request, response) { records.splice(0, records.length - MAX_RECORDS); } const canned = cannedAnswerFor(request.url); + if (canned?.barrier) { + return holdAtBarrier(response, canned); + } if (canned) { return send(response, canned.status, canned.contentType, canned.body); } diff --git a/e2e/src/datasource/node-plugins.ts b/e2e/src/datasource/node-plugins.ts index 5d388e2bb4..9125f9fbad 100644 --- a/e2e/src/datasource/node-plugins.ts +++ b/e2e/src/datasource/node-plugins.ts @@ -117,3 +117,30 @@ export const OPEN_API_FIXTURE_SPEC = { }, }, } as const; + +/** The scheme word of an HTTP Basic `Authorization` header value (RFC 7617). */ +export const BASIC_AUTH_SCHEME = "Basic"; + +/** The user name and password of an HTTP Basic `Authorization` header value. */ +export interface BasicCredentials { + user: string; + password: string; +} + +/** + * Decodes an `Authorization` header value of the form `Basic ` (RFC 7617: the user name ends at the first + * colon, the password may hold colons). Returns `undefined` for anything else: no header, a repeated header (an array), another + * scheme, text that is not canonical base64, or a decoded text without a colon. The tests compare what a plugin sent with the + * credentials they configured, so a failing decode must read as "not Basic credentials", never as an empty user. + */ +export function parseBasicAuthorization(header: string | string[] | undefined): BasicCredentials | undefined { + if (typeof header !== "string") return undefined; + const prefix = `${BASIC_AUTH_SCHEME} `; + if (!header.startsWith(prefix)) return undefined; + const encoded = header.slice(prefix.length); + const decoded = Buffer.from(encoded, "base64").toString("utf8"); + if (Buffer.from(decoded, "utf8").toString("base64") !== encoded) return undefined; + const colon = decoded.indexOf(":"); + if (colon < 0) return undefined; + return { user: decoded.slice(0, colon), password: decoded.slice(colon + 1) }; +} diff --git a/e2e/src/fixtures.ts b/e2e/src/fixtures.ts index 0831ca4cbc..d8e5512147 100644 --- a/e2e/src/fixtures.ts +++ b/e2e/src/fixtures.ts @@ -198,7 +198,7 @@ export const test = base.extend({ answer: async (subPath, canned) => { const response = await fetch(`${baseURL}${ECHO_PATHS.ANSWERS}`, { method: "POST", - body: JSON.stringify({ prefix: `${path}${subPath}`, status: canned.status, contentType: canned.contentType ?? "application/json", body: canned.body }), + body: JSON.stringify({ prefix: `${path}${subPath}`, status: canned.status, contentType: canned.contentType ?? "application/json", body: canned.body, barrier: canned.barrier && { prefix: `${path}${canned.barrier.subPath}`, count: canned.barrier.count, timeoutMs: canned.barrier.timeoutMs } }), }); if (response.status !== 204) { throw new Error(`the echo sidecar refused the canned answer of ${subPath} with ${response.status}`); diff --git a/e2e/src/security/echo.ts b/e2e/src/security/echo.ts index 8b8f17b65d..6055480b31 100644 --- a/e2e/src/security/echo.ts +++ b/e2e/src/security/echo.ts @@ -88,4 +88,10 @@ export interface CannedAnswer { status: number; body: string; contentType?: string; + /** + * Withholds the answer until `count` requests answered with a barrier of the same `subPath` are waiting at once (so the answer + * proves they were waiting at the echo together); if that does not happen within `timeoutMs` of the first waiting request, every waiting + * request is answered 504 `barrier timeout`. `subPath` is below the target and starts with "/", e.g. "/" for the whole target. + */ + barrier?: { subPath: string; count: number; timeoutMs: number }; } diff --git a/e2e/tests/datasource/plugin-openapi-wrappers-data.spec.ts b/e2e/tests/datasource/plugin-openapi-wrappers-data.spec.ts new file mode 100644 index 0000000000..bac38021e8 --- /dev/null +++ b/e2e/tests/datasource/plugin-openapi-wrappers-data.spec.ts @@ -0,0 +1,423 @@ +import { randomBytes } from "node:crypto"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, TAGS } from "../../src/constants"; +import { appDsl, nodePluginQuery } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { parseBasicAuthorization, type BasicCredentials } from "../../src/datasource/node-plugins"; +import { expect, test } from "../../src/fixtures"; +import { recordsContain, type EchoRecord, type EchoTarget } from "../../src/security/echo"; + +/** + * D8: the plugins of node-service that wrap one bundled OpenAPI document and take a server URL: CouchDB, Jira, Datadog, + * WooCommerce and the Supabase Management API (`server/node-service/src/plugins/{couchdb,jira,datadog,woocommerce,supabaseApi}/index.ts`, + * all running `runOpenApi` of `plugins/openApi/index.ts`). The server URL is the test's own target on the echo sidecar, so the + * tests prove the request each plugin builds (method, path below the server URL, query, auth header) and the path of a canned + * answer into the app. They are NOT a fidelity test of any of the services. + * + * Each plugin runs one read-only operation of its bundled document: + * - CouchDB `allDBs`: `GET /_all_dbs` (`CouchDB-3.1.1-resolved.json`, a Swagger 2 document: the server URL is split into host, + * base path and scheme, so the `/t/` prefix of the target has to survive as the base path); + * - Jira `getCurrentUser`: `GET /rest/api/3/myself` (`jira.spec.json`); + * - Datadog `get_api_v1_validate`: `GET /api/v1/validate` (`datadog.spec.yaml`); + * - WooCommerce `get_products`: `GET /products` below `/wp-json/wc/v3` (`woocommerce-spec.json`, `prepareServerUrl`); + * - Supabase `v1_list_all_projects`: `GET /v1/projects` (`supabaseApi.spec.json`). + * + * The plugins keep their parsed document in a module-level object, and `runOpenApi` rewrites its server URL in place. D8i submits + * several queries together and checks that each reaches its own server URL with its own data. The echo withholds every answer (a + * barrier) until all requests of the test are waiting at it, so the canned data reaches the queries only if all of the requests + * were waiting at the echo at the same time; a group that never fills is answered 504 and fails the test. That says nothing about + * what happens inside node-service while the requests are built. + */ +const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; + +/** + * Observation: a CouchDB data source with both a Basic and a JWT credential sends only the Basic one, because both set the + * `Authorization` header and the document lists them as one combined requirement (D8f). + */ +const COUCHDB_AUTH_OBSERVATION = { type: "observation", description: "couchdb with Basic and JWT credentials sends only the Basic Authorization header" } as const; +const COUCHDB_AUTH_DETAILS = { annotation: COUCHDB_AUTH_OBSERVATION }; + +/** + * Candidate defect: a WooCommerce server URL that already ends in `/wp-json/wc/v3/` (with the trailing slash) is not recognised by + * `prepareServerUrl`, which then appends `wp-json/wc/v3` a second time. + */ +const WOO_TRAILING_SLASH_DEFECT = { type: "defect", description: "NSD-5 candidate" } as const; +const WOO_TRAILING_SLASH_DETAILS = { annotation: WOO_TRAILING_SLASH_DEFECT }; + +const HTTP_OK = 200; +const QUERY_CODE_OK = "OK"; +const QUERY_CODE_FAILED = "FAILED"; +const JSON_CONTENT_TYPE = "application/json"; +const MARKER_BYTES = 4; +const QUERY_ID = "q1"; +const QUERY_NAME = "q"; + +/** Request headers of node-service's HTTP client (`node-fetch` through `common/fetch.ts`) that every plugin request carries, measured on the images `3.0.0-e2e` and `3.0.1-e2e`. */ +const NODE_FETCH_USER_AGENT = "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"; +const ACCEPT_ENCODING = "gzip,deflate"; +const CONNECTION_CLOSE = "close"; + +const WOO_API_PATH = "/wp-json/wc/v3"; +/** + * The query string of the recorded WooCommerce action (measured): the editor saved the defaults of the operation's enumerated + * parameters (`context`, `order`, `orderby`, `status`, `type`, `stock_status`); the empty ones are not sent. + */ +const WOO_QUERY = "context=view&order=asc&orderby=date&status=any&type=simple&stock_status=instock"; +const WOO_REFUSAL_MESSAGE = "only woocommerce api v3 is supported"; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +function canned(body: unknown): { status: number; contentType: string; body: string } { + return { status: HTTP_OK, contentType: JSON_CONTENT_TYPE, body: JSON.stringify(body) }; +} + +function onlyRecord(records: EchoRecord[], description: string): EchoRecord { + expect(records, description).toHaveLength(1); + return records[0] as EchoRecord; +} + +/** The records whose path (below the echo target) starts with `subPath` followed by `/`. */ +function recordsUnder(records: EchoRecord[], echo: EchoTarget, subPath: string): EchoRecord[] { + return records.filter((record) => record.path.startsWith(`${echo.path}${subPath}/`)); +} + +/** A data source from the recording with `config` merged over it (a key set to `undefined` is left out of the request body). */ +async function wrapperDatasource(page: Page, apiUser: RegisteredUser, plugin: string, config: Record): Promise { + return createNodePluginDatasource(page.request, { orgId: apiUser.orgId, recorded: recordedPluginDatasource(plugin), config }); +} + +/** A saved app with the recorded query of `plugin` on the data source (not published: the draft runs with `viewMode: false`). */ +async function wrapperApp(page: Page, apiUser: RegisteredUser, plugin: string, datasourceId: string): Promise { + const query = nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery(plugin) }); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: `e2e-${plugin}`, dsl: appDsl([], { queries: [query] }) }); + return appId; +} + +async function runDraft(page: Page, appId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId: QUERY_ID, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +function expectSucceeded(answer: RawAnswer): void { + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); +} + +/** The request headers a plugin request carries besides its credentials: `host` is the echo's. */ +function commonHeaders(echo: EchoTarget): Record { + return { + accept: JSON_CONTENT_TYPE, + "user-agent": NODE_FETCH_USER_AGENT, + "accept-encoding": ACCEPT_ENCODING, + host: new URL(echo.url).host, + connection: CONNECTION_CLOSE, + }; +} + +/** + * Asserts one recorded request completely: method `GET`, the exact path and query, no body, and the exact header set (the headers + * every plugin request carries plus the credentials: a decoded Basic `Authorization`, or the exact credential headers). + */ +function expectRequest(record: EchoRecord, echo: EchoTarget, expected: { path: string; basic?: BasicCredentials; headers?: Record }, label: string): void { + expect(record.method, `${label}: the method`).toBe("GET"); + expect(record.path, `${label}: the path and query`).toBe(expected.path); + expect(record.body, `${label}: no body`).toBe(""); + const { authorization, ...otherHeaders } = record.headers; + if (expected.basic) { + expect(parseBasicAuthorization(authorization), `${label}: the Authorization header decodes to the configured user and password`).toEqual(expected.basic); + expect(otherHeaders, `${label}: every other header`).toEqual(commonHeaders(echo)); + } else { + expect({ authorization, ...otherHeaders }, `${label}: the credential headers and every other header`).toEqual({ ...commonHeaders(echo), ...expected.headers }); + } +} + +/** What a row configures as the credentials, and what they must look like on the wire. */ +interface AuthSetup { + /** The data source keys of the credentials, as the form stores them. */ + config: Record; + /** Set for Basic auth: the user and password the `Authorization` header must decode to. */ + basic?: BasicCredentials; + /** Set for API key and bearer auth: the exact header names and values (lower-case names, as the echo records them). */ + headers?: Record; +} + +interface WrapperRow { + id: string; + plugin: string; + /** The data source key that holds the server URL (`serverUrl` of Jira, `serverURL` of the others). */ + serverKey: string; + auth: (marker: string) => AuthSetup; + /** The path of the operation below the server URL, and the query string it carries (measured). */ + operationPath: string; + operationQuery: string; + /** The canned answer of the echo and the data the query must return. */ + data: (marker: string) => unknown; +} + +const COUCHDB_USER = "e2e-couch-user"; + +const ROWS: readonly WrapperRow[] = [ + { + id: "D8a", + plugin: "couchdb", + serverKey: "serverURL", + auth: (marker) => { + const basic = { user: `${COUCHDB_USER}-${marker}`, password: `e2e-couch-pass-${marker}` }; + // the JWT field is left out of the data source: both credentials would set the same header (D8f) + return { basic, config: { "BasicAuth.username": basic.user, "BasicAuth.password": basic.password, "JwtAuth.value": undefined } }; + }, + operationPath: "/_all_dbs", + operationQuery: "", + data: (marker) => ["_replicator", "_users", `e2e-db-${marker}`], + }, + { + id: "D8b", + plugin: "jira", + serverKey: "serverUrl", + auth: (marker) => { + const basic = { user: `e2e-jira-${marker}@example.test`, password: `e2e-jira-token-${marker}` }; + return { basic, config: { "basicAuth.username": basic.user, "basicAuth.password": basic.password } }; + }, + operationPath: "/rest/api/3/myself", + operationQuery: "", + data: (marker) => ({ accountId: `e2e-account-${marker}`, displayName: `E2E ${marker}`, active: true }), + }, + { + id: "D8c", + plugin: "datadog", + serverKey: "serverURL", + auth: (marker) => { + const headers = { "dd-api-key": `e2e-dd-api-${marker}`, "dd-application-key": `e2e-dd-app-${marker}` }; + return { headers, config: { "apiKeyAuth.value": headers["dd-api-key"], "appKeyAuth.value": headers["dd-application-key"] } }; + }, + operationPath: "/api/v1/validate", + operationQuery: "", + data: (marker) => ({ valid: true, marker }), + }, + { + id: "D8d", + plugin: "woocommerce", + serverKey: "serverURL", + auth: (marker) => { + const basic = { user: `ck_e2e_${marker}`, password: `cs_e2e_${marker}` }; + return { basic, config: { "basicAuth.username": basic.user, "basicAuth.password": basic.password } }; + }, + operationPath: `${WOO_API_PATH}/products`, + operationQuery: WOO_QUERY, + data: (marker) => [{ id: 1, name: `E2E product ${marker}`, status: "publish" }], + }, + { + id: "D8e", + plugin: "supabaseApi", + serverKey: "serverURL", + auth: (marker) => { + const headers = { authorization: `Bearer sbp_e2e_${marker}` }; + return { headers, config: { "bearerAuth.value": `sbp_e2e_${marker}` } }; + }, + operationPath: "/v1/projects", + operationQuery: "", + data: (marker) => [{ id: `e2e-project-${marker}`, name: `E2E ${marker}`, region: "eu-central-1" }], + }, +]; + +/** The path and query string a row's operation is requested with below `base`. */ +function requestPathOf(row: WrapperRow, base: string): string { + return `${base}${row.operationPath}${row.operationQuery ? `?${row.operationQuery}` : ""}`; +} + +/** The path of the canned answer: the operation's path without its query string. */ +function answerPathOf(row: WrapperRow, base: string): string { + return `${base}${row.operationPath}`; +} + +test.describe("OpenAPI wrapper data sources against the echo", NODE_SERVICE_DETAILS, () => { + for (const row of ROWS) { + test(`${row.id} ${row.plugin}: the operation reaches the server URL with its credentials and answers the canned data`, async ({ page, apiUser, echo }) => { + const marker = uniqueMarker(); + const auth = row.auth(marker); + const data = row.data(marker); + await echo.answer(answerPathOf(row, ""), canned(data)); + const datasourceId = await wrapperDatasource(page, apiUser, row.plugin, { [row.serverKey]: echo.url, ...auth.config }); + const appId = await wrapperApp(page, apiUser, row.plugin, datasourceId); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const record = onlyRecord(await echo.received(), "the echo received exactly one request"); + expectRequest(record, echo, { path: `${echo.path}${requestPathOf(row, "")}`, basic: auth.basic, headers: auth.headers }, row.plugin); + expect(envelopeOf(answer).data, "the answer is the body of the echo's canned reply").toEqual(data); + }); + } +}); + +test.describe("CouchDB credentials", NODE_SERVICE_DETAILS, () => { + test("D8f couchdb: a JWT credential alone is sent as the Authorization header; with a Basic credential only the Basic one is", COUCHDB_AUTH_DETAILS, async ({ page, apiUser, echo }) => { + const marker = uniqueMarker(); + const jwt = `Bearer e2e-jwt-${marker}`; + const basic = { user: `${COUCHDB_USER}-${marker}`, password: `e2e-couch-pass-${marker}` }; + const jwtBody = ["jwt-only"]; + const bothBody = ["jwt-and-basic"]; + await echo.answer("/jwt/_all_dbs", canned(jwtBody)); + await echo.answer("/both/_all_dbs", canned(bothBody)); + const jwtOnly = await wrapperDatasource(page, apiUser, "couchdb", { + serverURL: `${echo.url}/jwt`, + "BasicAuth.username": undefined, + "BasicAuth.password": undefined, + "JwtAuth.value": jwt, + }); + const both = await wrapperDatasource(page, apiUser, "couchdb", { + serverURL: `${echo.url}/both`, + "BasicAuth.username": basic.user, + "BasicAuth.password": basic.password, + "JwtAuth.value": jwt, + }); + const jwtApp = await wrapperApp(page, apiUser, "couchdb", jwtOnly); + const bothApp = await wrapperApp(page, apiUser, "couchdb", both); + expect(await echo.received(), "before the runs the echo holds nothing of this test").toEqual([]); + + const jwtAnswer = await runDraft(page, jwtApp); + const bothAnswer = await runDraft(page, bothApp); + + expectSucceeded(jwtAnswer); + expectSucceeded(bothAnswer); + expect(envelopeOf(jwtAnswer).data, "the JWT-only query's data").toEqual(jwtBody); + expect(envelopeOf(bothAnswer).data, "the combined query's data").toEqual(bothBody); + const records = await echo.received(); + expect(records, "one request per query").toHaveLength(2); + const jwtRecord = onlyRecord(recordsUnder(records, echo, "/jwt"), "the JWT-only query sent one request"); + const bothRecord = onlyRecord(recordsUnder(records, echo, "/both"), "the combined query sent one request"); + // the JWT field becomes the Authorization header when it is the only credential + expectRequest(jwtRecord, echo, { path: `${echo.path}/jwt/_all_dbs`, headers: { authorization: jwt } }, "JWT only"); + // measured on the images `3.0.0-e2e` and `3.0.1-e2e`: with both credentials the Basic one replaces the JWT one + expectRequest(bothRecord, echo, { path: `${echo.path}/both/_all_dbs`, basic }, "Basic and JWT"); + expect(recordsContain([bothRecord], jwt), "the JWT value is on no part of the combined request (the control above: the request arrived)").toBe(false); + }); +}); + +test.describe("WooCommerce server URL", NODE_SERVICE_DETAILS, () => { + test("D8g woocommerce: the API path is appended to a plain server URL, kept when present, and a v1 or v2 URL is refused before any request", async ({ page, apiUser, echo }) => { + const marker = uniqueMarker(); + const row = ROWS.find((candidate) => candidate.plugin === "woocommerce") as WrapperRow; + const auth = row.auth(marker); + const cases = [ + { sub: "/plain", url: `${echo.url}/plain`, base: `/plain` }, + { sub: "/slash", url: `${echo.url}/slash/`, base: `/slash` }, + { sub: "/kept", url: `${echo.url}/kept${WOO_API_PATH}`, base: `/kept` }, + ]; + for (const entry of cases) await echo.answer(answerPathOf(row, entry.base), canned([entry.sub])); + expect(await echo.received(), "before the runs the echo holds nothing of this test").toEqual([]); + + for (const entry of cases) { + const datasourceId = await wrapperDatasource(page, apiUser, "woocommerce", { serverURL: entry.url, ...auth.config }); + const answer = await runDraft(page, await wrapperApp(page, apiUser, "woocommerce", datasourceId)); + expectSucceeded(answer); + expect(envelopeOf(answer).data, `${entry.url}: the canned answer of its own path`).toEqual([entry.sub]); + } + const reached = await echo.received(); + expect(reached, "one request per accepted URL").toHaveLength(cases.length); + cases.forEach((entry, index) => { + // each below its own base with the API path once + expectRequest(reached[index] as EchoRecord, echo, { path: `${echo.path}${requestPathOf(row, entry.base)}`, basic: auth.basic }, entry.url); + }); + + // the refused versions: no request leaves the plugin (the three requests above are the control that the echo is reached) + for (const version of ["v1", "v2"]) { + const datasourceId = await wrapperDatasource(page, apiUser, "woocommerce", { serverURL: `${echo.url}/refused/wc/${version}`, ...auth.config }); + const answer = await runDraft(page, await wrapperApp(page, apiUser, "woocommerce", datasourceId)); + expectRan(answer); + expect(envelopeOf(answer).success, `wc/${version}: the query failed`).toBe(false); + expect(envelopeOf(answer).queryCode, `wc/${version}: the query code`).toBe(QUERY_CODE_FAILED); + expect(envelopeOf(answer).message, `wc/${version}: the plugin's refusal`).toBe(WOO_REFUSAL_MESSAGE); + } + const afterRefusals = await echo.received(); + expect(afterRefusals, "the refused URLs sent nothing: the echo still holds the three requests").toEqual(reached); + }); + + test("D8h woocommerce: a server URL with a trailing slash after the API path gets the API path twice", WOO_TRAILING_SLASH_DETAILS, async ({ page, apiUser, echo }) => { + const marker = uniqueMarker(); + const row = ROWS.find((candidate) => candidate.plugin === "woocommerce") as WrapperRow; + const auth = row.auth(marker); + const doubled = `/twice${WOO_API_PATH}${WOO_API_PATH}`; + const body = ["doubled"]; + await echo.answer(`${doubled}/products`, canned(body)); + const datasourceId = await wrapperDatasource(page, apiUser, "woocommerce", { serverURL: `${echo.url}/twice${WOO_API_PATH}/`, ...auth.config }); + const appId = await wrapperApp(page, apiUser, "woocommerce", datasourceId); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const record = onlyRecord(await echo.received(), "the request reached the echo"); + // Measured on the images `3.0.0-e2e` and `3.0.1-e2e`: `prepareServerUrl` recognises `/wc/v3` only at the very end of the URL, so + // the trailing slash makes it append `wp-json/wc/v3` again (NSD-5 candidate, see WOO_TRAILING_SLASH_DEFECT). + expectRequest(record, echo, { path: `${echo.path}${doubled}/products?${WOO_QUERY}`, basic: auth.basic }, "doubled API path"); + expect(envelopeOf(answer).data, "the canned answer of the doubled path").toEqual(body); + }); +}); + +/** + * How long the echo withholds the answers of D8i until all queries of the test are waiting at it. The slowest start is datadog: + * its document is dereferenced on every run (about 0.7 s each, one after the other on node-service's single thread), so 4 queries + * arrive within about 3 s; the 10 s query timeout of the app is the outer limit. + */ +const BARRIER_TIMEOUT_MS = 8_000; + +/** How many queries run at once against each plugin, and the share of them per server URL: half and half. Datadog's document is large and is dereferenced on every run (measured about 0.7 s each, and more under load), so it gets fewer. */ +const CONCURRENT_RUNS: Record = { couchdb: 8, woocommerce: 8, datadog: 4 }; + +test.describe("concurrent queries of one plugin", NODE_SERVICE_DETAILS, () => { + for (const [plugin, runs] of Object.entries(CONCURRENT_RUNS)) { + test(`D8i ${plugin}: queries submitted together against two server URLs each reach their own server, with all requests waiting at the echo at once`, async ({ page, apiUser, echo }) => { + const row = ROWS.find((candidate) => candidate.plugin === plugin) as WrapperRow; + const marker = uniqueMarker(); + const auth = row.auth(marker); + const sides = ["a", "b"] as const; + const apps: Record = {}; + for (const side of sides) { + await echo.answer(answerPathOf(row, `/${side}`), { ...canned({ side }), barrier: { subPath: "/", count: runs, timeoutMs: BARRIER_TIMEOUT_MS } }); + const datasourceId = await wrapperDatasource(page, apiUser, plugin, { [row.serverKey]: `${echo.url}/${side}`, ...auth.config }); + apps[side] = await wrapperApp(page, apiUser, plugin, datasourceId); + } + expect(await echo.received(), "before the runs the echo holds nothing of this test").toEqual([]); + + const runsOf = Array.from({ length: runs }, (_, index) => sides[index % sides.length] as (typeof sides)[number]); + // the echo answers only once all `runs` requests are waiting at it, so success below proves all requests were waiting at the echo at the same time + const answers = await Promise.all(runsOf.map((side) => runDraft(page, apps[side] as string))); + + answers.forEach((answer, index) => { + const side = runsOf[index]; + expectSucceeded(answer); + expect(envelopeOf(answer).data, `run ${index} against server ${side}: the data of its own server`).toEqual({ side }); + }); + const records = await echo.received(); + expect(records, "one request per run").toHaveLength(runs); + for (const side of sides) { + const own = recordsUnder(records, echo, `/${side}`); + expect(own, `server ${side} received exactly its share`).toHaveLength(runs / sides.length); + own.forEach((record, index) => { + expectRequest(record, echo, { path: `${echo.path}${requestPathOf(row, `/${side}`)}`, basic: auth.basic, headers: auth.headers }, `server ${side}, request ${index}`); + }); + } + }); + } +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index ed5793b0a8..f8559d66e3 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -23,6 +23,7 @@ import { OPEN_API_FIXTURE_OPERATION, OPEN_API_FIXTURE_SCHEME, OPEN_API_FIXTURE_SPEC, + parseBasicAuthorization, } from "../../src/datasource/node-plugins"; /** @@ -213,6 +214,56 @@ test.describe("node-service data source helpers", { tag: [TAGS.NODE_SERVICE] }, expect(text, "an epoch of 10 digits or more").not.toMatch(/\b\d{10,}\b/); }); + test("the OpenAPI wrapper recordings are the form's body and the editor's saved query, with no value of the recording session", () => { + // the form of these plugins has no dynamic config, so the body holds the typed fields and the two defaults only + const expectations = [ + { id: "couchdb", server: "serverURL", fields: ["BasicAuth.username", "BasicAuth.password", "JwtAuth.value"], action: "allDBs" }, + { id: "jira", server: "serverUrl", fields: ["basicAuth.username", "basicAuth.password"], action: "getCurrentUser" }, + { id: "datadog", server: "serverURL", fields: ["apiKeyAuth.value", "appKeyAuth.value"], action: "get_api_v1_validate" }, + { id: "woocommerce", server: "serverURL", fields: ["basicAuth.username", "basicAuth.password"], action: "get_products" }, + { id: "supabaseApi", server: "serverURL", fields: ["bearerAuth.value"], action: "v1_list_all_projects" }, + ]; + for (const { id, server, fields, action } of expectations) { + const datasource = recordedPluginDatasource(id); + const query = recordedPluginQuery(id); + const config = datasource.datasourceConfig; + expect(datasource.type, `${id}: the data source type`).toBe(id); + expect(Object.keys(datasource), `${id}: no workspace id`).toEqual(["name", "type", "datasourceConfig"]); + expect(Object.keys(config), `${id}: the form fields`).toEqual([server, ...fields, "authConfigType", "sslCertVerificationType"]); + expect(config[server], `${id}: the placeholder server URL`).toBe(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL); + for (const field of fields) expect(config[field], `${id}: ${field} is a placeholder`).toBe("placeholder"); + expect(query.compType, `${id}: the query type`).toBe(id); + expect(query.comp.actionName, `${id}: the recorded operation`).toBe(action); + expect(Object.keys(query), `${id}: only what the builder keeps`).toEqual(["compType", "comp"]); + const text = [`${id}Datasource.json`, `${id}Query.json`].map((file) => readFileSync(join(RECORDED_PLUGINS_DIR, id, file), "utf8")).join("\n"); + expect(text, `${id}: a 24-hex id`).not.toMatch(/\b[0-9a-f]{24}\b/); + expect(text, `${id}: an echo address`).not.toContain("e2e-echo"); + expect(text, `${id}: an epoch of 10 digits or more`).not.toMatch(/\b\d{10,}\b/); + } + expect(recordedPluginQuery("woocommerce").comp.action, "woocommerce: the editor's defaults of the enumerated parameters").toMatchObject({ + "query_@_context": "view", + "query_@_order": "asc", + "query_@_orderby": "date", + "query_@_status": "any", + "query_@_type": "simple", + "query_@_stock_status": "instock", + }); + }); + + test("parseBasicAuthorization decodes user and password, and reads anything else as not Basic credentials", () => { + const header = (text: string): string => `Basic ${Buffer.from(text, "utf8").toString("base64")}`; + expect(parseBasicAuthorization(header("user:secret"))).toEqual({ user: "user", password: "secret" }); + expect(parseBasicAuthorization(header("user:pa:ss")), "the password may hold colons").toEqual({ user: "user", password: "pa:ss" }); + expect(parseBasicAuthorization(header(":")), "empty credentials are credentials").toEqual({ user: "", password: "" }); + expect(parseBasicAuthorization(header("ünï:pässword")), "UTF-8").toEqual({ user: "ünï", password: "pässword" }); + expect(parseBasicAuthorization(undefined), "no header").toBeUndefined(); + expect(parseBasicAuthorization([header("a:b")]), "a repeated header").toBeUndefined(); + expect(parseBasicAuthorization("Bearer abc"), "another scheme").toBeUndefined(); + expect(parseBasicAuthorization("Basic"), "no credentials").toBeUndefined(); + expect(parseBasicAuthorization(header("nocolon")), "no colon").toBeUndefined(); + expect(parseBasicAuthorization("Basic ***"), "not base64").toBeUndefined(); + }); + test("the recorded placeholder host is under the reserved .invalid TLD", () => { expect(new URL(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL).hostname.endsWith(".invalid")).toBe(true); }); diff --git a/e2e/tests/foundation/security-echo.spec.ts b/e2e/tests/foundation/security-echo.spec.ts index c73f68da32..35a9866f84 100644 --- a/e2e/tests/foundation/security-echo.spec.ts +++ b/e2e/tests/foundation/security-echo.spec.ts @@ -18,6 +18,11 @@ const STARTUP_POLL_MS = 100; /** Larger than MAX_BODY_BYTES (65536) of the sidecar. */ const OVERSIZED_BODY_BYTES = 70_000; const MAX_BODY_BYTES = 65_536; +/** Barrier timeouts of the barrier tests: long enough that a group is never cut short while its requests are being sent, short enough that a timed-out group is quick. */ +const BARRIER_LONG_TIMEOUT_MS = 5_000; +const BARRIER_SHORT_TIMEOUT_MS = 300; +/** How long the barrier tests wait after the second request of a group has been recorded before they check that nothing was answered: a premature answer is sent on arrival, a loopback round trip is far below this. */ +const HOLD_WINDOW_MS = 300; let child: ChildProcess; let baseUrl: string; @@ -201,6 +206,75 @@ test.describe("echo helpers", () => { expect((await recordsOf(path)).map((record) => record.path), "all three requests were recorded").toEqual([`${path}/token?x=1`, `${path}/token/special`, `${path}/other`]); }); + test("a barrier holds every answer until the group is full, then answers them together; the same prefix serves later groups, also after a group that timed out", async () => { + const path = echoTargetPath({ workerIndex: 3, repeatEachIndex: 2, retry: 0 }); + const post = async (entry: unknown): Promise => (await fetch(`${baseUrl}${ECHO_PATHS.ANSWERS}`, { method: "POST", body: JSON.stringify(entry) })).status; + /** ONE barrier prefix for every group of this test: a group that is not cleaned up after its release or its timeout would leak into the next. */ + const barrier = (timeoutMs: number) => ({ prefix: `${path}/`, count: 3, timeoutMs }); + const setAnswers = async (timeoutMs: number): Promise => { + expect(await post({ prefix: `${path}/a`, status: 200, contentType: "text/plain", body: "answer-a", barrier: barrier(timeoutMs) })).toBe(204); + expect(await post({ prefix: `${path}/b`, status: 201, contentType: "text/plain", body: "answer-b", barrier: barrier(timeoutMs) })).toBe(204); + }; + const ask = (sub: string) => fetch(`${baseUrl}${path}${sub}`).then(async (response) => ({ status: response.status, text: await response.text() })); + const asked = { count: 0 }; + + /** Two requests wait (and are recorded), nothing is answered within the window, the third fills the group and all three get their own answer. */ + const completeGroup = async (label: string): Promise => { + const settled: string[] = []; + const track = (promise: ReturnType) => promise.then((answer) => { + settled.push(answer.text); + return answer; + }); + const first = track(ask("/a")); + const second = track(ask("/b")); + asked.count += 2; + // positive control that the requests arrived: both are recorded while neither is answered + await expect.poll(async () => (await recordsOf(path)).length, { message: `${label}: both requests reached the echo` }).toBe(asked.count); + await new Promise((resolve) => setTimeout(resolve, HOLD_WINDOW_MS)); + expect(settled, `${label}: with 2 of 3 waiting nothing is answered`).toEqual([]); + const third = track(ask("/a")); + asked.count += 1; + expect(await Promise.all([first, second, third]), `${label}: the third request fills the group: all three are answered with their own canned answer`).toEqual([ + { status: 200, text: "answer-a" }, + { status: 201, text: "answer-b" }, + { status: 200, text: "answer-a" }, + ]); + }; + + await setAnswers(BARRIER_LONG_TIMEOUT_MS); + await completeGroup("first group"); + await completeGroup("second group, same prefix after a release"); + + // a group that does not fill within its (short) timeout is answered 504 ... + await setAnswers(BARRIER_SHORT_TIMEOUT_MS); + const timedOut = await ask("/a"); + asked.count += 1; + expect(timedOut, "a group of one that never fills").toEqual({ status: 504, text: "barrier timeout" }); + // ... and the same prefix then serves a complete group again + await setAnswers(BARRIER_LONG_TIMEOUT_MS); + await completeGroup("group after a timed-out group, same prefix"); + }); + + test("a canned answer with an invalid barrier is refused with 400", async () => { + const path = echoTargetPath({ workerIndex: 3, repeatEachIndex: 3, retry: 0 }); + const base = { prefix: `${path}/x`, status: 200, contentType: "text/plain", body: "b" }; + const invalid = [ + { prefix: "no-slash", count: 2, timeoutMs: 100 }, + { prefix: "/p", count: 1, timeoutMs: 100 }, + { prefix: "/p", count: 2.5, timeoutMs: 100 }, + { prefix: "/p", count: 2, timeoutMs: 0 }, + { prefix: "/p", count: 2, timeoutMs: 60000 }, + "text", + null, + ]; + for (const barrier of invalid) { + const status = (await fetch(`${baseUrl}${ECHO_PATHS.ANSWERS}`, { method: "POST", body: JSON.stringify({ ...base, barrier }) })).status; + expect(status, `barrier ${JSON.stringify(barrier)}`).toBe(400); + } + const plain = await fetch(`${baseUrl}${path}/x`); + expect(await plain.json(), "nothing was stored").toEqual({}); + }); + test("the latest canned answer of a prefix replaces the earlier one, and an invalid one is refused with 400 and changes nothing", async () => { const path = echoTargetPath({ workerIndex: 3, repeatEachIndex: 1, retry: 0 }); const post = async (entry: unknown): Promise => (await fetch(`${baseUrl}${ECHO_PATHS.ANSWERS}`, { method: "POST", body: typeof entry === "string" ? entry : JSON.stringify(entry) })).status; From eda71346ac14bdba878bbd1704a34d7ac46fa4f0 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 18:05:32 +0100 Subject: [PATCH 11/20] test: add Lowcoder, OpenAI, APITemplate, Carbone and UiPath scenarios Adds recorded data source and query fixtures for five OpenAPI-based node-service plugins and scenarios that point each at the run's echo target: the request method, path, headers and body for each plugin, the credential header each one sends, an HTTP error answer reported as success, and queries submitted together against two server URLs. Two behaviours are characterised and annotated as defect candidates: the OpenAI plugin sends no API key for spec version 1.0 (the default), and the UiPath plugin cannot run at all because building its query configuration overflows the stack. The desired UiPath behaviour is asserted in a quarantined test. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 2 +- e2e/README.md | 22 +- .../dsl/plugins/OpenAI/OpenAIDatasource.json | 10 + .../dsl/plugins/OpenAI/OpenAIQuery.json | 13 + .../apiTemplate/apiTemplateDatasource.json | 10 + .../plugins/apiTemplate/apiTemplateQuery.json | 20 + .../carboneIo/carboneIoDatasource.json | 10 + .../dsl/plugins/carboneIo/carboneIoQuery.json | 13 + .../plugins/lowcoder/lowcoderDatasource.json | 10 + .../dsl/plugins/lowcoder/lowcoderQuery.json | 13 + .../dsl/plugins/uiPath/uiPathDatasource.json | 10 + .../dsl/plugins/uiPath/uiPathQuery.json | 13 + .../plugin-openapi-wrappers-apps.spec.ts | 513 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 43 ++ 14 files changed, 692 insertions(+), 10 deletions(-) create mode 100644 e2e/fixtures/dsl/plugins/OpenAI/OpenAIDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/OpenAI/OpenAIQuery.json create mode 100644 e2e/fixtures/dsl/plugins/apiTemplate/apiTemplateDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/apiTemplate/apiTemplateQuery.json create mode 100644 e2e/fixtures/dsl/plugins/carboneIo/carboneIoDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/carboneIo/carboneIoQuery.json create mode 100644 e2e/fixtures/dsl/plugins/lowcoder/lowcoderDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/lowcoder/lowcoderQuery.json create mode 100644 e2e/fixtures/dsl/plugins/uiPath/uiPathDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/uiPath/uiPathQuery.json create mode 100644 e2e/tests/datasource/plugin-openapi-wrappers-apps.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index c3d49f3c19..a968b0a468 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,7 +129,7 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). diff --git a/e2e/README.md b/e2e/README.md index df3bb21db9..8ea2f589bb 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce and Supabase Management API run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), D5 to D8, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), D5 to D9, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -209,7 +209,7 @@ e2e/ fixtures/sql/init.sql PostgreSQL data: items, products, notes fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb`, `jira`, `datadog`, `woocommerce`, `supabaseApi` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each) + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb`, `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate) src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -252,15 +252,16 @@ Test titles carry these ids. - D6 the GitLab and Shopify GraphQL plugins of node-service against the echo sidecar: a GitLab query posts the query, the variables and every header (data source, query and the access token), a GraphQL error answer fails the query, the published view after a click; a Shopify query reaches the endpoint, and the header the query sets does not (NSD-2 candidate) (`@node-service`; the request shape and the answer's path into the app, not the vendor service). - D7 the generic Open API plugin of node-service against the echo sidecar: the data source form's dynamic config reads the OpenAPI document from its URL (the echo serves a canned document) and answers the spec and the key field, an operation runs against the server URL with the key in the header the document names, the key comes from the data source (no key, no header), an error status answers its body as a successful result (NSD-4 candidate), the published view after a click, the dynamic config answer is cached in memory per request body, with no expiry (observation) (`@node-service`). - D8 the Open API wrapper plugins of node-service with a server URL (CouchDB, Jira, Datadog, WooCommerce, Supabase Management API) against the echo sidecar: one read-only operation each reaches the server URL (the target's path survives as the base path) with its credentials and answers the canned data, CouchDB JWT credential alone and with a Basic one (observation), WooCommerce server URL forms and refusal of v1/v2, a trailing slash after the API path doubles it (NSD-5 candidate), concurrent queries against two server URLs each reach their own server (`@node-service`). +- D9 the Open API wrapper plugins of node-service with a server URL (Lowcoder API, OpenAI, APITemplate.io, Carbone, UiPath) against the echo sidecar: one read-only operation each reaches the server URL with its credentials and answers the canned data (Carbone `get_status` sends no token: observation), every Lowcoder spec version, an OpenAI chat completion posts its JSON body, OpenAI on spec version v1.0 sends no key (NSD-7 candidate), an error status answered as success (NSD-4 candidate), UiPath fails every query and its query configuration request (HTTP 500) and sends nothing (NSD-6 candidate; its desired behaviour is quarantined), concurrent queries against two server URLs each reach their own server (`@node-service`). - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`, after this branch's security fixes; this is a static listing, not a Docker run. A combined final run against an image built from this branch (tag `secfix-combined-e2e`) has since confirmed pass/fail for every scenario named in the per-defect rows below: 693/696 default tests passed, the 3 failures pre-existing or unrelated suite drift (documented in their own rows below)): -default **754 tests in 111 files**; with `E2E_INCLUDE_QUARANTINE=1` **767 in 112**; with `E2E_INCLUDE_SUPERADMIN=1` **759 in 111**; with both of those **772 in 112**; -with `E2E_INCLUDE_INSERT_ALL=1` **866 in 112**; with all three opt-in variables **884 in 113** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: +default **770 tests in 112 files**; with `E2E_INCLUDE_QUARANTINE=1` **784 in 113**; with `E2E_INCLUDE_SUPERADMIN=1` **775 in 112**; with both of those **789 in 113**; +with `E2E_INCLUDE_INSERT_ALL=1` **882 in 113**; with all three opt-in variables **901 in 114** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 56 (the 20 unit tests of `foundation/node-plugins.spec.ts`, D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f and D8a to D8i; a selection tag, they stay in the default run). On request: `@quarantine` 13 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 13 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 13 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5) and the icon switch of `components/displays.spec.ts` (CD-9 candidate). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 72 in 8 files (the 21 unit tests of `foundation/node-plugins.spec.ts` plus the 51 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests) and D9a to D9k with the four D9m tests (15 tests); a selection tag, they stay in the default run). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -309,7 +310,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | editor/js-query.spec.ts | a JS query written in the editor runs | @core | 1 | | editor/drop-size.spec.ts | a component dropped right after ready has width above 0 (D-5) | @quarantine | 1 | -### datasource (31) +### datasource (61) | File | Proves | Tags | Tests | |---|---|---|---| @@ -322,6 +323,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/plugin-graphql.spec.ts | D6: GitLab and Shopify against the echo sidecar (the endpoint is the test's own echo target plus `/api/graphql`). D6a a GitLab query posts one JSON body `{query, variables: {n: 3}, operationName}` (the variable's text `3` arrives as the number 3) with `PRIVATE-TOKEN`, the data source header and the query header, and answers the `data` member, D6b a `{"errors":[...]}` answer fails the query with `: `, D6c a Shopify query posts `{query, variables: {}}` and answers the `data` member (control), D6d the header the Shopify query sets reaches the echo neither as name nor as value (NSD-2 candidate), D6e the published view shows the GitLab answer after a click | @node-service | 5 | | datasource/plugin-openapi.spec.ts | D7: the generic Open API plugin against the echo sidecar (spec URL `/spec.json`, server URL `/api`; the document is `OPEN_API_FIXTURE_SPEC`: `GET /items`, operation `listItems`, parameter `q`, API key header `X-E2E-Key`, placeholder server). D7a the dynamic config call (`path` `$.dataSourceConfig.extra`) answers `[{data: {spec}, extraParams}]` with the key field `E2EKeyAuth.value` labelled `X-E2E-Key` and fetches the document with exactly one GET, D7b `listItems` sends `GET /api/items?q=` with `x-e2e-key` and answers the canned `[{id: 1}]`, D7c a data source with an empty `dynamicParamsConfig` sends no key header, D7d a canned 404 `{"message":"e2e-missing"}` is answered as `success: true`, `queryCode: "OK"`, data the 404 body (NSD-4 candidate), D7e the published view shows the first item's id only after the click (echo 0 requests before, exactly 1 after), D7f the same dynamic config request answers from the cache after the document changed on the echo (one fetch), while a request with another body fetches again; the cache is an in-process object keyed on path, query and body with no expiry (observation) | @node-service | 6 | | datasource/plugin-openapi-wrappers-data.spec.ts | D8: CouchDB, Jira, Datadog, WooCommerce and the Supabase Management API against the echo sidecar (server URL ``, one read-only operation of each bundled document). D8a couchdb `GET /_all_dbs` with `Authorization: Basic` of the configured user and password, D8b jira `GET /rest/api/3/myself` with Basic, D8c datadog `GET /api/v1/validate` with `dd-api-key` and `dd-application-key`, D8d woocommerce `GET /wp-json/wc/v3/products?context=view&order=asc&orderby=date&status=any&type=simple&stock_status=instock` with Basic, D8e supabaseApi `GET /v1/projects` with `Authorization: Bearer `; each asserts echo empty before, exactly one request (method, full path and query, no body, the complete header set) and the canned body as the query's data; D8f couchdb: a JWT credential alone is sent as `Authorization`, with a Basic credential too only the Basic one is (observation), each request asserted completely; D8g woocommerce: a plain, a slash-terminated and an already `/wp-json/wc/v3` server URL each give the API path once, `/wc/v1` and `/wc/v2` are refused with `only woocommerce api v3 is supported` and send nothing; D8h woocommerce: a server URL ending in `/wp-json/wc/v3/` gets the API path twice (NSD-5 candidate); D8i couchdb, woocommerce and datadog: 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 11 | +| datasource/plugin-openapi-wrappers-apps.spec.ts | D9: the Lowcoder API, OpenAI, APITemplate.io, Carbone and UiPath against the echo sidecar (server URL ``, one read-only operation of each bundled document). D9a lowcoder `GET /api/users/currentUser` with `Authorization: Bearer `, D9b OpenAI (spec version v2.3) `GET /models` with `Authorization: Bearer `, D9c apiTemplate `GET /v2/list-templates` with `x-api-key`, D9d carboneIo `GET /status` with NO credential header (observation: that operation lists no security scheme), D9e carboneIo `GET /template/` with `Authorization: Bearer ` and `carbone-version: 4`; each asserts echo empty before, exactly one request (method, full path and query, body, the complete header set) and the canned body as the query's data; D9f lowcoder: spec versions v1.0 to v1.3 send the same request; D9g OpenAI: a chat completion `POST /chat/completions` carries the JSON body, `content-type`, `content-length` and the key, and answers the canned completion; D9h OpenAI: spec version v1.0, chosen or by default, sends no `Authorization` header while v2.3 with the same key does (NSD-7 candidate); D9i apiTemplate: a canned 404 body is reported as a successful result (NSD-4 candidate); D9j uiPath: a query fails with the message `Maximum call stack size exceeded` and sends no request, after a control that another wrapper's query reaches the same echo target (NSD-6 candidate); D9k uiPath: the form's query configuration request for the UiPath document answers 500 / code 5000 `get dynamic config error`, while the identical request for apiTemplate answers success and lists its operations (NSD-6 candidate; the test asserts the failure and the control, not its cause); D9l uiPath (`@quarantine`, not counted in the default run): the folders query should reach `GET /odata/Folders` with `Bearer ` exactly and answer the canned data, fails today; D9m lowcoder, apiTemplate, carboneIo and OpenAI: 8, 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 15 (+1 `@quarantine`) | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -466,13 +468,13 @@ first makes sure some admin exists (accepting both answers), so none depends on SEC-R09d (D-38) left the quarantine: the check took the workspace of the first id of a `HashSet`; each id is now decided in its own workspace (Java unit and MongoDB integration tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)). Accounting of the earlier 3.0.0 run `E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --workers=4 --reporter=list --grep "@quarantine" tests/security` (measured before the `@superadmin` tag existed and before the reassessment, so it listed 44 tests, 19 of which have since left the quarantine): 44 listed, 43 failed, 1 passed (SEC-R09d); the two quarantined tests of `foundation/security-helpers.spec.ts` are outside that folder. -### foundation (283 default, 286 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) +### foundation (289 default, 292 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) | File | Proves | Tags | Tests | |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), and `parseBasicAuthorization` | @node-service | 20 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), and `parseBasicAuthorization` | @node-service | 21 | | foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources) | none | 27 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | @@ -515,8 +517,10 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-1 candidate | the Turso plugin prints a pipeline `error` result as `${result.error}`, an object: a failed statement reaches the app as `Cannot parse result, received error: [object Object]` and the server's own message is lost; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-turso-slack.spec.ts` D5d asserts today's message (characterisation, default run), annotation `{type:"defect", description:"NSD-1 candidate"}`; it changes when the plugin prints the message | | NSD-3 candidate | the DuckDB plugin answers rows keyed by the column position, not the column name (`SELECT 42 AS answer` arrives as `{"0": 42}`): `getRows()` answers arrays and `serializeBigInts` copies `Object.entries(row)`; measured on 3.0.0-e2e and 3.0.1-e2e. An app cannot read `row.answer`. The id is provisional until the owner assigns one | `datasource/plugin-duckdb.spec.ts` D4a to D4c assert today's keys (characterisation, default run), annotation `{type:"defect", description:"NSD-3 candidate"}`; they change when the plugin keys rows by name | | NSD-2 candidate | the Shopify plugin reads the query's headers and passes `{}` on, and its data source has only `endpoint`: it cannot send Shopify's access token (`X-Shopify-Access-Token`); measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-graphql.spec.ts` D6d asserts today's behaviour after a control that the request did reach the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-2 candidate"}`; it changes when the query's headers are forwarded | -| NSD-4 candidate | the generic Open API plugin returns the body of an error status answer as the query result (`runOpenApi` catch, `e.response.body`): a canned 404 `{"message":"e2e-missing"}` is reported as `success: true`, `queryCode: "OK"`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi.spec.ts` D7d asserts today's behaviour after a control that the request reached the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-4 candidate"}`; it changes when an error status fails the query | +| NSD-4 candidate | the generic Open API plugin returns the body of an error status answer as the query result (`runOpenApi` catch, `e.response.body`): a canned 404 `{"message":"e2e-missing"}` is reported as `success: true`, `queryCode: "OK"`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi.spec.ts` D7d asserts today's behaviour after a control that the request reached the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-4 candidate"}`; it changes when an error status fails the query. `datasource/plugin-openapi-wrappers-apps.spec.ts` D9i shows the same for APITemplate (wrappers share `runOpenApi`) | | NSD-5 candidate | the WooCommerce plugin appends `wp-json/wc/v3` to a server URL unless it ends exactly in `/wc/v3`, so a server URL copied with a trailing slash (`/wp-json/wc/v3/`) is requested at `/wp-json/wc/v3/wp-json/wc/v3/products`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-data.spec.ts` D8h asserts today's behaviour (characterisation, default run), annotation `{type:"defect", description:"NSD-5 candidate"}`; it changes when a trailing slash is accepted | +| NSD-6 candidate | the UiPath plugin cannot run: `getSchemaExample` (`plugins/openApi/util.ts`) recurses without end on a circular schema of the bundled document, so the query configuration (`POST /api/datasources/getPluginDynamicConfig`, path `$.queryConfig`) answers 500 / code 5000 `get dynamic config error` (the editor lists no operation and cannot save a UiPath query) and every query fails with `Maximum call stack size exceeded` before any request is sent; the cause (`RangeError: Maximum call stack size exceeded` at `getSchemaExample`, from a circular schema) was read in the app container's node-service log while recording, not asserted: the suite asserts only the HTTP 500 / code 5000 of the configuration request, the query's failure message and that no request is sent; measured on 3.0.0-e2e and 3.0.1-e2e. Whether UiPath sends its `Authorization` header (a doubled `Bearer`, or none) cannot be measured today. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9j and D9k assert today's behaviour after a control that another plugin reaches the echo / lists its operations (characterisation, default run), annotation `{type:"defect", description:"NSD-6 candidate"}`; D9l asserts the desired behaviour (`GET /odata/Folders` with `Authorization: Bearer ` exactly), `@quarantine`, same annotation; they change when the plugin runs | +| NSD-7 candidate | an OpenAI data source on spec version `v1.0` (the version an empty choice selects) sends no `Authorization` header: the plugin hands the key over as `ApiKeyAuth.value`, the security scheme of the `v2.3` document, while the `v1.0` document names its scheme `ApiKey`; with `v2.3` the same key is sent as `Authorization: Bearer `; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9h asserts today's behaviour after a control that v2.3 sends the key to the same echo (characterisation, default run), annotation `{type:"defect", description:"NSD-7 candidate"}`; it changes when the key reaches the `v1.0` document's scheme | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/fixtures/dsl/plugins/OpenAI/OpenAIDatasource.json b/e2e/fixtures/dsl/plugins/OpenAI/OpenAIDatasource.json new file mode 100644 index 0000000000..0a7c171859 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/OpenAI/OpenAIDatasource.json @@ -0,0 +1,10 @@ +{ + "name": "OpenAI", + "type": "OpenAI", + "datasourceConfig": { + "serverURL": "http://placeholder.invalid", + "apiKey": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/OpenAI/OpenAIQuery.json b/e2e/fixtures/dsl/plugins/OpenAI/OpenAIQuery.json new file mode 100644 index 0000000000..c1e76a6210 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/OpenAI/OpenAIQuery.json @@ -0,0 +1,13 @@ +{ + "compType": "OpenAI", + "comp": { + "actionName": "listModels", + "action": {}, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/apiTemplate/apiTemplateDatasource.json b/e2e/fixtures/dsl/plugins/apiTemplate/apiTemplateDatasource.json new file mode 100644 index 0000000000..64d5df68a8 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/apiTemplate/apiTemplateDatasource.json @@ -0,0 +1,10 @@ +{ + "name": "apiTemplate", + "type": "apiTemplate", + "datasourceConfig": { + "serverURL": "http://placeholder.invalid", + "ApiKeyAuth.value": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/apiTemplate/apiTemplateQuery.json b/e2e/fixtures/dsl/plugins/apiTemplate/apiTemplateQuery.json new file mode 100644 index 0000000000..9a02deb3e2 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/apiTemplate/apiTemplateQuery.json @@ -0,0 +1,20 @@ +{ + "compType": "apiTemplate", + "comp": { + "actionName": "list_templates", + "action": { + "query_@_limit": "", + "query_@_offset": "", + "query_@_format": "", + "query_@_template_id": "", + "query_@_group_name": "", + "query_@_with_layer_info": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/carboneIo/carboneIoDatasource.json b/e2e/fixtures/dsl/plugins/carboneIo/carboneIoDatasource.json new file mode 100644 index 0000000000..d448c3ae24 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/carboneIo/carboneIoDatasource.json @@ -0,0 +1,10 @@ +{ + "name": "carboneIo", + "type": "carboneIo", + "datasourceConfig": { + "serverURL": "http://placeholder.invalid", + "bearerAuth.value": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/carboneIo/carboneIoQuery.json b/e2e/fixtures/dsl/plugins/carboneIo/carboneIoQuery.json new file mode 100644 index 0000000000..cc2c734ba7 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/carboneIo/carboneIoQuery.json @@ -0,0 +1,13 @@ +{ + "compType": "carboneIo", + "comp": { + "actionName": "get_status", + "action": {}, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/lowcoder/lowcoderDatasource.json b/e2e/fixtures/dsl/plugins/lowcoder/lowcoderDatasource.json new file mode 100644 index 0000000000..4093c1c2b7 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/lowcoder/lowcoderDatasource.json @@ -0,0 +1,10 @@ +{ + "name": "lowcoder", + "type": "lowcoder", + "datasourceConfig": { + "serverURL": "http://placeholder.invalid", + "bearerAuth.value": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/lowcoder/lowcoderQuery.json b/e2e/fixtures/dsl/plugins/lowcoder/lowcoderQuery.json new file mode 100644 index 0000000000..274f471f8d --- /dev/null +++ b/e2e/fixtures/dsl/plugins/lowcoder/lowcoderQuery.json @@ -0,0 +1,13 @@ +{ + "compType": "lowcoder", + "comp": { + "actionName": "getUserInfo", + "action": {}, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/uiPath/uiPathDatasource.json b/e2e/fixtures/dsl/plugins/uiPath/uiPathDatasource.json new file mode 100644 index 0000000000..caa6cae0f8 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/uiPath/uiPathDatasource.json @@ -0,0 +1,10 @@ +{ + "name": "uiPath", + "type": "uiPath", + "datasourceConfig": { + "serverURL": "http://placeholder.invalid", + "Authorization.value": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/uiPath/uiPathQuery.json b/e2e/fixtures/dsl/plugins/uiPath/uiPathQuery.json new file mode 100644 index 0000000000..5078a0d91f --- /dev/null +++ b/e2e/fixtures/dsl/plugins/uiPath/uiPathQuery.json @@ -0,0 +1,13 @@ +{ + "compType": "uiPath", + "comp": { + "actionName": "Folders_Get", + "action": {}, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/tests/datasource/plugin-openapi-wrappers-apps.spec.ts b/e2e/tests/datasource/plugin-openapi-wrappers-apps.spec.ts new file mode 100644 index 0000000000..c57b83725f --- /dev/null +++ b/e2e/tests/datasource/plugin-openapi-wrappers-apps.spec.ts @@ -0,0 +1,513 @@ +import { randomBytes } from "node:crypto"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, pluginDynamicConfigRaw, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, TAGS } from "../../src/constants"; +import { appDsl, nodePluginQuery } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { expect, test } from "../../src/fixtures"; +import type { EchoRecord, EchoTarget } from "../../src/security/echo"; + +/** + * D9: the plugins of node-service that wrap one bundled OpenAPI document and take a server URL: the Lowcoder API, OpenAI, APITemplate.io, + * Carbone and UiPath (`server/node-service/src/plugins/{lowcoder,openAi,apiTemplate,carboneIo,uiPath}/index.ts`, all running `runOpenApi` of + * `plugins/openApi/index.ts`). The server URL is the test's own target on the echo sidecar, so the tests prove the request each plugin + * builds (method, path below the server URL, query, credential headers, body) and the path of a canned answer into the app. They are NOT a + * fidelity test of any of the services. + * + * Each plugin runs one read-only operation of its bundled document: + * - Lowcoder `getUserInfo`: `GET /api/users/currentUser` (every spec version, `lowcoder.spec-v1.0.json` to `-v1.3.json`); + * - OpenAI `listModels`: `GET /models` (`openAI_v2.3.0.json`; the data source's `specVersion` picks the document); + * - APITemplate `list_templates`: `GET /v2/list-templates` (`apiTemplate.spec.json`); + * - Carbone `get_status`: `GET /status` and `get_template__templateId_`: `GET /template/{templateId}` (`carboneIo.spec.json`); + * - UiPath `Folders_Get`: `GET /odata/Folders` (`uiPath.spec.json`); measured: this plugin cannot run any operation (D9j to D9l). + * + * The plugins keep their parsed document in a module-level object, and `runOpenApi` rewrites its server URL in place. D9m submits several + * queries together and checks that each reaches its own server URL with its own data. The echo withholds every answer (a barrier) until all + * requests of the test are waiting at it, so the canned data reaches the queries only if all of the requests were waiting at the echo at the + * same time; a group that never fills is answered 504 and fails the test. That says nothing about what happens inside node-service while the + * requests are built. + */ +const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; + +/** Candidate defect: an error status answer with a body is returned as the query's successful result (the generic plugin's D7d shows the same). */ +const ERROR_STATUS_SUCCESS_DEFECT = { type: "defect", description: "NSD-4 candidate" } as const; +const ERROR_STATUS_DETAILS = { annotation: ERROR_STATUS_SUCCESS_DEFECT }; + +/** + * Candidate defect: the UiPath plugin cannot run: `getSchemaExample` (`plugins/openApi/util.ts`) recurses without end on a circular schema of + * the bundled document, so its query configuration (what the editor lists) and every query fail with `Maximum call stack size exceeded`. + */ +const UIPATH_DEFECT = { type: "defect", description: "NSD-6 candidate" } as const; +const UIPATH_DETAILS = { annotation: UIPATH_DEFECT }; +/** The desired behaviour of the UiPath plugin: it fails today, so it is quarantined (the enclosing describe adds `@node-service`). */ +const UIPATH_QUARANTINE_DETAILS = { tag: [TAGS.QUARANTINE], annotation: UIPATH_DEFECT }; + +/** + * Candidate defect: an OpenAI data source on the spec version `v1.0` (the default when none is chosen) sends no `Authorization` header: the + * plugin hands the key over as `ApiKeyAuth.value`, the scheme of the `v2.3` document, while the `v1.0` document names its scheme `ApiKey`. + */ +const OPENAI_V1_AUTH_DEFECT = { type: "defect", description: "NSD-7 candidate" } as const; +const OPENAI_V1_AUTH_DETAILS = { annotation: OPENAI_V1_AUTH_DEFECT }; + +/** Observation: a Carbone data source sends its token only with the operations whose document entry lists the `bearerAuth` scheme; `get_status` does not. */ +const CARBONE_STATUS_OBSERVATION = { type: "observation", description: "carboneIo get_status sends no Authorization header: the operation lists no security scheme" } as const; +const CARBONE_STATUS_DETAILS = { annotation: CARBONE_STATUS_OBSERVATION }; + +const HTTP_OK = 200; +const HTTP_NOT_FOUND = 404; +const HTTP_SERVER_ERROR = 500; +const QUERY_CODE_OK = "OK"; +const QUERY_CODE_FAILED = "FAILED"; +const JSON_CONTENT_TYPE = "application/json"; +const MARKER_BYTES = 4; +const QUERY_ID = "q1"; +const QUERY_NAME = "q"; + +/** Request headers of node-service's HTTP client (`node-fetch` through `common/fetch.ts`) that every plugin request carries, measured on the images `3.0.0-e2e` and `3.0.1-e2e`. */ +const NODE_FETCH_USER_AGENT = "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"; +const ACCEPT_ENCODING = "gzip,deflate"; +const CONNECTION_CLOSE = "close"; + +/** The OpenAI document versions: `v1.0` is what an empty `specVersion` selects, `v2.3` is the one whose scheme the plugin's key reaches. */ +const OPENAI_SPEC_V1 = "v1.0"; +const OPENAI_SPEC_V2 = "v2.3"; +const LOWCODER_SPEC_VERSIONS = ["v1.0", "v1.1", "v1.2", "v1.3"] as const; + +/** The operations the rows run, by the name the editor stores. `get_template__templateId_` and `createChatCompletion` are not the recorded ones: the action keys below are what the editor saved for them. */ +const CARBONE_TEMPLATE_ACTION = "get_template__templateId_"; +const CARBONE_TEMPLATE_ID_KEY = "path_@_templateId"; +const CARBONE_VERSION_KEY = "header_@_carbone-version"; +const CARBONE_VERSION = "4"; +const CHAT_ACTION = "createChatCompletion"; +const CHAT_BODY_KEY = "body_@_body"; + +/** What UiPath's error answers: the node-service message of a failed query (`runPluginQuery`) and the answer of the form's dynamic config. */ +const UIPATH_FAILURE_MESSAGE = "Maximum call stack size exceeded"; +const DYNAMIC_CONFIG_ERROR_CODE = 5000; +const DYNAMIC_CONFIG_ERROR_MESSAGE = "get dynamic config error"; +/** The path of the plugin's query configuration in a dynamic config request (`pluginMetaOps`, `services/plugin.ts`). */ +const QUERY_CONFIG_PATH = "$.queryConfig"; +const FORM_DEFAULTS = { authConfigType: "NO_AUTH", sslCertVerificationType: "VERIFY_CA_CERT" } as const; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +function canned(body: unknown, status = HTTP_OK): { status: number; contentType: string; body: string } { + return { status, contentType: JSON_CONTENT_TYPE, body: JSON.stringify(body) }; +} + +function onlyRecord(records: EchoRecord[], description: string): EchoRecord { + expect(records, description).toHaveLength(1); + return records[0] as EchoRecord; +} + +/** The records whose path (below the echo target) starts with `subPath` followed by `/`. */ +function recordsUnder(records: EchoRecord[], echo: EchoTarget, subPath: string): EchoRecord[] { + return records.filter((record) => record.path.startsWith(`${echo.path}${subPath}/`)); +} + +/** What a query of the recording changes: another operation of the same plugin, with its action keys (as the editor saved them). */ +interface QueryVariant { + actionName?: string; + action?: Record; +} + +/** A data source from the recording with `config` merged over it. */ +async function wrapperDatasource(page: Page, apiUser: RegisteredUser, plugin: string, config: Record): Promise { + return createNodePluginDatasource(page.request, { orgId: apiUser.orgId, recorded: recordedPluginDatasource(plugin), config }); +} + +/** A saved app with the recorded query of `plugin` (or a variant of it) on the data source (not published: the draft runs with `viewMode: false`). */ +async function wrapperApp(page: Page, apiUser: RegisteredUser, plugin: string, datasourceId: string, variant: QueryVariant = {}): Promise { + const recorded = recordedPluginQuery(plugin); + if (variant.actionName) recorded.comp.actionName = variant.actionName; + const query = nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded, action: variant.action }); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: `e2e-${plugin}`, dsl: appDsl([], { queries: [query] }) }); + return appId; +} + +async function runDraft(page: Page, appId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId: QUERY_ID, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +function expectSucceeded(answer: RawAnswer): void { + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); +} + +/** The request headers a plugin request carries besides its credentials: `host` is the echo's. */ +function commonHeaders(echo: EchoTarget): Record { + return { + accept: JSON_CONTENT_TYPE, + "user-agent": NODE_FETCH_USER_AGENT, + "accept-encoding": ACCEPT_ENCODING, + host: new URL(echo.url).host, + connection: CONNECTION_CLOSE, + }; +} + +/** + * Asserts one recorded request completely: the method, the exact path and query, the exact body, and the exact header set (the headers + * every plugin request carries plus the `headers` of the call: the credential headers, and for a body the `content-type` and `content-length`). + */ +function expectRequest( + record: EchoRecord, + echo: EchoTarget, + expected: { method?: string; path: string; body?: string; headers?: Record }, + label: string, +): void { + expect(record.method, `${label}: the method`).toBe(expected.method ?? "GET"); + expect(record.path, `${label}: the path and query`).toBe(expected.path); + expect(record.body, `${label}: the body`).toBe(expected.body ?? ""); + expect(record.headers, `${label}: the complete header set`).toEqual({ ...commonHeaders(echo), ...expected.headers }); +} + +/** What a row configures as the credentials, and what they must look like on the wire. */ +interface AuthSetup { + /** The data source keys of the credentials and the other settings, as the form stores them. */ + config: Record; + /** The exact credential headers (lower-case names, as the echo records them); none when the plugin sends none. */ + headers: Record; +} + +interface WrapperRow { + id: string; + plugin: string; + /** The operation: its recorded query, or the variant of it. */ + variant: QueryVariant; + auth: (marker: string) => AuthSetup; + /** The path of the operation below the server URL, and the query string it carries (measured). */ + operationPath: (marker: string) => string; + operationQuery: string; + /** The extra headers of the operation's own parameters (measured). */ + operationHeaders?: Record; + /** The canned answer of the echo and the data the query must return. */ + data: (marker: string) => unknown; +} + +const ROWS: readonly WrapperRow[] = [ + { + id: "D9a", + plugin: "lowcoder", + variant: {}, + auth: (marker) => ({ headers: { authorization: `Bearer e2e-lowcoder-${marker}` }, config: { "bearerAuth.value": `e2e-lowcoder-${marker}` } }), + operationPath: () => "/api/users/currentUser", + operationQuery: "", + data: (marker) => ({ id: `e2e-user-${marker}`, name: `E2E ${marker}`, orgs: [] }), + }, + { + id: "D9b", + plugin: "OpenAI", + variant: {}, + // `v2.3` is the document whose scheme the key reaches (D9h shows `v1.0`) + auth: (marker) => ({ headers: { authorization: `Bearer e2e-openai-${marker}` }, config: { apiKey: `e2e-openai-${marker}`, specVersion: OPENAI_SPEC_V2 } }), + operationPath: () => "/models", + operationQuery: "", + data: (marker) => ({ object: "list", data: [{ id: `e2e-model-${marker}`, object: "model" }] }), + }, + { + id: "D9c", + plugin: "apiTemplate", + variant: {}, + auth: (marker) => ({ headers: { "x-api-key": `e2e-apitemplate-${marker}` }, config: { "ApiKeyAuth.value": `e2e-apitemplate-${marker}` } }), + operationPath: () => "/v2/list-templates", + // the recorded action's parameters are empty, and an empty parameter is not sent (measured) + operationQuery: "", + data: (marker) => ({ status: "success", templates: [{ template_id: `e2e-template-${marker}`, name: `E2E ${marker}` }] }), + }, + { + id: "D9d", + plugin: "carboneIo", + variant: {}, + // measured: the token configured for the data source is NOT sent with `get_status`, whose document entry lists no security scheme (D9e shows it is sent with a template operation) + auth: (marker) => ({ headers: {}, config: { "bearerAuth.value": `e2e-carbone-${marker}` } }), + operationPath: () => "/status", + operationQuery: "", + data: (marker) => ({ success: true, code: 200, message: `OK ${marker}`, version: "4.0.0" }), + }, + { + id: "D9e", + plugin: "carboneIo", + variant: { actionName: CARBONE_TEMPLATE_ACTION }, + auth: (marker) => ({ headers: { authorization: `Bearer e2e-carbone-${marker}` }, config: { "bearerAuth.value": `e2e-carbone-${marker}` } }), + operationPath: (marker) => `/template/e2e-template-${marker}`, + operationQuery: "", + operationHeaders: { "carbone-version": CARBONE_VERSION }, + data: (marker) => ({ success: true, data: { id: `e2e-template-${marker}` } }), + }, +]; + +/** The variant of a row with its marker-bound action keys (the template id). */ +function variantOf(row: WrapperRow, marker: string): QueryVariant { + return row.id === "D9e" + ? { ...row.variant, action: { [CARBONE_TEMPLATE_ID_KEY]: `e2e-template-${marker}`, [CARBONE_VERSION_KEY]: CARBONE_VERSION } } + : row.variant; +} + +/** The path and query string a row's operation is requested with below `base`. */ +function requestPathOf(row: WrapperRow, marker: string, base: string): string { + return `${base}${row.operationPath(marker)}${row.operationQuery ? `?${row.operationQuery}` : ""}`; +} + +/** The path of the canned answer: the operation's path without its query string. */ +function answerPathOf(row: WrapperRow, marker: string, base: string): string { + return `${base}${row.operationPath(marker)}`; +} + +test.describe("OpenAPI wrapper data sources against the echo", NODE_SERVICE_DETAILS, () => { + for (const row of ROWS) { + const details = row.id === "D9d" ? CARBONE_STATUS_DETAILS : {}; + test(`${row.id} ${row.plugin}${row.variant.actionName ? ` ${row.variant.actionName}` : ""}: the operation reaches the server URL with its credentials and answers the canned data`, details, async ({ page, apiUser, echo }) => { + const marker = uniqueMarker(); + const auth = row.auth(marker); + const data = row.data(marker); + await echo.answer(answerPathOf(row, marker, ""), canned(data)); + const datasourceId = await wrapperDatasource(page, apiUser, row.plugin, { serverURL: echo.url, ...auth.config }); + const appId = await wrapperApp(page, apiUser, row.plugin, datasourceId, variantOf(row, marker)); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const record = onlyRecord(await echo.received(), "the echo received exactly one request"); + expectRequest(record, echo, { path: `${echo.path}${requestPathOf(row, marker, "")}`, headers: { ...auth.headers, ...row.operationHeaders } }, row.plugin); + expect(envelopeOf(answer).data, "the answer is the body of the echo's canned reply").toEqual(data); + }); + } +}); + +test.describe("Lowcoder API spec versions", NODE_SERVICE_DETAILS, () => { + test("D9f lowcoder: every spec version sends the same current-user request with the token as a Bearer header", async ({ page, apiUser, echo }) => { + const marker = uniqueMarker(); + const token = `e2e-lowcoder-${marker}`; + for (const version of LOWCODER_SPEC_VERSIONS) await echo.answer(`/${version}/api/users/currentUser`, canned({ version })); + expect(await echo.received(), "before the runs the echo holds nothing of this test").toEqual([]); + + for (const version of LOWCODER_SPEC_VERSIONS) { + const datasourceId = await wrapperDatasource(page, apiUser, "lowcoder", { serverURL: `${echo.url}/${version}`, "bearerAuth.value": token, specVersion: version }); + const answer = await runDraft(page, await wrapperApp(page, apiUser, "lowcoder", datasourceId)); + expectSucceeded(answer); + expect(envelopeOf(answer).data, `${version}: the canned answer of its own path`).toEqual({ version }); + } + + const records = await echo.received(); + expect(records, "one request per version").toHaveLength(LOWCODER_SPEC_VERSIONS.length); + LOWCODER_SPEC_VERSIONS.forEach((version, index) => { + expectRequest(records[index] as EchoRecord, echo, { path: `${echo.path}/${version}/api/users/currentUser`, headers: { authorization: `Bearer ${token}` } }, version); + }); + }); +}); + +test.describe("OpenAI", NODE_SERVICE_DETAILS, () => { + test("D9g OpenAI: a chat completion posts its JSON body to the server URL with the key and answers the canned completion", async ({ page, apiUser, echo }) => { + const marker = uniqueMarker(); + const key = `e2e-openai-${marker}`; + const body = { model: `e2e-model-${marker}`, messages: [{ role: "user", content: `hello ${marker}` }] }; + const completion = { id: `e2e-completion-${marker}`, object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: `hi ${marker}` } }] }; + await echo.answer("/chat/completions", canned(completion)); + const datasourceId = await wrapperDatasource(page, apiUser, "OpenAI", { serverURL: echo.url, apiKey: key, specVersion: OPENAI_SPEC_V2 }); + const appId = await wrapperApp(page, apiUser, "OpenAI", datasourceId, { actionName: CHAT_ACTION, action: { [CHAT_BODY_KEY]: JSON.stringify(body) } }); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const record = onlyRecord(await echo.received(), "the echo received exactly one request"); + const sent = JSON.stringify(body); + expectRequest( + record, + echo, + { method: "POST", path: `${echo.path}/chat/completions`, body: sent, headers: { authorization: `Bearer ${key}`, "content-type": JSON_CONTENT_TYPE, "content-length": String(Buffer.byteLength(sent)) } }, + "chat completion", + ); + expect(envelopeOf(answer).data, "the answer is the body of the echo's canned reply").toEqual(completion); + }); + + test("D9h OpenAI: on the spec version v1.0, chosen or by default, the key is sent nowhere; on v2.3 it is sent as a Bearer header", OPENAI_V1_AUTH_DETAILS, async ({ page, apiUser, echo }) => { + const marker = uniqueMarker(); + const key = `e2e-openai-${marker}`; + const sides = [ + { side: "default", config: {} }, + { side: "v1", config: { specVersion: OPENAI_SPEC_V1 } }, + { side: "v2", config: { specVersion: OPENAI_SPEC_V2 } }, + ]; + for (const { side } of sides) await echo.answer(`/${side}/models`, canned({ side })); + expect(await echo.received(), "before the runs the echo holds nothing of this test").toEqual([]); + + for (const { side, config } of sides) { + const datasourceId = await wrapperDatasource(page, apiUser, "OpenAI", { serverURL: `${echo.url}/${side}`, apiKey: key, ...config }); + const answer = await runDraft(page, await wrapperApp(page, apiUser, "OpenAI", datasourceId)); + expectSucceeded(answer); + expect(envelopeOf(answer).data, `${side}: the canned answer of its own path`).toEqual({ side }); + } + + const records = await echo.received(); + expect(records, "one request per data source").toHaveLength(sides.length); + // control: with the same key on the same server the v2.3 document sends it, so the missing header below is the plugin's, not the echo's + expectRequest(onlyRecord(recordsUnder(records, echo, "/v2"), "v2.3 sent one request"), echo, { path: `${echo.path}/v2/models`, headers: { authorization: `Bearer ${key}` } }, "v2.3"); + // Measured on the images `3.0.0-e2e` and `3.0.1-e2e`: the v1.0 document names its scheme `ApiKey`, the plugin hands the key over as `ApiKeyAuth.value`, so no header is sent (NSD-7 candidate, see OPENAI_V1_AUTH_DEFECT). + expectRequest(onlyRecord(recordsUnder(records, echo, "/default"), "the default version sent one request"), echo, { path: `${echo.path}/default/models` }, "default version"); + expectRequest(onlyRecord(recordsUnder(records, echo, "/v1"), "v1.0 sent one request"), echo, { path: `${echo.path}/v1/models` }, "v1.0"); + expect(JSON.stringify([records[0], records[1]]).includes(key), "the key is on no part of the v1.0 and default requests").toBe(false); + }); +}); + +test.describe("an error answer", NODE_SERVICE_DETAILS, () => { + test("D9i apiTemplate: an error status answers its body as a successful result", ERROR_STATUS_DETAILS, async ({ page, apiUser, echo }) => { + const marker = uniqueMarker(); + const row = ROWS.find((candidate) => candidate.plugin === "apiTemplate") as WrapperRow; + const auth = row.auth(marker); + const body = { status: "error", message: `e2e-missing-${marker}` }; + await echo.answer(answerPathOf(row, marker, ""), canned(body, HTTP_NOT_FOUND)); + const datasourceId = await wrapperDatasource(page, apiUser, row.plugin, { serverURL: echo.url, ...auth.config }); + const appId = await wrapperApp(page, apiUser, row.plugin, datasourceId); + + const answer = await runDraft(page, appId); + + // control: the request reached the echo and the echo answered 404 (the canned answer of this path) + const record = onlyRecord(await echo.received(), "the request reached the echo"); + expectRequest(record, echo, { path: `${echo.path}${requestPathOf(row, marker, "")}`, headers: auth.headers }, row.plugin); + expectRan(answer); + // Measured on the images `3.0.0-e2e` and `3.0.1-e2e`: `runOpenApi` returns the body of an error answer as the result (NSD-4 candidate, see ERROR_STATUS_SUCCESS_DEFECT), so the 404 is reported as a successful query. + expect(envelopeOf(answer).success, "the 404 is reported as success").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code of the 404").toBe(QUERY_CODE_OK); + expect(envelopeOf(answer).data, "the result is the error body").toEqual(body); + }); +}); + +/** The APITemplate request of the control in the UiPath tests: it reaches the same echo target, so a missing UiPath request is not an unreachable echo. */ +async function expectApiTemplateReachesEcho(page: Page, apiUser: RegisteredUser, echo: EchoTarget, marker: string): Promise { + const row = ROWS.find((candidate) => candidate.plugin === "apiTemplate") as WrapperRow; + const auth = row.auth(marker); + await echo.answer(answerPathOf(row, marker, ""), canned(row.data(marker))); + const datasourceId = await wrapperDatasource(page, apiUser, row.plugin, { serverURL: echo.url, ...auth.config }); + const answer = await runDraft(page, await wrapperApp(page, apiUser, row.plugin, datasourceId)); + expectSucceeded(answer); + expectRequest(onlyRecord(await echo.received(), "the control query's request reached the echo"), echo, { path: `${echo.path}${requestPathOf(row, marker, "")}`, headers: auth.headers }, "control (apiTemplate)"); +} + +test.describe("UiPath", NODE_SERVICE_DETAILS, () => { + test("D9j uiPath: a query fails with a stack overflow of the plugin and sends no request", UIPATH_DETAILS, async ({ page, apiUser, echo }) => { + const marker = uniqueMarker(); + const datasourceId = await wrapperDatasource(page, apiUser, "uiPath", { serverURL: echo.url, "Authorization.value": `e2e-uipath-${marker}` }); + const appId = await wrapperApp(page, apiUser, "uiPath", datasourceId); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectRan(answer); + // Measured on the images `3.0.0-e2e` and `3.0.1-e2e` (NSD-6 candidate, see UIPATH_DEFECT). + expect(envelopeOf(answer).success, "the query failed").toBe(false); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_FAILED); + expect(envelopeOf(answer).message, "node-service's message").toBe(UIPATH_FAILURE_MESSAGE); + expect(await echo.received(), "no request left the plugin").toEqual([]); + // positive control: another wrapper's query against the same echo target arrives (the empty list above is not an unreachable echo) + await expectApiTemplateReachesEcho(page, apiUser, echo, marker); + }); + + test("D9k uiPath: the data source form's query configuration request fails with HTTP 500 / code 5000, while the same request for APITemplate succeeds and lists its operations", UIPATH_DETAILS, async ({ page, apiUser, echo }) => { + expect(apiUser.orgId, "the test is signed in (the route needs a session)").not.toBe(""); + // the request body is the key of node-service's in-memory cache: the target's URL makes both bodies unique to this test + const dataSourceConfig = { serverURL: echo.url, ...FORM_DEFAULTS }; + + const answer = await pluginDynamicConfigRaw(page.request, [{ pluginName: "uiPath", path: QUERY_CONFIG_PATH, dataSourceConfig }]); + + // Measured on the images `3.0.0-e2e` and `3.0.1-e2e` (NSD-6 candidate, see UIPATH_DEFECT): the request for the UiPath document fails, so the editor + // cannot list a single operation. The test asserts the failure of this request and, below, that the same request shape succeeds for another + // plugin; the cause (a `RangeError: Maximum call stack size exceeded` in `getSchemaExample`) was seen in node-service's log while recording, the suite cannot read that log. + expect(answer.status, "the HTTP status").toBe(HTTP_SERVER_ERROR); + expect(answer.code, "the API code").toBe(DYNAMIC_CONFIG_ERROR_CODE); + expect((answer.json as { message?: string; success?: boolean }).message, "the message").toBe(DYNAMIC_CONFIG_ERROR_MESSAGE); + expect((answer.json as { success?: boolean }).success, "success").toBe(false); + // positive control: the identical request (same path and data source settings) for APITemplate succeeds and lists its operations, so the + // failure above is specific to the UiPath document and not to the route, the session or the request shape + const control = await pluginDynamicConfigRaw(page.request, [{ pluginName: "apiTemplate", path: QUERY_CONFIG_PATH, dataSourceConfig }]); + expectRan(control); + expect((control.json as { success?: boolean }).success, "the control request succeeded").toBe(true); + const entry = (control.json as { data?: { actions?: { actionName?: string }[] }[] }).data?.[0]; + expect(entry?.actions?.map((action) => action.actionName), "the operations APITemplate's configuration lists").toContain("list_templates"); + }); + + test("D9l uiPath: a folders query reaches the server URL with the token as a Bearer header and answers the canned data", UIPATH_QUARANTINE_DETAILS, async ({ page, apiUser, echo }) => { + const marker = uniqueMarker(); + const token = `e2e-uipath-${marker}`; + const data = { "@odata.count": 1, value: [{ Id: 1, DisplayName: `E2E folder ${marker}` }] }; + await echo.answer("/odata/Folders", canned(data)); + const datasourceId = await wrapperDatasource(page, apiUser, "uiPath", { serverURL: echo.url, "Authorization.value": token }); + const appId = await wrapperApp(page, apiUser, "uiPath", datasourceId); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + // The desired behaviour, not a measured one: it fails today (D9j). `Bearer ` exactly, not doubled and not missing. + expectSucceeded(answer); + const record = onlyRecord(await echo.received(), "the echo received exactly one request"); + expectRequest(record, echo, { path: `${echo.path}/odata/Folders`, headers: { authorization: `Bearer ${token}` } }, "uiPath"); + expect(envelopeOf(answer).data, "the answer is the body of the echo's canned reply").toEqual(data); + }); +}); + +/** + * How long the echo withholds the answers of D9m until all queries of the test are waiting at it. The slowest start is OpenAI's v2.3 + * document (825 KB, dereferenced on every run, one run after the other on node-service's single thread); the 10 s query timeout of the app + * is the outer limit. + */ +const BARRIER_TIMEOUT_MS = 8_000; + +/** How many queries run at once against each plugin, and the share of them per server URL: half and half. OpenAI's document is large, so it gets fewer. */ +const CONCURRENT_RUNS: Record = { lowcoder: 8, apiTemplate: 8, carboneIo: 8, OpenAI: 4 }; + +test.describe("concurrent queries of one plugin", NODE_SERVICE_DETAILS, () => { + for (const [plugin, runs] of Object.entries(CONCURRENT_RUNS)) { + test(`D9m ${plugin}: queries submitted together against two server URLs each reach their own server, with all requests waiting at the echo at once`, async ({ page, apiUser, echo }) => { + const row = ROWS.find((candidate) => candidate.plugin === plugin) as WrapperRow; + const marker = uniqueMarker(); + const auth = row.auth(marker); + const sides = ["a", "b"] as const; + const apps: Record = {}; + for (const side of sides) { + await echo.answer(answerPathOf(row, marker, `/${side}`), { ...canned({ side }), barrier: { subPath: "/", count: runs, timeoutMs: BARRIER_TIMEOUT_MS } }); + const datasourceId = await wrapperDatasource(page, apiUser, plugin, { serverURL: `${echo.url}/${side}`, ...auth.config }); + apps[side] = await wrapperApp(page, apiUser, plugin, datasourceId, variantOf(row, marker)); + } + expect(await echo.received(), "before the runs the echo holds nothing of this test").toEqual([]); + + const runsOf = Array.from({ length: runs }, (_, index) => sides[index % sides.length] as (typeof sides)[number]); + // the echo answers only once all `runs` requests are waiting at it, so success below proves all requests were waiting at the echo at the same time + const answers = await Promise.all(runsOf.map((side) => runDraft(page, apps[side] as string))); + + answers.forEach((answer, index) => { + const side = runsOf[index]; + expectSucceeded(answer); + expect(envelopeOf(answer).data, `run ${index} against server ${side}: the data of its own server`).toEqual({ side }); + }); + const records = await echo.received(); + expect(records, "one request per run").toHaveLength(runs); + for (const side of sides) { + const own = recordsUnder(records, echo, `/${side}`); + expect(own, `server ${side} received exactly its share`).toHaveLength(runs / sides.length); + own.forEach((record, index) => { + expectRequest(record, echo, { path: `${echo.path}${requestPathOf(row, marker, `/${side}`)}`, headers: { ...auth.headers, ...row.operationHeaders } }, `server ${side}, request ${index}`); + }); + } + }); + } +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index f8559d66e3..b9c68c60f1 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -250,6 +250,49 @@ test.describe("node-service data source helpers", { tag: [TAGS.NODE_SERVICE] }, }); }); + test("the Lowcoder API, OpenAI, APITemplate, Carbone and UiPath recordings are the form's body and a query (the editor's saved query for the first four, a hand-built one for UiPath), with no value of the recording session", () => { + // the form of these plugins has no dynamic config, so the body holds the typed fields and the two defaults only (the spec version + // of Lowcoder and OpenAI is a select that was left at its default, so it is not in the body) + const expectations = [ + { id: "lowcoder", fields: ["bearerAuth.value"], action: "getUserInfo" }, + { id: "OpenAI", fields: ["apiKey"], action: "listModels" }, + { id: "apiTemplate", fields: ["ApiKeyAuth.value"], action: "list_templates" }, + { id: "carboneIo", fields: ["bearerAuth.value"], action: "get_status" }, + { id: "uiPath", fields: ["Authorization.value"], action: "Folders_Get" }, + ]; + for (const { id, fields, action } of expectations) { + const datasource = recordedPluginDatasource(id); + const query = recordedPluginQuery(id); + const config = datasource.datasourceConfig; + expect(datasource.type, `${id}: the data source type`).toBe(id); + expect(Object.keys(datasource), `${id}: no workspace id`).toEqual(["name", "type", "datasourceConfig"]); + expect(Object.keys(config), `${id}: the form fields`).toEqual(["serverURL", ...fields, "authConfigType", "sslCertVerificationType"]); + expect(config.serverURL, `${id}: the placeholder server URL`).toBe(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL); + for (const field of fields) expect(config[field], `${id}: ${field} is a placeholder`).toBe("placeholder"); + expect(query.compType, `${id}: the query type`).toBe(id); + expect(query.comp.actionName, `${id}: the recorded operation`).toBe(action); + expect(Object.keys(query), `${id}: only what the builder keeps`).toEqual(["compType", "comp"]); + expect(query.comp.headers, `${id}: the editor's empty header row`).toEqual([{ key: "", value: "" }]); + const text = [`${id}Datasource.json`, `${id}Query.json`].map((file) => readFileSync(join(RECORDED_PLUGINS_DIR, id, file), "utf8")).join("\n"); + expect(text, `${id}: a 24-hex id`).not.toMatch(/\b[0-9a-f]{24}\b/); + expect(text, `${id}: an echo address`).not.toContain("e2e-echo"); + expect(text, `${id}: an epoch of 10 digits or more`).not.toMatch(/\b\d{10,}\b/); + } + expect(recordedPluginQuery("apiTemplate").comp.action, "apiTemplate: the editor's empty defaults of the operation's parameters").toEqual({ + "query_@_limit": "", + "query_@_offset": "", + "query_@_format": "", + "query_@_template_id": "", + "query_@_group_name": "", + "query_@_with_layer_info": "", + }); + // the other recordings have no action parameters; UiPath's has none either, but the editor could not save it: its query configuration + // fails (the form lists no operation), so the query is the shape the editor saved for the other four plugins, built by hand + for (const id of ["lowcoder", "OpenAI", "carboneIo", "uiPath"]) { + expect(recordedPluginQuery(id).comp.action, `${id}: no action parameters`).toEqual({}); + } + }); + test("parseBasicAuthorization decodes user and password, and reads anything else as not Basic credentials", () => { const header = (text: string): string => `Basic ${Buffer.from(text, "utf8").toString("base64")}`; expect(parseBasicAuthorization(header("user:secret"))).toEqual({ user: "user", password: "secret" }); From a3019f59ea940718979bfaa99423917978253435 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 19:01:37 +0100 Subject: [PATCH 12/20] test: add DynamoDB and S3 node-service data source scenarios Adds recorded DynamoDB and S3 data source and query fixtures, one per action, and scenarios that point each plugin's endpoint at the run's echo target: every request the AWS SDK sends is asserted in full (method, path, query, body, header set and the signing scope by shape), together with the answers the plugins return, error answers, signed URLs and the form's connection test. S3 reads with an empty bucket are characterised and annotated as a defect candidate. The run script now passes the echo's IP address on the run network to the test runner as E2E_ECHO_IP, and echoUrlByIp turns an echo target URL into one addressed by that IP, so bucket calls stay on the run network instead of resolving a . name. The address is validated strictly and covered by unit tests. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 8 +- e2e/README.md | 28 +- .../plugins/dynamodb/dynamodbDatasource.json | 12 + .../dynamodb/dynamodbGetItemQuery.json | 16 + .../dynamodb/dynamodbListTablesQuery.json | 15 + .../dynamodb/dynamodbPutItemQuery.json | 16 + .../dsl/plugins/dynamodb/dynamodbQuery.json | 16 + e2e/fixtures/dsl/plugins/s3/s3Datasource.json | 12 + .../dsl/plugins/s3/s3DeleteFileQuery.json | 16 + .../dsl/plugins/s3/s3ListObjectsQuery.json | 19 + e2e/fixtures/dsl/plugins/s3/s3Query.json | 13 + .../dsl/plugins/s3/s3ReadFileQuery.json | 17 + .../dsl/plugins/s3/s3UploadDataQuery.json | 20 + e2e/scripts/run-in-docker.sh | 4 +- e2e/src/constants.ts | 7 + e2e/src/datasource/node-plugins.ts | 31 + e2e/src/dsl/recorded.ts | 18 +- e2e/src/security/echo.ts | 28 +- e2e/tests/datasource/plugin-aws-sdk.spec.ts | 743 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 67 ++ e2e/tests/foundation/security-echo.spec.ts | 32 +- 21 files changed, 1112 insertions(+), 26 deletions(-) create mode 100644 e2e/fixtures/dsl/plugins/dynamodb/dynamodbDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/dynamodb/dynamodbGetItemQuery.json create mode 100644 e2e/fixtures/dsl/plugins/dynamodb/dynamodbListTablesQuery.json create mode 100644 e2e/fixtures/dsl/plugins/dynamodb/dynamodbPutItemQuery.json create mode 100644 e2e/fixtures/dsl/plugins/dynamodb/dynamodbQuery.json create mode 100644 e2e/fixtures/dsl/plugins/s3/s3Datasource.json create mode 100644 e2e/fixtures/dsl/plugins/s3/s3DeleteFileQuery.json create mode 100644 e2e/fixtures/dsl/plugins/s3/s3ListObjectsQuery.json create mode 100644 e2e/fixtures/dsl/plugins/s3/s3Query.json create mode 100644 e2e/fixtures/dsl/plugins/s3/s3ReadFileQuery.json create mode 100644 e2e/fixtures/dsl/plugins/s3/s3UploadDataQuery.json create mode 100644 e2e/tests/datasource/plugin-aws-sdk.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index a968b0a468..4792894d68 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,7 +129,7 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). @@ -182,16 +182,16 @@ MUST NOT: | component from its recording | `component`, `recordedItem`, `recordedHook`, `recordedHookOf`, `hook` | `src/dsl/builders.ts`, `src/dsl/recorded.ts` | | layout and app | `stackItems`, `containerOf`, `appDsl`, `button`, `text`, `input`, `table`, `barChart` | `src/dsl/builders.ts` | | events and actions | `eventHandler`, `executeQuery`, `setTempState`, `runScript`, `executeComp`, `triggerModuleEvent` | `src/dsl/builders.ts` | -| queries, state, logic | `postgresQuery`, `jsQuery`, `n8nWorkflowsQuery` (recordings in `fixtures/dsl/n8n/`, loaded by `recordedN8nQuery` and `recordedN8nDatasource`), `nodePluginQuery` (recordings in `fixtures/dsl/plugins//`, loaded by `recordedPluginQuery` and `recordedPluginDatasource`, checked by `parsePluginRecording`), `tempState`, `transformer`, `dataResponder` | `src/dsl/builders.ts` | +| queries, state, logic | `postgresQuery`, `jsQuery`, `n8nWorkflowsQuery` (recordings in `fixtures/dsl/n8n/`, loaded by `recordedN8nQuery` and `recordedN8nDatasource`), `nodePluginQuery` (recordings in `fixtures/dsl/plugins//`, loaded by `recordedPluginQuery` (a plugin whose saved query differs by action has one recording per action: `Query.json`, `recordedPluginQuery(id, "")`) and `recordedPluginDatasource`, checked by `parsePluginRecording`), `tempState`, `transformer`, `dataResponder` | `src/dsl/builders.ts` | | modules | `moduleApp`, `moduleInstance`, `scenarioModuleDsl`, `waitForSavedInstance`, `HandlerRetryBudget` | `src/dsl/builders.ts`, `src/modules/moduleScenario.ts` | | bound text, nested override, seeded view | `boundText`, `withValueAt`, `openSeededView` | `src/components/scenario.ts` | | containers and slots | `containerWithChildren`, `slotChild`, `slotContainers`, `openSeededApp` | `src/simple-components/seed.ts` | | catalogue, saved-DSL polling | `INSERT_TYPES`, `HOOK_TYPES`, `searchTextOf`, `waitForSavedType`, `prepareForPublish` | `src/components/insert-catalog.ts`, `src/components/insert-all.ts` | | notes and products queries | `selectProductsQuery`, `selectNotesQuery`, `noteWriteQuery`, `insertUpdateDeleteQueries` | `src/datasource/notes-queries.ts` | -| node-service plugin ids and catalogue | `NODE_PLUGIN_IDS`, `nodePluginIdsOf`, `NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL`, `OPEN_API_FIXTURE_SPEC` (canned OpenAPI document for the generic `openApi` plugin), `parseBasicAuthorization` (decodes a Basic `Authorization` header an echo record holds) | `src/datasource/node-plugins.ts` | +| node-service plugin ids and catalogue | `NODE_PLUGIN_IDS`, `nodePluginIdsOf`, `NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL`, `OPEN_API_FIXTURE_SPEC` (canned OpenAPI document for the generic `openApi` plugin), `parseBasicAuthorization` (decodes a Basic `Authorization` header an echo record holds), `parseSigV4Authorization` (splits an AWS SigV4 `Authorization` header into key, date, region, service, signed headers and signature) | `src/datasource/node-plugins.ts` | | negative and counter reads, local storage | `expectTextStays`, `countAfterEquals`, `parseCounter`, `rawLocalStorage` | `src/logic/helpers.ts` | | media | `PNG_RED`, `PNG_BLUE`, `WAV`, `WEBM`, `MP4`, `PDF`, `PDF_RAW_B64` | `src/media.ts` | -| security actors, quarantine, answers, tokens | `Actor`, `adminOfApiUser`, `joinWorkspace`, `makeDeveloper`, `makeAdmin`, `grantApp`, `seedPrivateApp`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `securityTestDetails`, `securityCandidateDetails`, `expectAnswer`, `expectDeniedAs`, `forgeApiKeyToken`, `forgeUnsignedToken`, `withRandomSignature`, `tokenIsSignedWith`, `superAdminCredentials`, `SUPER_ADMIN_ENV`, `enterpriseAdmin` (ENTERPRISE stack: an actor the super admin makes admin of the one workspace), `echoTargetPath`, `echoReadPrefix`, `echoBaseUrl`, `recordsContain` (requests the SERVER makes, read back from the HTTP echo sidecar: the `echo` fixture gives a test its own target `url` and `received()`; a denial must follow a positive control that the echo does receive from that path; compare a secret with `recordsContain(...)` as a boolean, never as a matcher's value) (the `actor`, `superAdmin` and `echo` fixtures are in `src/fixtures.ts`; the raw-answer helper `apiRaw` and the other security API helpers are in `src/api/client.ts`) | `src/security/actors.ts`, `scene.ts`, `quarantine.ts`, `assertions.ts`, `tokens.ts`, `super-admin.ts`, `enterprise.ts`, `echo.ts` | +| security actors, quarantine, answers, tokens | `Actor`, `adminOfApiUser`, `joinWorkspace`, `makeDeveloper`, `makeAdmin`, `grantApp`, `seedPrivateApp`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `securityTestDetails`, `securityCandidateDetails`, `expectAnswer`, `expectDeniedAs`, `forgeApiKeyToken`, `forgeUnsignedToken`, `withRandomSignature`, `tokenIsSignedWith`, `superAdminCredentials`, `SUPER_ADMIN_ENV`, `enterpriseAdmin` (ENTERPRISE stack: an actor the super admin makes admin of the one workspace), `echoTargetPath`, `echoReadPrefix`, `echoBaseUrl`, `echoUrlByIp` (an echo target URL with its host replaced by the echo's IP address, `E2E_ECHO_IP`: for a plugin that derives a host name from its endpoint, e.g. an S3 bucket call; never address a bucket of the `e2e-echo` alias), `recordsContain` (requests the SERVER makes, read back from the HTTP echo sidecar: the `echo` fixture gives a test its own target `url` and `received()`; a denial must follow a positive control that the echo does receive from that path; compare a secret with `recordsContain(...)` as a boolean, never as a matcher's value) (the `actor`, `superAdmin` and `echo` fixtures are in `src/fixtures.ts`; the raw-answer helper `apiRaw` and the other security API helpers are in `src/api/client.ts`) | `src/security/actors.ts`, `scene.ts`, `quarantine.ts`, `assertions.ts`, `tokens.ts`, `super-admin.ts`, `enterprise.ts`, `echo.ts` | | pages | `EditorPage`, `AppViewPage`, `PropertyPanel`, `QueryPanel`, `TableView`, `ExtensionsPanel`, `AppListPage`, `AuthPage`, `LoginPage`, `UserMenu`, `SettingPage`, `DatasourcePage` | `src/pages/` | Accepted exception to the `test` import rule: stack-free unit specs that open no browser page (no `page`, no app) may diff --git a/e2e/README.md b/e2e/README.md index 8ea2f589bb..1a7f6601b2 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), D5 to D9, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -38,7 +38,7 @@ lifecycle (insert, save, publish, load) is covered by S1 when `@insert-all` runs `products` (25 shared read-only rows), `notes` (writes, owner-scoped). Host name in `E2E_POSTGRES_HOST`; connection constants are `POSTGRES` in `src/constants.ts`. - **HTTP echo sidecar** (`scripts/echo-server.js`, started by `run-in-docker.sh` on the already pinned runner image, so no extra image or - download; network alias `e2e-echo`, port 8080; the runner gets `E2E_ECHO_URL`): the target of the requests the SERVER makes inside the + download; network alias `e2e-echo`, port 8080; the runner gets `E2E_ECHO_URL` and the sidecar's IP address on the run network as `E2E_ECHO_IP`): the target of the requests the SERVER makes inside the app container (node-service's npm registry proxy, the n8n plugin). It records `{ method, path, headers, body }` of every request in memory (bodies cut at 65536 bytes, 10000 records kept) and answers `{}`; `GET /__e2e/requests?prefix=

` returns the records whose path starts with `

`. The `echo` fixture of `src/fixtures.ts` gives each test its own target `/t/---` @@ -188,6 +188,7 @@ data; its tests are untagged. | `LOWCODER_BASE_URL` | config | origin under test; set by the script; any URL works for `--list` | | `E2E_POSTGRES_HOST` | `src/postgres.ts` | set by the script | | `E2E_ECHO_URL` | run-in-docker.sh, `src/security/echo.ts` (`ECHO_ENV`) | set by the script: `http://e2e-echo:8080`, the HTTP echo sidecar; the `echo` fixture throws, naming the variable, when it is missing | +| `E2E_ECHO_IP` | run-in-docker.sh, `src/security/echo.ts` (`ECHO_IP_ENV`) | set by the script: the echo sidecar's IP address on the run network (the one `--add-host e2e-echo:` uses). For a plugin that derives a host name from its endpoint (the AWS SDK addresses a bucket of a host NAME as `.`, which the alias mapping does not cover); `echoUrlByIp(url, env)` swaps an echo URL's host for it and throws, naming the variable, when it is missing or not an IPv4 address | | `E2E_SUPERUSER_USERNAME`, `E2E_SUPERUSER_PASSWORD` | run-in-docker.sh, `src/security/super-admin.ts` | set by the script for each run (a caller's value is overwritten; the password is random per run and never printed); the app gets the same pair as `LOWCODER_SUPERUSER_*` | | `BASE_IMAGE`, `TARGET_IMAGE`, `CLIENT_REF` | build-e2e-image.sh | build inputs (defaults `...:3.0.0`, `...:3.0.0-e2e`, tag `3.0.0`) | @@ -209,7 +210,7 @@ e2e/ fixtures/sql/init.sql PostgreSQL data: items, products, notes fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb`, `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate) + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb`, `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate), `dynamodb` and `s3` (the form's body, and one query recording per action because the saved query differs by action: `Query.json` is the editor's default action, the others are `Query.json`, loaded by `recordedPluginQuery(id, "")`: `dynamodb` Query, ListTables, GetItem, PutItem; `s3` listBuckets, ListObjects, ReadFile, UploadData, DeleteFile) src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -225,7 +226,7 @@ e2e/ components/ insert-all.ts (S1 helpers), insert-catalog.ts (112 types), scenario.ts (boundText, withValueAt, openSeededView) simple-components/seed.ts container and slot seeds, openSeededApp modules/moduleScenario.ts module scenario DSL, saved-instance polling, HandlerRetryBudget - security/echo.ts `echoTargetPath`, `echoReadPrefix`, `echoBaseUrl`, `recordsContain` (boolean: never prints the needle), `EchoRecord`, `EchoTarget` (the `echo` fixture) + security/echo.ts `echoTargetPath`, `echoReadPrefix`, `echoBaseUrl`, `echoUrlByIp`, `recordsContain` (boolean: never prints the needle), `EchoRecord`, `EchoTarget` (the `echo` fixture) security/actors.ts, scene.ts, quarantine.ts, assertions.ts, tokens.ts, super-admin.ts security helpers (joinWorkspace, makeDeveloper, grantApp, seedPrivateApp, adminOfApiUser, sceneOf, memberOf, roleOf), the quarantine list and `securityCandidateDetails`, `expectAnswer` (status and code), forged, unsigned and wrongly signed API-key tokens, `superAdminCredentials` (reads `SUPER_ADMIN_ENV`); security/enterprise.ts: `enterpriseAdmin` (the admin of the one workspace of the ENTERPRISE stack) reporters/d3-threshold-reporter.ts fails the run when more than half of S1 or M3 tests carry `D-3 retry` tests/ specs by area (catalogue below) @@ -253,15 +254,16 @@ Test titles carry these ids. - D7 the generic Open API plugin of node-service against the echo sidecar: the data source form's dynamic config reads the OpenAPI document from its URL (the echo serves a canned document) and answers the spec and the key field, an operation runs against the server URL with the key in the header the document names, the key comes from the data source (no key, no header), an error status answers its body as a successful result (NSD-4 candidate), the published view after a click, the dynamic config answer is cached in memory per request body, with no expiry (observation) (`@node-service`). - D8 the Open API wrapper plugins of node-service with a server URL (CouchDB, Jira, Datadog, WooCommerce, Supabase Management API) against the echo sidecar: one read-only operation each reaches the server URL (the target's path survives as the base path) with its credentials and answers the canned data, CouchDB JWT credential alone and with a Basic one (observation), WooCommerce server URL forms and refusal of v1/v2, a trailing slash after the API path doubles it (NSD-5 candidate), concurrent queries against two server URLs each reach their own server (`@node-service`). - D9 the Open API wrapper plugins of node-service with a server URL (Lowcoder API, OpenAI, APITemplate.io, Carbone, UiPath) against the echo sidecar: one read-only operation each reaches the server URL with its credentials and answers the canned data (Carbone `get_status` sends no token: observation), every Lowcoder spec version, an OpenAI chat completion posts its JSON body, OpenAI on spec version v1.0 sends no key (NSD-7 candidate), an error status answered as success (NSD-4 candidate), UiPath fails every query and its query configuration request (HTTP 500) and sends nothing (NSD-6 candidate; its desired behaviour is quarantined), concurrent queries against two server URLs each reach their own server (`@node-service`). +- D10 the DynamoDB and S3 plugins of node-service (AWS SDK v3) against the echo sidecar: a DynamoDB call is a signed JSON POST to `/ddb/` (`x-amz-target`, credential scope with the access key and region, the secret never sent), GetItem, PutItem and Query wrap the request's values and unwrap the answer's typed attributes, a service error fails the query with its message, the published view after a click; the S3 connection test lists the buckets (API and the form's Test Connection button), a refused test answers `code` 500 with the service's text (HTTP 200), a listBuckets query answers the names, every call that takes a bucket (listObjects with and without a presigned URL, readFile, uploadData, deleteFile) is path-style `/s3//` on the echo's IP address, a service error fails the query, a bucket call without a bucket sends nothing (readFile, uploadData and deleteFile show the SDK's text, NSD-8 candidate) (`@node-service`; the signed request's shape and the answer's path into the app, not the vendor service). - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue -Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`, after this branch's security fixes; this is a static listing, not a Docker run. A combined final run against an image built from this branch (tag `secfix-combined-e2e`) has since confirmed pass/fail for every scenario named in the per-defect rows below: 693/696 default tests passed, the 3 failures pre-existing or unrelated suite drift (documented in their own rows below)): -default **770 tests in 112 files**; with `E2E_INCLUDE_QUARANTINE=1` **784 in 113**; with `E2E_INCLUDE_SUPERADMIN=1` **775 in 112**; with both of those **789 in 113**; -with `E2E_INCLUDE_INSERT_ALL=1` **882 in 113**; with all three opt-in variables **901 in 114** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: +Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the current suite, `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (794 tests): 44 failed, 750 passed. The baseline from a clean worktree of the previous commit (770 tests, same command and image): 43 failed, 727 passed. The failing sets are the same except `SEC-R09d`, which is intermittent on both (5 repeats: 3 failed with the current tree, 2 failed on the baseline). The 44 failures are 25 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`, and `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag and by the baseline, not analysed one by one). No node-service scenario failed.): +default **794 tests in 113 files**; with `E2E_INCLUDE_QUARANTINE=1` **808 in 114**; with `E2E_INCLUDE_SUPERADMIN=1` **799 in 113**; with both of those **813 in 114**; +with `E2E_INCLUDE_INSERT_ALL=1` **906 in 114**; with all three opt-in variables **925 in 115** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 72 in 8 files (the 21 unit tests of `foundation/node-plugins.spec.ts` plus the 51 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests) and D9a to D9k with the four D9m tests (15 tests); a selection tag, they stay in the default run). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). Whether each of these PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 94 in 9 files (the 24 unit tests of `foundation/node-plugins.spec.ts` plus the 70 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each); a selection tag, they stay in the default run). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -310,7 +312,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | editor/js-query.spec.ts | a JS query written in the editor runs | @core | 1 | | editor/drop-size.spec.ts | a component dropped right after ready has width above 0 (D-5) | @quarantine | 1 | -### datasource (61) +### datasource (80) | File | Proves | Tags | Tests | |---|---|---|---| @@ -324,6 +326,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/plugin-openapi.spec.ts | D7: the generic Open API plugin against the echo sidecar (spec URL `/spec.json`, server URL `/api`; the document is `OPEN_API_FIXTURE_SPEC`: `GET /items`, operation `listItems`, parameter `q`, API key header `X-E2E-Key`, placeholder server). D7a the dynamic config call (`path` `$.dataSourceConfig.extra`) answers `[{data: {spec}, extraParams}]` with the key field `E2EKeyAuth.value` labelled `X-E2E-Key` and fetches the document with exactly one GET, D7b `listItems` sends `GET /api/items?q=` with `x-e2e-key` and answers the canned `[{id: 1}]`, D7c a data source with an empty `dynamicParamsConfig` sends no key header, D7d a canned 404 `{"message":"e2e-missing"}` is answered as `success: true`, `queryCode: "OK"`, data the 404 body (NSD-4 candidate), D7e the published view shows the first item's id only after the click (echo 0 requests before, exactly 1 after), D7f the same dynamic config request answers from the cache after the document changed on the echo (one fetch), while a request with another body fetches again; the cache is an in-process object keyed on path, query and body with no expiry (observation) | @node-service | 6 | | datasource/plugin-openapi-wrappers-data.spec.ts | D8: CouchDB, Jira, Datadog, WooCommerce and the Supabase Management API against the echo sidecar (server URL ``, one read-only operation of each bundled document). D8a couchdb `GET /_all_dbs` with `Authorization: Basic` of the configured user and password, D8b jira `GET /rest/api/3/myself` with Basic, D8c datadog `GET /api/v1/validate` with `dd-api-key` and `dd-application-key`, D8d woocommerce `GET /wp-json/wc/v3/products?context=view&order=asc&orderby=date&status=any&type=simple&stock_status=instock` with Basic, D8e supabaseApi `GET /v1/projects` with `Authorization: Bearer `; each asserts echo empty before, exactly one request (method, full path and query, no body, the complete header set) and the canned body as the query's data; D8f couchdb: a JWT credential alone is sent as `Authorization`, with a Basic credential too only the Basic one is (observation), each request asserted completely; D8g woocommerce: a plain, a slash-terminated and an already `/wp-json/wc/v3` server URL each give the API path once, `/wc/v1` and `/wc/v2` are refused with `only woocommerce api v3 is supported` and send nothing; D8h woocommerce: a server URL ending in `/wp-json/wc/v3/` gets the API path twice (NSD-5 candidate); D8i couchdb, woocommerce and datadog: 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 11 | | datasource/plugin-openapi-wrappers-apps.spec.ts | D9: the Lowcoder API, OpenAI, APITemplate.io, Carbone and UiPath against the echo sidecar (server URL ``, one read-only operation of each bundled document). D9a lowcoder `GET /api/users/currentUser` with `Authorization: Bearer `, D9b OpenAI (spec version v2.3) `GET /models` with `Authorization: Bearer `, D9c apiTemplate `GET /v2/list-templates` with `x-api-key`, D9d carboneIo `GET /status` with NO credential header (observation: that operation lists no security scheme), D9e carboneIo `GET /template/` with `Authorization: Bearer ` and `carbone-version: 4`; each asserts echo empty before, exactly one request (method, full path and query, body, the complete header set) and the canned body as the query's data; D9f lowcoder: spec versions v1.0 to v1.3 send the same request; D9g OpenAI: a chat completion `POST /chat/completions` carries the JSON body, `content-type`, `content-length` and the key, and answers the canned completion; D9h OpenAI: spec version v1.0, chosen or by default, sends no `Authorization` header while v2.3 with the same key does (NSD-7 candidate); D9i apiTemplate: a canned 404 body is reported as a successful result (NSD-4 candidate); D9j uiPath: a query fails with the message `Maximum call stack size exceeded` and sends no request, after a control that another wrapper's query reaches the same echo target (NSD-6 candidate); D9k uiPath: the form's query configuration request for the UiPath document answers 500 / code 5000 `get dynamic config error`, while the identical request for apiTemplate answers success and lists its operations (NSD-6 candidate; the test asserts the failure and the control, not its cause); D9l uiPath (`@quarantine`, not counted in the default run): the folders query should reach `GET /odata/Folders` with `Bearer ` exactly and answer the canned data, fails today; D9m lowcoder, apiTemplate, carboneIo and OpenAI: 8, 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 15 (+1 `@quarantine`) | +| datasource/plugin-aws-sdk.spec.ts | D10: DynamoDB and S3 against the echo sidecar (endpoints `/ddb` and `/s3`; bucket calls on the echo's IP address). Measured on 3.0.0-e2e and 3.0.1-e2e (the SDK version printed in its user agent is 3.668.0 on 3.0.0-e2e; the tests match the shape, not the version): the SDK keeps the endpoint's path, DynamoDB posts to `/ddb/`, S3 without a bucket gets `/s3/?x-id=ListBuckets`, and with a bucket on an IP-address endpoint it is path-style (`/s3//`, `Host` the IP address). Every request a D10 test makes is asserted completely: method, path and query, body, the whole header set (per-request values by shape: date, invocation id, user agents, signature), the credential scope (access key, date, region, service) and the signed-header list, and every D10 test that sends a request also asserts that the secret key is in no header, path or body of the echo's records (with a control that the access key is: it travels in the credential scope). The rows of D10q that send nothing assert that the echo holds no record, after which a control call with a bucket is asserted completely. The presigned URL of D10l is asserted by its stable query parameters and by shape, not by value. D10a DynamoDB ListTables (region `eu-central-1` in the scope, body `{TableName: "", Limit: 10}`, answer without `$metadata`), D10b GetItem wraps the key and unwraps a string, a number, a string set and a boolean, D10c PutItem wraps a number, a string and a boolean, D10d Query keeps the expression and unwraps the items, D10e a 400 `ResourceNotFoundException` fails the query (`Requested resource not found`, one request), D10f the published view after a click, D10g the connection test (`code` 1, `success`, `data` true; one `GET /s3/?x-id=ListBuckets`), D10h a 403 test answers HTTP 200 with `code` 500, `success` false and `Failed to connect data source: Access Denied.`, and the same body succeeds once the endpoint answers 200, D10i the form's Test Connection button shows that text, then `Connection Successful`, D10j listBuckets answers `[{name}]`, D10k listObjects is path-style on the IP with `delimiter`, `max-keys` and `prefix` and answers name, size, time, file URL, D10l `returnSignedUrl` adds a presigned URL (`X-Amz-Expires=300`, signed header `host`, no extra request), D10m readFile as text and base64, D10n uploadData of text and of base64 without a content type (`application/octet-stream`), D10o deleteFile, D10p a 403 and a 404 fail the query with the service's text, D10q a bucket call without a bucket sends nothing: listObjects says `Bucket is required`, readFile, uploadData and deleteFile say `Empty value provided for input HTTP label: Bucket.` (NSD-8 candidate), after a control that a call with a bucket reaches the echo. Not covered: a real DynamoDB or S3 service, the SDK's retry of a 5xx answer | @node-service | 19 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -468,13 +471,13 @@ first makes sure some admin exists (accepting both answers), so none depends on SEC-R09d (D-38) left the quarantine: the check took the workspace of the first id of a `HashSet`; each id is now decided in its own workspace (Java unit and MongoDB integration tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)). Accounting of the earlier 3.0.0 run `E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --workers=4 --reporter=list --grep "@quarantine" tests/security` (measured before the `@superadmin` tag existed and before the reassessment, so it listed 44 tests, 19 of which have since left the quarantine): 44 listed, 43 failed, 1 passed (SEC-R09d); the two quarantined tests of `foundation/security-helpers.spec.ts` are outside that folder. -### foundation (289 default, 292 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) +### foundation (294 default, 297 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) | File | Proves | Tags | Tests | |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), and `parseBasicAuthorization` | @node-service | 21 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb and s3 recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization` | @node-service | 24 | | foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources) | none | 27 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | @@ -487,7 +490,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | foundation/d3-threshold-reporter.spec.ts | D-3 gate verdicts of the reporter | none | 9 | | foundation/security-helpers.spec.ts | the security helpers of `src/api/client.ts`, `src/security/actors.ts` and `src/security/scene.ts` against the stack (`apiRaw`, `actor`, `joinWorkspace`, `makeDeveloper`, grants, folders, datasources, API keys, bundles, `publishBundle`, `setBundlePublicToAll`, `signIn`, `getApp`, `listGroupMembers`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `adminOfApiUser`, the `superAdmin` fixture, ...); 2 tests are `@quarantine` (D-45 API-key delete, D-46 bundle recycle) | none, @superadmin for 1, @quarantine for 2 | 37 default + 1 `@superadmin` + 2 quarantined | | foundation/security-pages.spec.ts | the page objects `SettingPage` (settings sidebar, members rows and role selects, provider page) and `DatasourcePage` (the form's save answer) as admin, developer and plain member, and `AppViewPage.openAndAwaitQuery` (the status of the query a seeded app runs on load) | none | 4 | -| foundation/security-echo.spec.ts | the echo sidecar (`scripts/echo-server.js` started on a loopback port: record and read back, per-target prefixes, control paths, body cut, canned answers, barriers) and `src/security/echo.ts`, `n8nDatasourceBody`, `npmRegistryPath` (no stack) | none | 19 | +| foundation/security-echo.spec.ts | the echo sidecar (`scripts/echo-server.js` started on a loopback port: record and read back, per-target prefixes, control paths, body cut, canned answers, barriers) and `src/security/echo.ts` (incl. `echoUrlByIp` and that `run-in-docker.sh` passes `E2E_ECHO_IP`), `n8nDatasourceBody`, `npmRegistryPath` (no stack) | none | 21 | | foundation/security-api-raw.spec.ts | `apiRaw` against a local server: status, code, body, params, request and response headers; `executeAppQueryRaw`'s path (no stack) | none | 8 | | foundation/security-quarantine.spec.ts | `securityTestDetails`, `securityCandidateDetails`, `lifecycleTestDetails`, `lifecycleCandidateDetails` and the two quarantine maps (no stack) | none | 16 | | foundation/lifecycle-pages.spec.ts | `ProfilePage`, `ProfileModal`, `UserMenu` (profile, create and switch workspace), `ApiKeysCard`, `WorkspacesPage`, `GroupsPage`, `ShareDialog`, `SettingPage` (invite link, operations), `PasswordRecoveryPage`, `LoginPage.forgotPasswordLink`, the invite dialog of `SettingPage` (send, notice), `ProvidersPage`, `ProfilePage.infoCount`, `SettingPage.openDetailOf`, the navigation and tour locators of `AppListPage` (`tourClose` on a UI sign-up) | none | 14 | @@ -521,6 +524,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-5 candidate | the WooCommerce plugin appends `wp-json/wc/v3` to a server URL unless it ends exactly in `/wc/v3`, so a server URL copied with a trailing slash (`/wp-json/wc/v3/`) is requested at `/wp-json/wc/v3/wp-json/wc/v3/products`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-data.spec.ts` D8h asserts today's behaviour (characterisation, default run), annotation `{type:"defect", description:"NSD-5 candidate"}`; it changes when a trailing slash is accepted | | NSD-6 candidate | the UiPath plugin cannot run: `getSchemaExample` (`plugins/openApi/util.ts`) recurses without end on a circular schema of the bundled document, so the query configuration (`POST /api/datasources/getPluginDynamicConfig`, path `$.queryConfig`) answers 500 / code 5000 `get dynamic config error` (the editor lists no operation and cannot save a UiPath query) and every query fails with `Maximum call stack size exceeded` before any request is sent; the cause (`RangeError: Maximum call stack size exceeded` at `getSchemaExample`, from a circular schema) was read in the app container's node-service log while recording, not asserted: the suite asserts only the HTTP 500 / code 5000 of the configuration request, the query's failure message and that no request is sent; measured on 3.0.0-e2e and 3.0.1-e2e. Whether UiPath sends its `Authorization` header (a doubled `Bearer`, or none) cannot be measured today. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9j and D9k assert today's behaviour after a control that another plugin reaches the echo / lists its operations (characterisation, default run), annotation `{type:"defect", description:"NSD-6 candidate"}`; D9l asserts the desired behaviour (`GET /odata/Folders` with `Authorization: Bearer ` exactly), `@quarantine`, same annotation; they change when the plugin runs | | NSD-7 candidate | an OpenAI data source on spec version `v1.0` (the version an empty choice selects) sends no `Authorization` header: the plugin hands the key over as `ApiKeyAuth.value`, the security scheme of the `v2.3` document, while the `v1.0` document names its scheme `ApiKey`; with `v2.3` the same key is sent as `Authorization: Bearer `; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9h asserts today's behaviour after a control that v2.3 sends the key to the same echo (characterisation, default run), annotation `{type:"defect", description:"NSD-7 candidate"}`; it changes when the key reaches the `v1.0` document's scheme | +| NSD-8 candidate | the S3 plugin checks the bucket itself only for `listObjects` (`Bucket is required`); `readFile`, `uploadData` and `deleteFile` with an empty bucket reach the AWS SDK, which refuses before any request with its own text `Empty value provided for input HTTP label: Bucket.`, so the user sees an SDK message and the checks are inconsistent; no request is sent in any of the four cases; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-aws-sdk.spec.ts` D10q asserts today's messages after a control that a call with a bucket reaches the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-8 candidate"}`; it changes when the three operations check the bucket like `listObjects` | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/fixtures/dsl/plugins/dynamodb/dynamodbDatasource.json b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbDatasource.json new file mode 100644 index 0000000000..0dae2dfd92 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbDatasource.json @@ -0,0 +1,12 @@ +{ + "name": "dynamodb", + "type": "dynamodb", + "datasourceConfig": { + "accessKey": "placeholder", + "secretKey": "placeholder", + "endpointUrl": "http://placeholder.invalid", + "region": "us-west-1", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} diff --git a/e2e/fixtures/dsl/plugins/dynamodb/dynamodbGetItemQuery.json b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbGetItemQuery.json new file mode 100644 index 0000000000..9e793cb272 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbGetItemQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "dynamodb", + "comp": { + "actionName": "GetItem", + "action": { + "tableName": "", + "params": "{\n \"Key\": {\n \"id\": 1\n }\n}" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/dynamodb/dynamodbListTablesQuery.json b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbListTablesQuery.json new file mode 100644 index 0000000000..262e45d925 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbListTablesQuery.json @@ -0,0 +1,15 @@ +{ + "compType": "dynamodb", + "comp": { + "actionName": "ListTables", + "action": { + "params": "{\n \"Limit\": 10\n}" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/dynamodb/dynamodbPutItemQuery.json b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbPutItemQuery.json new file mode 100644 index 0000000000..361fe10508 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbPutItemQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "dynamodb", + "comp": { + "actionName": "PutItem", + "action": { + "tableName": "", + "params": "{\n \"Item\": {\n \"id\": 1,\n \"name\": \"Alice\"\n }\n}" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/dynamodb/dynamodbQuery.json b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbQuery.json new file mode 100644 index 0000000000..d9a06c3a61 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "dynamodb", + "comp": { + "actionName": "Query", + "action": { + "tableName": "", + "params": "{\n \"KeyConditionExpression\": \"id = :n\",\n \"ExpressionAttributeValues\": {\n \":n\": {\n \"N\": \"1\"\n }\n }\n}" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/s3/s3Datasource.json b/e2e/fixtures/dsl/plugins/s3/s3Datasource.json new file mode 100644 index 0000000000..6ba513a13f --- /dev/null +++ b/e2e/fixtures/dsl/plugins/s3/s3Datasource.json @@ -0,0 +1,12 @@ +{ + "name": "s3", + "type": "s3", + "datasourceConfig": { + "accessKey": "placeholder", + "secretKey": "placeholder", + "endpointUrl": "http://placeholder.invalid", + "region": "us-west-1", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} diff --git a/e2e/fixtures/dsl/plugins/s3/s3DeleteFileQuery.json b/e2e/fixtures/dsl/plugins/s3/s3DeleteFileQuery.json new file mode 100644 index 0000000000..eb5cfcf6b1 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/s3/s3DeleteFileQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "s3", + "comp": { + "actionName": "deleteFile", + "action": { + "bucket": "", + "fileName": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/s3/s3ListObjectsQuery.json b/e2e/fixtures/dsl/plugins/s3/s3ListObjectsQuery.json new file mode 100644 index 0000000000..2a1665e29c --- /dev/null +++ b/e2e/fixtures/dsl/plugins/s3/s3ListObjectsQuery.json @@ -0,0 +1,19 @@ +{ + "compType": "s3", + "comp": { + "actionName": "listObjects", + "action": { + "bucket": "", + "prefix": "", + "delimiter": "", + "limit": "10", + "returnSignedUrl": false + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/s3/s3Query.json b/e2e/fixtures/dsl/plugins/s3/s3Query.json new file mode 100644 index 0000000000..6e04bd9f2d --- /dev/null +++ b/e2e/fixtures/dsl/plugins/s3/s3Query.json @@ -0,0 +1,13 @@ +{ + "compType": "s3", + "comp": { + "actionName": "listBuckets", + "action": {}, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/s3/s3ReadFileQuery.json b/e2e/fixtures/dsl/plugins/s3/s3ReadFileQuery.json new file mode 100644 index 0000000000..86263647ff --- /dev/null +++ b/e2e/fixtures/dsl/plugins/s3/s3ReadFileQuery.json @@ -0,0 +1,17 @@ +{ + "compType": "s3", + "comp": { + "actionName": "readFile", + "action": { + "bucket": "", + "fileName": "", + "encoding": "base64" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/s3/s3UploadDataQuery.json b/e2e/fixtures/dsl/plugins/s3/s3UploadDataQuery.json new file mode 100644 index 0000000000..5d116e14ec --- /dev/null +++ b/e2e/fixtures/dsl/plugins/s3/s3UploadDataQuery.json @@ -0,0 +1,20 @@ +{ + "compType": "s3", + "comp": { + "actionName": "uploadData", + "action": { + "bucket": "", + "fileName": "", + "encoding": "base64", + "data": "", + "contentType": "", + "returnSignedUrl": false + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/scripts/run-in-docker.sh b/e2e/scripts/run-in-docker.sh index 8a56049a21..ee4599b447 100755 --- a/e2e/scripts/run-in-docker.sh +++ b/e2e/scripts/run-in-docker.sh @@ -59,7 +59,8 @@ ## Also starts an HTTP echo sidecar (scripts/echo-server.js, on the already pinned runner image, no extra download) under the ## alias e2e-echo: the target of the requests the SERVER makes inside the app container (npm registry proxy, n8n plugin). ## It records every request in memory and serves them back per path prefix; it dies with the run. The runner gets its -## address as E2E_ECHO_URL. Nothing is sent to the internet by it. The app and runner containers resolve the alias through +## address as E2E_ECHO_URL and its IP address on the run network as E2E_ECHO_IP (for the few tests that must not derive a host +## name, e.g. an S3 virtual-host address `.`). Nothing is sent to the internet by it. The app and runner containers resolve the alias through ## `--add-host e2e-echo:`, not through DNS: should the sidecar die, the name still points at that ## private address and the request fails locally (refused or unreachable) instead of the name resolving on an external resolver. ## @@ -281,6 +282,7 @@ run_tests() { -e LOWCODER_BASE_URL="http://${E2E_APP_HOST}:${APP_PORT}" \ -e E2E_POSTGRES_HOST="$POSTGRES_CONTAINER" \ -e E2E_ECHO_URL="http://${ECHO_ALIAS}:${ECHO_PORT}" \ + -e E2E_ECHO_IP="$ECHO_IP" \ -e E2E_INCLUDE_QUARANTINE="${E2E_INCLUDE_QUARANTINE:-}" \ -e E2E_INCLUDE_INSERT_ALL="${E2E_INCLUDE_INSERT_ALL:-}" \ -e E2E_INCLUDE_SUPERADMIN="${E2E_INCLUDE_SUPERADMIN:-}" \ diff --git a/e2e/src/constants.ts b/e2e/src/constants.ts index 62e55ac7b2..65d70706a1 100644 --- a/e2e/src/constants.ts +++ b/e2e/src/constants.ts @@ -81,6 +81,13 @@ export const NPM_REGISTRIES_SETTING_KEY = "npmRegistries"; */ export const ECHO_ENV = "E2E_ECHO_URL"; +/** + * The variable the run script sets to the echo sidecar's IP address on the run network. A test whose plugin derives a host name + * from the endpoint (an S3 virtual-host address `.`) points the endpoint at this address instead of the + * `e2e-echo` alias, because a derived name is not covered by the alias mapping and may resolve outside the run network. + */ +export const ECHO_IP_ENV = "E2E_ECHO_IP"; + /** The control routes of the echo sidecar; every other path is recorded and answered `{}`. */ export const ECHO_PATHS = { HEALTH: "/__e2e/health", REQUESTS: "/__e2e/requests", MAILS: "/__e2e/mails", ANSWERS: "/__e2e/answers" } as const; diff --git a/e2e/src/datasource/node-plugins.ts b/e2e/src/datasource/node-plugins.ts index 9125f9fbad..7a851dc3bf 100644 --- a/e2e/src/datasource/node-plugins.ts +++ b/e2e/src/datasource/node-plugins.ts @@ -144,3 +144,34 @@ export function parseBasicAuthorization(header: string | string[] | undefined): if (colon < 0) return undefined; return { user: decoded.slice(0, colon), password: decoded.slice(colon + 1) }; } + +/** The pieces of an AWS Signature Version 4 `Authorization` header (the form the AWS SDK sends). */ +export interface SigV4Authorization { + /** The access key id of the credential scope. */ + accessKey: string; + /** The `YYYYMMDD` date of the credential scope. */ + date: string; + region: string; + /** The service of the credential scope (`dynamodb`, `s3`). */ + service: string; + /** The header names that were signed, in the order the header lists them. */ + signedHeaders: string[]; + /** The 64 hex digits of the signature (never compared with a value: it depends on the clock and a random invocation id). */ + signature: string; +} + +const SIGV4_PATTERN = /^AWS4-HMAC-SHA256 Credential=([^/,\s]+)\/(\d{8})\/([^/,\s]+)\/([^/,\s]+)\/aws4_request, SignedHeaders=([a-z0-9;-]+), Signature=([0-9a-f]{64})$/; + +/** + * Parses `AWS4-HMAC-SHA256 Credential=////aws4_request, SignedHeaders=, Signature=<64 hex>`. + * Returns `undefined` for anything else: no header, a repeated header (an array), another scheme, a different order or spacing of + * the three parts, a scope that does not end in `aws4_request`, or a signature that is not 64 lower-case hex digits. A test compares + * the stable parts (key, scope, signed-header list) and never the signature. + */ +export function parseSigV4Authorization(header: string | string[] | undefined): SigV4Authorization | undefined { + if (typeof header !== "string") return undefined; + const match = SIGV4_PATTERN.exec(header); + if (!match) return undefined; + const [, accessKey, date, region, service, signedHeaders, signature] = match as unknown as [string, string, string, string, string, string, string]; + return { accessKey, date, region, service, signedHeaders: signedHeaders.split(";"), signature }; +} diff --git a/e2e/src/dsl/recorded.ts b/e2e/src/dsl/recorded.ts index 1ca3a5c9d9..a35e0e9eaf 100644 --- a/e2e/src/dsl/recorded.ts +++ b/e2e/src/dsl/recorded.ts @@ -264,21 +264,27 @@ export function parsePluginRecording(label: string, text: string, expect: { comp return parsed; } -function loadPluginRecording(pluginId: string, suffix: "Query" | "Datasource", expect: { compType?: string; type?: string }): Record { - const label = `plugins/${pluginId}/${pluginId}${suffix}`; +function loadPluginRecording(pluginId: string, suffix: "Query" | "Datasource", expect: { compType?: string; type?: string }, variant = ""): Record { + const file = `${pluginId}${variant}${suffix}`; + const label = `plugins/${pluginId}/${file}`; if (!PLUGIN_ID_PATTERN.test(pluginId)) throw new RecordedFixtureError(label, "the plugin id is not a folder name (letters and digits only)"); + if (variant !== "" && !PLUGIN_ID_PATTERN.test(variant)) throw new RecordedFixtureError(label, "the variant is not a file name part (letters and digits only)"); let text: string; try { - text = readFileSync(join(RECORDED_PLUGINS_DIR, pluginId, `${pluginId}${suffix}.json`), "utf8"); + text = readFileSync(join(RECORDED_PLUGINS_DIR, pluginId, `${file}.json`), "utf8"); } catch (error) { throw new RecordedFixtureError(label, error instanceof Error ? error.message : String(error)); } return parsePluginRecording(label, text, expect); } -/** The query the editor saved for plugin `pluginId`, as a fresh deep copy; its `compType` is the plugin id. Throws RecordedFixtureError when missing or malformed. */ -export function recordedPluginQuery(pluginId: string): RecordedPluginQuery { - return structuredClone(loadPluginRecording(pluginId, "Query", { compType: pluginId })) as unknown as RecordedPluginQuery; +/** + * The query the editor saved for plugin `pluginId`, as a fresh deep copy; its `compType` is the plugin id. `variant` (letters and digits + * only) picks a further recording of the same plugin, `Query.json` (a plugin whose queries differ by action keeps one + * recording per action). Throws RecordedFixtureError when missing or malformed. + */ +export function recordedPluginQuery(pluginId: string, variant = ""): RecordedPluginQuery { + return structuredClone(loadPluginRecording(pluginId, "Query", { compType: pluginId }, variant)) as unknown as RecordedPluginQuery; } /** The create body the form sent for a data source of plugin `pluginId`, as a fresh deep copy; its `type` is the plugin id. Throws RecordedFixtureError when missing or malformed. */ diff --git a/e2e/src/security/echo.ts b/e2e/src/security/echo.ts index 6055480b31..9a8387e1b9 100644 --- a/e2e/src/security/echo.ts +++ b/e2e/src/security/echo.ts @@ -1,5 +1,5 @@ import { randomBytes } from "node:crypto"; -import { ECHO_ENV, ECHO_TARGET_PREFIX } from "../constants"; +import { ECHO_ENV, ECHO_IP_ENV, ECHO_TARGET_PREFIX } from "../constants"; /** One request the echo sidecar received (scripts/echo-server.js): `path` includes the query string, `body` is UTF-8 text. */ export interface EchoRecord { @@ -38,6 +38,10 @@ export function echoReadPrefix(targetPath: string): string { return `${targetPath}/`; } +/** Four dot-separated decimal octets, each 0 to 255 without a leading zero (the form `docker inspect` reports; a leading zero reads as octal in some parsers). */ +const IPV4_OCTET = "(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)"; +const IPV4_PATTERN = new RegExp(`^${IPV4_OCTET}(\\.${IPV4_OCTET}){3}$`); + /** The base URL of the echo sidecar from the environment, without a trailing slash; throws when the run script did not set it. */ export function echoBaseUrl(env: NodeJS.ProcessEnv): string { const value = env[ECHO_ENV]; @@ -47,6 +51,28 @@ export function echoBaseUrl(env: NodeJS.ProcessEnv): string { return value.replace(/\/+$/, ""); } +/** + * `targetUrl` (an echo target URL, `echo.url`) with its host replaced by the echo sidecar's IP address from the environment; scheme, + * port, path and query are kept. Throws, naming the variable, when the run script did not set it, when it is not a valid IPv4 address + * (four octets of 0 to 255, no leading zeros; a name would defeat the purpose) or when the URL's host is not the IP after the swap. Pure: reads only `env`. + */ +export function echoUrlByIp(targetUrl: string, env: NodeJS.ProcessEnv): string { + const ip = env[ECHO_IP_ENV]; + if (!ip) { + throw new Error(`${ECHO_IP_ENV} is not set. Run the suite through e2e/scripts/run-in-docker.sh (it passes the echo sidecar's IP address).`); + } + if (!IPV4_PATTERN.test(ip)) { + throw new Error(`${ECHO_IP_ENV} is not an IPv4 address: ${JSON.stringify(ip)}`); + } + const url = new URL(targetUrl); + url.hostname = ip; + // a hostname the URL parser refuses is left unchanged by the assignment: prove the swap happened + if (url.hostname !== ip) { + throw new Error(`${ECHO_IP_ENV} could not replace the host of ${targetUrl}: the host is ${url.hostname}, not ${ip}`); + } + return url.toString().replace(/\/+$/, ""); +} + function percentDecoded(text: string): string { try { return decodeURIComponent(text); diff --git a/e2e/tests/datasource/plugin-aws-sdk.spec.ts b/e2e/tests/datasource/plugin-aws-sdk.spec.ts new file mode 100644 index 0000000000..e549e18d3d --- /dev/null +++ b/e2e/tests/datasource/plugin-aws-sdk.spec.ts @@ -0,0 +1,743 @@ +import { createHash, randomBytes } from "node:crypto"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, nodePluginDatasourceBody, testDatasourceRaw, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, TAGS } from "../../src/constants"; +import { appDsl, button, nodePluginQuery, stackItems } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { parseSigV4Authorization } from "../../src/datasource/node-plugins"; +import { boundText, boundTextTestId, openSeededView } from "../../src/components/scenario"; +import { expect, test } from "../../src/fixtures"; +import { DatasourcePage } from "../../src/pages/DatasourcePage"; +import { echoUrlByIp, recordsContain, type EchoRecord, type EchoTarget } from "../../src/security/echo"; + +/** + * D10: the DynamoDB and S3 plugins of node-service (`server/node-service/src/plugins/{dynamodb,s3}/run.ts`), which use the AWS SDK + * for JavaScript v3 with a configurable endpoint. The endpoint is the test's own target on the echo sidecar (`/ddb`, + * `/s3`), so the tests prove the signed request the SDK builds and the path of the canned answer into the app. They are NOT + * a fidelity test of DynamoDB or S3. + * + * Measured on the images `3.0.0-e2e` and `3.0.1-e2e` (the SDK keeps the endpoint's path; the paths below carry a trailing slash for + * the bucket-free calls): + * - DynamoDB: `POST /ddb/`, JSON protocol (`x-amz-target: DynamoDB_20120810.`). + * - S3 without a bucket (list buckets, the connection test): `GET /s3/?x-id=ListBuckets` to the host of the endpoint. + * - S3 with a bucket, endpoint given by IP address: path-style, `/s3//`, `Host` is the IP address. + * + * Every S3 call that takes a bucket goes to the echo's IP address (`E2E_ECHO_IP`), never to the `e2e-echo` alias: the SDK addresses a + * bucket of a host NAME as `.`, a name the alias mapping does not cover and that may resolve outside the run network + * (README, the echo sidecar bullet and the `E2E_ECHO_IP` row). For an IP address it falls back to path-style (the measurement above, asserted by the tests). + * + * The SDK signs with the current time and a random invocation id, so the tests assert the shape of those values (a pattern) and + * every stable part: the credential scope, the service, the region, the list of signed headers, the content hash of the body, the + * content type and the target header. The signature itself is checked for its shape only. + * + * Not covered: a real DynamoDB or S3 service (no vendor host is reachable), the SDK's retry of a 5xx answer. + */ +const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; + +/** + * Candidate defect: `listObjects` refuses an empty bucket itself (`Bucket is required`, before any request), but `readFile`, + * `uploadData` and `deleteFile` do not, so the SDK's own text (`Empty value provided for input HTTP label: Bucket.`) reaches the + * user. No request is sent in either case. + */ +const BUCKET_CHECK_DEFECT = { type: "defect", description: "NSD-8 candidate" } as const; +const BUCKET_CHECK_DETAILS = { annotation: BUCKET_CHECK_DEFECT }; + +const HTTP_OK = 200; +const HTTP_NO_CONTENT = 204; +const HTTP_BAD_REQUEST = 400; +const HTTP_FORBIDDEN = 403; +const HTTP_NOT_FOUND = 404; +const QUERY_CODE_OK = "OK"; +const QUERY_CODE_FAILED = "FAILED"; +/** The `code` of the envelope of a refused connection test (`ResponseView.error(500, message)`). */ +const REFUSED_CODE = 500; +const MARKER_BYTES = 4; +const QUERY_ID = "q1"; +const QUERY_NAME = "q"; +const BUTTON_TEST_ID = "e2e-aws-run"; +const RESULT_NAME = "label"; +const SUCCESS_NAME = "succeeded"; + +const DDB_PATH = "/ddb"; +const S3_PATH = "/s3"; +const DDB_CONTENT_TYPE = "application/x-amz-json-1.0"; +const XML_CONTENT_TYPE = "application/xml"; +const TEXT_CONTENT_TYPE = "text/plain"; +const DDB_TARGET_PREFIX = "DynamoDB_20120810."; +const SERVICE_DDB = "dynamodb"; +const SERVICE_S3 = "s3"; +const DEFAULT_REGION = "us-west-1"; + +/** The bucket, key and table of the tests. */ +const BUCKET = "e2e-bucket"; +const OBJECT_KEY = "e2e.txt"; +const TABLE = "e2e-table"; + +/** The validity of a signed URL the plugin asks for (`getFileSignedUrl`: `expiresIn: 60 * 5`). */ +const SIGNED_URL_EXPIRES_SECONDS = "300"; +const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; +/** The SHA-256 of an empty body, the content hash of every S3 request without a body. */ +const EMPTY_BODY_SHA256 = createHash("sha256").update("").digest("hex"); + +/** What the SDK sends on every request (measured): a retry budget of three attempts, and a kept-alive connection. */ +const SDK_REQUEST_HEADER = "attempt=1; max=3"; +const KEEP_ALIVE = "keep-alive"; +const EXPECT_CONTINUE = "100-continue"; +const DEFAULT_UPLOAD_CONTENT_TYPE = "application/octet-stream"; + +/** The text the connection test of the form shows, measured (`Connection Successful` toast; the refusal text follows `ResponseView.error`). */ +const CONNECTION_OK_TOAST = "Connection Successful"; +const CONNECTION_FAILED_PREFIX = "Failed to connect data source: "; +const ACCESS_DENIED_TEXT = "Access Denied"; + +/** Shapes of the values the SDK generates per request. */ +const SDK_VERSION = "\\d+\\.\\d+\\.\\d+"; +const SDK_AGENT = new RegExp(`^aws-sdk-js/${SDK_VERSION}$`); +const AMZ_DATE = /^\d{8}T\d{6}Z$/; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +const SIGNATURE = /^[0-9a-f]{64}$/; +/** What a normalised header holds instead of a value that differs per request. */ +const SHAPE_OK = ""; +const SHAPE_BAD = ""; + +/** The signed-header lists (measured): they carry no `expect`, which the SDK does not sign. */ +const SIGNED_DDB = ["amz-sdk-invocation-id", "amz-sdk-request", "content-length", "content-type", "host", "x-amz-content-sha256", "x-amz-date", "x-amz-target", "x-amz-user-agent"]; +const SIGNED_S3_GET = ["amz-sdk-invocation-id", "amz-sdk-request", "host", "x-amz-content-sha256", "x-amz-date", "x-amz-user-agent"]; +const SIGNED_S3_PUT = ["amz-sdk-invocation-id", "amz-sdk-request", "content-length", "content-type", "host", "x-amz-content-sha256", "x-amz-date", "x-amz-user-agent"]; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +function sha256Hex(text: string): string { + return createHash("sha256").update(text, "utf8").digest("hex"); +} + +function onlyRecord(records: EchoRecord[]): EchoRecord { + expect(records, "the echo received exactly one request").toHaveLength(1); + return records[0] as EchoRecord; +} + +/** The credentials and the region of a data source: the access key carries the test's marker, the secret is a value that must never reach the echo. */ +interface Credentials { + accessKey: string; + secretKey: string; + region: string; +} + +function credentialsOf(marker: string, region = DEFAULT_REGION): Credentials { + return { accessKey: `E2EKEY${marker}`, secretKey: `e2eSecret${marker}`, region }; +} + +/** What one signed request must look like. `body` is the exact text the echo recorded; `host` is what the `Host` header must hold. */ +interface ExpectedSigned { + method: string; + /** Path and query below the echo, as recorded. */ + path: string; + body: string; + host: string; + credentials: Credentials; + service: string; + signedHeaders: string[]; + /** The stable headers besides the common set (`content-type`, `x-amz-target`, `expect`). */ + extraHeaders: Record; +} + +/** + * Asserts one recorded SDK request completely: method, path and query, body, the COMPLETE header set (no header besides the ones + * listed; each header's value, or for the per-request values their shape) and the parts of the SigV4 `Authorization` header (access + * key, date equal to the one of `x-amz-date`, region, service, the signed-header list, a 64-digit signature). The secret key is + * not asserted here: see `expectSecretNotSent`. + */ +function expectSignedRequest(record: EchoRecord, expected: ExpectedSigned, label: string): void { + expect(record.method, `${label}: the method`).toBe(expected.method); + expect(record.path, `${label}: the path and query`).toBe(expected.path); + expect(record.body, `${label}: the body`).toBe(expected.body); + const { authorization, ...others } = record.headers; + const agentOf = (service: string): RegExp => new RegExp(`^aws-sdk-js/${SDK_VERSION} ua/2\\.1 os/\\S+ lang/js md/nodejs#\\S+ api/${service}#${SDK_VERSION} m/[A-Za-z,]+$`); + const shape = (name: string, pattern: RegExp): string => (typeof others[name] === "string" && pattern.test(others[name] as string) ? SHAPE_OK : SHAPE_BAD); + const parsed = parseSigV4Authorization(authorization); + expect(parsed, `${label}: the Authorization header is a SigV4 header`).toBeDefined(); + expect( + { ...others, "x-amz-user-agent": shape("x-amz-user-agent", SDK_AGENT), "user-agent": shape("user-agent", agentOf(expected.service)), "amz-sdk-invocation-id": shape("amz-sdk-invocation-id", UUID), "x-amz-date": shape("x-amz-date", AMZ_DATE) }, + `${label}: every header besides Authorization`, + ).toEqual({ + ...expected.extraHeaders, + host: expected.host, + "amz-sdk-request": SDK_REQUEST_HEADER, + "x-amz-content-sha256": expected.extraHeaders["x-amz-content-sha256"] ?? sha256Hex(expected.body), + connection: KEEP_ALIVE, + "x-amz-user-agent": SHAPE_OK, + "user-agent": SHAPE_OK, + "amz-sdk-invocation-id": SHAPE_OK, + "x-amz-date": SHAPE_OK, + }); + expect( + { accessKey: parsed?.accessKey, date: parsed?.date, region: parsed?.region, service: parsed?.service, signedHeaders: parsed?.signedHeaders }, + `${label}: the credential scope and the signed headers`, + ).toEqual({ + accessKey: expected.credentials.accessKey, + date: String(others["x-amz-date"]).slice(0, "YYYYMMDD".length), + region: expected.credentials.region, + service: expected.service, + signedHeaders: expected.signedHeaders, + }); + expect(SIGNATURE.test(parsed?.signature ?? ""), `${label}: the signature has the shape of a SigV4 signature`).toBe(true); +} + +/** The access key travels in the credential scope of every request (the positive control), the secret key never leaves node-service. */ +function expectSecretNotSent(records: EchoRecord[], credentials: Credentials, label: string): void { + expect(recordsContain(records, credentials.accessKey), `${label}: positive control, the access key is in the credential scope`).toBe(true); + expect(recordsContain(records, credentials.secretKey), `${label}: the secret key is in no header, path or body`).toBe(false); +} + +/** The body of a JSON-protocol request, parsed (the SDK orders the members its own way). */ +function ddbBodyOf(record: EchoRecord): unknown { + return JSON.parse(record.body); +} + +function ddbHeaders(operation: string, body: string): Record { + return { "content-type": DDB_CONTENT_TYPE, "x-amz-target": `${DDB_TARGET_PREFIX}${operation}`, "content-length": String(Buffer.byteLength(body)) }; +} + +/** Asserts the DynamoDB request of the echo for `operation`; `body` is the member set the plugin sends. */ +function expectDdbRequest(record: EchoRecord, echo: EchoTarget, params: { operation: string; credentials: Credentials; body: unknown }, label: string): void { + expect(ddbBodyOf(record), `${label}: the request body, member for member`).toEqual(params.body); + expectSignedRequest( + record, + { + method: "POST", + path: `${echo.path}${DDB_PATH}/`, + body: record.body, + host: new URL(echo.url).host, + credentials: params.credentials, + service: SERVICE_DDB, + signedHeaders: SIGNED_DDB, + extraHeaders: ddbHeaders(params.operation, record.body), + }, + label, + ); +} + +/** A DynamoDB data source from the recording, its endpoint the echo target's `/ddb`; returns its id. */ +async function ddbDatasource(page: Page, apiUser: RegisteredUser, echo: EchoTarget, credentials: Credentials): Promise { + return createNodePluginDatasource(page.request, { + orgId: apiUser.orgId, + recorded: recordedPluginDatasource(SERVICE_DDB), + config: { ...credentials, endpointUrl: `${echo.url}${DDB_PATH}` }, + }); +} + +/** A saved app with one manual DynamoDB query of the recorded `variant` (not published: the draft runs with `viewMode: false`). */ +async function ddbApp(page: Page, apiUser: RegisteredUser, echo: EchoTarget, credentials: Credentials, variant: string, action: Record): Promise { + const datasourceId = await ddbDatasource(page, apiUser, echo, credentials); + const query = nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery(SERVICE_DDB, variant), action }); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: "e2e-dynamodb", dsl: appDsl([], { queries: [query] }) }); + return appId; +} + +/** + * The endpoint of an S3 data source: the echo target's `/s3` on the echo's IP address (`bucketCalls`: every call that takes a bucket) + * or on the `e2e-echo` alias (calls without a bucket, which derive no host name). + */ +function s3Endpoint(echo: EchoTarget, addressing: "ip" | "alias"): string { + return `${addressing === "ip" ? echoUrlByIp(echo.url, process.env) : echo.url}${S3_PATH}`; +} + +/** The `Host` header the S3 request of `addressing` carries. */ +function s3Host(echo: EchoTarget, addressing: "ip" | "alias"): string { + return new URL(s3Endpoint(echo, addressing)).host; +} + +async function s3Datasource(page: Page, apiUser: RegisteredUser, echo: EchoTarget, credentials: Credentials, addressing: "ip" | "alias"): Promise { + return createNodePluginDatasource(page.request, { + orgId: apiUser.orgId, + recorded: recordedPluginDatasource(SERVICE_S3), + config: { ...credentials, endpointUrl: s3Endpoint(echo, addressing) }, + }); +} + +/** A saved app with one manual S3 query of the recorded `variant`. */ +async function s3App(page: Page, apiUser: RegisteredUser, echo: EchoTarget, credentials: Credentials, addressing: "ip" | "alias", variant: string, action: Record): Promise { + const datasourceId = await s3Datasource(page, apiUser, echo, credentials, addressing); + const query = nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery(SERVICE_S3, variant), action }); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: "e2e-s3", dsl: appDsl([], { queries: [query] }) }); + return appId; +} + +async function runDraft(page: Page, appId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId: QUERY_ID, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +function expectSucceeded(answer: RawAnswer): void { + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); +} + +function expectFailed(answer: RawAnswer, message: string): void { + expectRan(answer); + expect({ success: envelopeOf(answer).success, queryCode: envelopeOf(answer).queryCode, message: envelopeOf(answer).message, data: envelopeOf(answer).data }, "the query failed with the measured message").toEqual({ + success: false, + queryCode: QUERY_CODE_FAILED, + message, + data: null, + }); +} + +const BUCKETS_XML = (names: string[]): string => + `e2e-ownere2e${names.map((name) => `${name}2020-01-01T00:00:00.000Z`).join("")}`; + +const OBJECTS_XML = `${BUCKET}10false${OBJECT_KEY}2020-01-01T00:00:00.000Z"e2e"5STANDARD`; + +const ACCESS_DENIED_XML = `AccessDenied${ACCESS_DENIED_TEXT}e2e-request`; + +/** The `GET /s3/` request of the bucket-free calls (list buckets, the connection test): the query holds only the operation id. */ +function expectListBucketsRequest(record: EchoRecord, echo: EchoTarget, credentials: Credentials, label: string): void { + expectSignedRequest( + record, + { + method: "GET", + path: `${echo.path}${S3_PATH}/?x-id=ListBuckets`, + body: "", + host: s3Host(echo, "alias"), + credentials, + service: SERVICE_S3, + signedHeaders: SIGNED_S3_GET, + extraHeaders: { "x-amz-content-sha256": EMPTY_BODY_SHA256 }, + }, + label, + ); +} + +/** A path-style S3 request with a bucket, to the echo's IP address. */ +function expectBucketRequest( + record: EchoRecord, + echo: EchoTarget, + params: { method: string; pathAndQuery: string; credentials: Credentials; body?: string; uploadContentType?: string }, + label: string, +): void { + const body = params.body ?? ""; + const upload = params.uploadContentType !== undefined; + expectSignedRequest( + record, + { + method: params.method, + path: `${echo.path}${S3_PATH}/${params.pathAndQuery}`, + body, + host: s3Host(echo, "ip"), + credentials: params.credentials, + service: SERVICE_S3, + signedHeaders: upload ? SIGNED_S3_PUT : SIGNED_S3_GET, + extraHeaders: upload + ? { "content-type": params.uploadContentType as string, "content-length": String(Buffer.byteLength(body)), expect: EXPECT_CONTINUE } + : { "x-amz-content-sha256": EMPTY_BODY_SHA256 }, + }, + label, + ); +} + +test.describe("DynamoDB data source against the echo", NODE_SERVICE_DETAILS, () => { + test("D10a: ListTables is a signed JSON call answered from the endpoint", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker(), "eu-central-1"); + await echo.answer(DDB_PATH, { status: HTTP_OK, contentType: DDB_CONTENT_TYPE, body: JSON.stringify({ TableNames: [TABLE] }) }); + const appId = await ddbApp(page, apiUser, echo, credentials, "ListTables", {}); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + // the recorded parameters (`{ "Limit": 10 }`) plus the empty table name the plugin always adds + expectDdbRequest(onlyRecord(records), echo, { operation: "ListTables", credentials, body: { TableName: "", Limit: 10 } }, "ListTables"); + expectSecretNotSent(records, credentials, "ListTables"); + expect(envelopeOf(answer).data, "the answer without its `$metadata`").toEqual({ TableNames: [TABLE] }); + }); + + test("D10b: GetItem wraps the key and unwraps the typed attributes", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + const id = `e2e-${uniqueMarker()}`; + await echo.answer(DDB_PATH, { + status: HTTP_OK, + contentType: DDB_CONTENT_TYPE, + body: JSON.stringify({ Item: { id: { S: id }, n: { N: "3" }, tags: { SS: ["a", "b"] }, ok: { BOOL: true } } }), + }); + const appId = await ddbApp(page, apiUser, echo, credentials, "GetItem", { tableName: TABLE, params: JSON.stringify({ Key: { id } }) }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + expectSecretNotSent(await echo.received(), credentials, "D10b"); + const records = await echo.received(); + expectDdbRequest(onlyRecord(records), echo, { operation: "GetItem", credentials, body: { TableName: TABLE, Key: { id: { S: id } } } }, "GetItem"); + expect(envelopeOf(answer).data, "the item without type wrappers: a string, a number, a string set and a boolean").toEqual({ Item: { id, n: 3, tags: ["a", "b"], ok: true } }); + }); + + test("D10c: PutItem wraps a number, a string and a boolean of the item", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + await echo.answer(DDB_PATH, { status: HTTP_OK, contentType: DDB_CONTENT_TYPE, body: "{}" }); + const appId = await ddbApp(page, apiUser, echo, credentials, "PutItem", { tableName: TABLE, params: JSON.stringify({ Item: { id: 7, name: "Alice", ok: true } }) }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + expectSecretNotSent(await echo.received(), credentials, "D10c"); + expectDdbRequest( + onlyRecord(await echo.received()), + echo, + { operation: "PutItem", credentials, body: { TableName: TABLE, Item: { id: { N: "7" }, name: { S: "Alice" }, ok: { BOOL: true } } } }, + "PutItem", + ); + expect(envelopeOf(answer).data, "an empty answer is an empty object").toEqual({}); + }); + + test("D10d: Query keeps the expression and unwraps every item of the list", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + await echo.answer(DDB_PATH, { + status: HTTP_OK, + contentType: DDB_CONTENT_TYPE, + body: JSON.stringify({ Items: [{ id: { N: "1" } }, { id: { N: "2" } }], Count: 2, ScannedCount: 2 }), + }); + const appId = await ddbApp(page, apiUser, echo, credentials, "", { tableName: TABLE }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + expectSecretNotSent(await echo.received(), credentials, "D10d"); + // the recorded default parameters of the Query action + expectDdbRequest( + onlyRecord(await echo.received()), + echo, + { operation: "Query", credentials, body: { TableName: TABLE, KeyConditionExpression: "id = :n", ExpressionAttributeValues: { ":n": { N: "1" } } } }, + "Query", + ); + expect(envelopeOf(answer).data, "the unwrapped items and the counts").toEqual({ Items: [{ id: 1 }, { id: 2 }], Count: 2, ScannedCount: 2 }); + }); + + test("D10e: a service error answers the query as failed with the service's message", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + await echo.answer(DDB_PATH, { + status: HTTP_BAD_REQUEST, + contentType: DDB_CONTENT_TYPE, + body: JSON.stringify({ __type: "com.amazonaws.dynamodb.v20120810#ResourceNotFoundException", message: "Requested resource not found" }), + }); + const appId = await ddbApp(page, apiUser, echo, credentials, "GetItem", { tableName: TABLE }); + + const answer = await runDraft(page, appId); + + expectFailed(answer, "Requested resource not found"); + // the recorded default key `{ id: 1 }` is wrapped to a number; one request only (a 400 is not retried) + const records = await echo.received(); + expectDdbRequest(onlyRecord(records), echo, { operation: "GetItem", credentials, body: { TableName: TABLE, Key: { id: { N: "1" } } } }, "the failing GetItem"); + expectSecretNotSent(records, credentials, "the failing GetItem"); + }); + + test("D10f: the published view shows an item after a click", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + const id = `e2e-${uniqueMarker()}`; + await echo.answer(DDB_PATH, { status: HTTP_OK, contentType: DDB_CONTENT_TYPE, body: JSON.stringify({ Item: { id: { S: id } } }) }); + const datasourceId = await ddbDatasource(page, apiUser, echo, credentials); + // before the first run `q.data` is not an object + const expression = `{{${QUERY_NAME}.data ? ${QUERY_NAME}.data.Item.id : ""}}`; + const view = await openSeededView( + page, + apiUser.orgId, + "e2e-dynamodb-view", + stackItems([ + button({ id: "b1", name: "button1", text: "Run", testId: BUTTON_TEST_ID, onClickQuery: QUERY_NAME }), + boundText({ id: "t1", name: RESULT_NAME, expression }), + // `success` also reads `true` before the first run (measured on the Turso view), so only the state after the click proves anything + boundText({ id: "t2", name: SUCCESS_NAME, expression: `{{String(${QUERY_NAME}.success)}}` }), + ]), + { queries: [nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery(SERVICE_DDB, "GetItem"), action: { tableName: TABLE } })] }, + ); + + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "before the click the text is empty").toHaveText(""); + expect(await echo.received(), "before the click the echo holds nothing of this test").toEqual([]); + await view.buttonByTestId(BUTTON_TEST_ID).click(); + await expect(view.byTestId(boundTextTestId(SUCCESS_NAME)), "after the click the query succeeded").toHaveText("true"); + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "after the click the text shows the item's id").toHaveText(id); + const records = await echo.received(); + expectDdbRequest(onlyRecord(records), echo, { operation: "GetItem", credentials, body: { TableName: TABLE, Key: { id: { N: "1" } } } }, "the click's GetItem"); + expectSecretNotSent(records, credentials, "the click's GetItem"); + }); +}); + +test.describe("S3 data source against the echo", NODE_SERVICE_DETAILS, () => { + test("D10g: the connection test lists the buckets at the endpoint", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + await echo.answer(S3_PATH, { status: HTTP_OK, contentType: XML_CONTENT_TYPE, body: BUCKETS_XML([BUCKET]) }); + const body = nodePluginDatasourceBody(recordedPluginDatasource(SERVICE_S3), { orgId: apiUser.orgId, config: { ...credentials, endpointUrl: s3Endpoint(echo, "alias") } }); + expect(await echo.received(), "before the test the echo holds nothing of this test").toEqual([]); + + const answer = await testDatasourceRaw(page.request, body); + + expect({ status: answer.status, json: answer.json }, "the envelope: code 1, success, data true").toEqual({ status: HTTP_OK, json: { code: API_OK, message: "", data: true, success: true } }); + const records = await echo.received(); + expectListBucketsRequest(onlyRecord(records), echo, credentials, "the connection test"); + expectSecretNotSent(records, credentials, "the connection test"); + }); + + test("D10h: a refused connection test reports the service's error, and the same call succeeds once the endpoint answers", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + const body = nodePluginDatasourceBody(recordedPluginDatasource(SERVICE_S3), { orgId: apiUser.orgId, config: { ...credentials, endpointUrl: s3Endpoint(echo, "alias") } }); + await echo.answer(S3_PATH, { status: HTTP_FORBIDDEN, contentType: XML_CONTENT_TYPE, body: ACCESS_DENIED_XML }); + + const refused = await testDatasourceRaw(page.request, body); + + // `ResponseView.error(500, message)`: the HTTP status stays 200 (measured), the refusal is in the envelope + expect({ status: refused.status, code: refused.code, json: refused.json }, "the refusal").toEqual({ + status: HTTP_OK, + code: REFUSED_CODE, + json: { code: REFUSED_CODE, message: `${CONNECTION_FAILED_PREFIX}${ACCESS_DENIED_TEXT}.`, success: false }, + }); + const afterRefusal = await echo.received(); + expectListBucketsRequest(onlyRecord(afterRefusal), echo, credentials, "the refused connection test"); + expectSecretNotSent(afterRefusal, credentials, "the refused connection test"); + + await echo.answer(S3_PATH, { status: HTTP_OK, contentType: XML_CONTENT_TYPE, body: BUCKETS_XML([BUCKET]) }); + const accepted = await testDatasourceRaw(page.request, body); + + expect(accepted.json, "control: the same body is accepted when the endpoint answers 200, so the endpoint's answer decided").toEqual({ code: API_OK, message: "", data: true, success: true }); + const records = await echo.received(); + expect(records, "the echo holds exactly the two calls").toHaveLength(2); + for (const [index, record] of records.entries()) expectListBucketsRequest(record, echo, credentials, `connection test ${index + 1}`); + expectSecretNotSent(records, credentials, "both connection tests"); + }); + + test("D10i: the form's Test Connection button reports the endpoint's answer", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + const datasources = new DatasourcePage(page); + await datasources.open(); + await datasources.newButton.click(); + await page.getByText("AWS S3", { exact: true }).first().click(); + // the field ids of the form (measured: `name`, `accessKey`, `secretKey`, `endpointUrl`) + await page.locator("#name").fill("e2e-s3-form"); + await page.locator("#accessKey").fill(credentials.accessKey); + await page.locator("#secretKey").fill(credentials.secretKey); + await page.locator("#endpointUrl").fill(s3Endpoint(echo, "alias")); + const testButton = page.getByRole("button", { name: "Test Connection" }); + await echo.answer(S3_PATH, { status: HTTP_FORBIDDEN, contentType: XML_CONTENT_TYPE, body: ACCESS_DENIED_XML }); + await expect(page.getByText(CONNECTION_OK_TOAST), "before the first click no result is shown").toHaveCount(0); + expect(await echo.received(), "before the first click the echo holds nothing of this test").toEqual([]); + + await testButton.click(); + + await expect(page.getByText(`${CONNECTION_FAILED_PREFIX}${ACCESS_DENIED_TEXT}.`), "the refusal of the service is shown").toBeVisible(); + const afterFirst = await echo.received(); + expectListBucketsRequest(onlyRecord(afterFirst), echo, credentials, "the first click"); + expectSecretNotSent(afterFirst, credentials, "the first click"); + + await echo.answer(S3_PATH, { status: HTTP_OK, contentType: XML_CONTENT_TYPE, body: BUCKETS_XML([BUCKET]) }); + await testButton.click(); + + await expect(page.getByText(CONNECTION_OK_TOAST), "once the endpoint answers 200 the success is shown").toBeVisible(); + const records = await echo.received(); + expect(records, "the echo holds exactly the two clicks' requests").toHaveLength(2); + for (const [index, record] of records.entries()) expectListBucketsRequest(record, echo, credentials, `click ${index + 1}`); + expectSecretNotSent(records, credentials, "the form's connection test"); + }); + + test("D10j: a listBuckets query answers the bucket names", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker(), "eu-west-3"); + await echo.answer(S3_PATH, { status: HTTP_OK, contentType: XML_CONTENT_TYPE, body: BUCKETS_XML([BUCKET, `${BUCKET}-2`]) }); + const appId = await s3App(page, apiUser, echo, credentials, "alias", "", {}); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + expectSecretNotSent(await echo.received(), credentials, "D10j"); + expectListBucketsRequest(onlyRecord(await echo.received()), echo, credentials, "listBuckets"); + expect(envelopeOf(answer).data, "the names, nothing else").toEqual([{ name: BUCKET }, { name: `${BUCKET}-2` }]); + }); + + test("D10k: a listObjects call addresses the bucket in the path of the echo's IP address", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + await echo.answer(S3_PATH, { status: HTTP_OK, contentType: XML_CONTENT_TYPE, body: OBJECTS_XML }); + const appId = await s3App(page, apiUser, echo, credentials, "ip", "ListObjects", { bucket: BUCKET, prefix: "p/", delimiter: "/", limit: 3 }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + // path-style: `//`, never a `.` address, so the request reached the echo and carries the IP as its host + expectBucketRequest(onlyRecord(records), echo, { method: "GET", pathAndQuery: `${BUCKET}/?delimiter=%2F&max-keys=3&prefix=p%2F`, credentials }, "listObjects"); + expect(onlyRecord(records).headers.host, "the host is the IP address of the echo, not a derived name").toBe(new URL(echoUrlByIp(echo.url, process.env)).host); + expectSecretNotSent(records, credentials, "listObjects"); + expect(envelopeOf(answer).data, "name, size, time, an empty signed URL and the file URL below the endpoint").toEqual([ + { name: OBJECT_KEY, size: 5, lastModified: "2020-01-01T00:00:00.000Z", signedUrl: "", url: `${s3Endpoint(echo, "ip")}/${BUCKET}/${OBJECT_KEY}` }, + ]); + }); + + test("D10l: listObjects with returnSignedUrl adds a presigned URL for each file and sends nothing more", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + await echo.answer(S3_PATH, { status: HTTP_OK, contentType: XML_CONTENT_TYPE, body: OBJECTS_XML }); + const appId = await s3App(page, apiUser, echo, credentials, "ip", "ListObjects", { bucket: BUCKET, returnSignedUrl: true }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + expectSecretNotSent(await echo.received(), credentials, "D10l"); + const records = await echo.received(); + expectBucketRequest(onlyRecord(records), echo, { method: "GET", pathAndQuery: `${BUCKET}/?delimiter=&max-keys=10&prefix=`, credentials }, "listObjects"); + const files = envelopeOf(answer).data as Array<{ name: string; signedUrl: string; url: string }>; + expect(files.map((file) => file.name), "the one file").toEqual([OBJECT_KEY]); + const signed = new URL(files[0]?.signedUrl ?? ""); + expect({ origin: signed.origin, path: signed.pathname }, "the presigned URL addresses the file below the IP endpoint").toEqual({ + origin: new URL(echoUrlByIp(echo.url, process.env)).origin, + path: `${echo.path}${S3_PATH}/${BUCKET}/${OBJECT_KEY}`, + }); + const params = Object.fromEntries(signed.searchParams); + expect(Object.keys(params).sort(), "the query parameters of a presigned GET").toEqual( + ["X-Amz-Algorithm", "X-Amz-Content-Sha256", "X-Amz-Credential", "X-Amz-Date", "X-Amz-Expires", "X-Amz-Signature", "X-Amz-SignedHeaders", "x-id"].sort(), + ); + expect( + { + algorithm: params["X-Amz-Algorithm"], + payload: params["X-Amz-Content-Sha256"], + credentialScope: params["X-Amz-Credential"]?.replace(/\/\d{8}\//, "//"), + expires: params["X-Amz-Expires"], + signedHeaders: params["X-Amz-SignedHeaders"], + operation: params["x-id"], + }, + "the stable parts of the presigned URL", + ).toEqual({ + algorithm: "AWS4-HMAC-SHA256", + payload: UNSIGNED_PAYLOAD, + credentialScope: `${credentials.accessKey}//${credentials.region}/${SERVICE_S3}/aws4_request`, + expires: SIGNED_URL_EXPIRES_SECONDS, + signedHeaders: "host", + operation: "GetObject", + }); + expect(AMZ_DATE.test(params["X-Amz-Date"] ?? ""), "the signing time has the shape of an SDK date").toBe(true); + expect(SIGNATURE.test(params["X-Amz-Signature"] ?? ""), "the signature has the shape of a SigV4 signature").toBe(true); + expect(records.length, "presigning is local: the echo holds only the listing").toBe(1); + }); + + test.describe("a file operation addresses the object in the path of the echo's IP address", () => { + const TEXT = "hello e2e"; + const KEY = "dir/e2e file.txt"; + const ENCODED_KEY = "dir/e2e%20file.txt"; + for (const row of [ + { title: "text", encoding: "utf8", expected: TEXT }, + { title: "base64 (the default)", encoding: undefined, expected: Buffer.from(TEXT, "utf8").toString("base64") }, + ]) { + test(`D10m: readFile as ${row.title} answers the content type and the data`, async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + await echo.answer(S3_PATH, { status: HTTP_OK, contentType: TEXT_CONTENT_TYPE, body: TEXT }); + const appId = await s3App(page, apiUser, echo, credentials, "ip", "ReadFile", { bucket: BUCKET, fileName: KEY, ...(row.encoding ? { encoding: row.encoding } : {}) }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + expectSecretNotSent(await echo.received(), credentials, "D10m"); + expectBucketRequest(onlyRecord(await echo.received()), echo, { method: "GET", pathAndQuery: `${BUCKET}/${ENCODED_KEY}?x-id=GetObject`, credentials }, "readFile"); + // measured: the answer holds no `length` and no `lastModified` (why is NOT VERIFIED) + expect(envelopeOf(answer).data, "the content type and the data in the requested encoding").toEqual({ contentType: TEXT_CONTENT_TYPE, data: row.expected }); + }); + } + + for (const row of [ + { title: "text with a content type", action: { encoding: "utf8", data: "hello up", contentType: TEXT_CONTENT_TYPE }, body: "hello up", contentType: TEXT_CONTENT_TYPE }, + { title: "base64 without a content type", action: { data: Buffer.from("hello", "utf8").toString("base64"), contentType: "" }, body: "hello", contentType: DEFAULT_UPLOAD_CONTENT_TYPE }, + ]) { + test(`D10n: uploadData of ${row.title} puts the decoded bytes`, async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + await echo.answer(S3_PATH, { status: HTTP_OK, contentType: XML_CONTENT_TYPE, body: "" }); + const appId = await s3App(page, apiUser, echo, credentials, "ip", "UploadData", { bucket: BUCKET, fileName: "up.bin", ...row.action }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + expectSecretNotSent(await echo.received(), credentials, "D10n"); + expectBucketRequest( + onlyRecord(await echo.received()), + echo, + { method: "PUT", pathAndQuery: `${BUCKET}/up.bin?x-id=PutObject`, credentials, body: row.body, uploadContentType: row.contentType }, + "uploadData", + ); + // measured: an empty content type is sent as `application/octet-stream` (the SDK's default for a binary body) + expect(envelopeOf(answer).data, "the name, no signed URL and the file URL below the endpoint").toEqual({ + fileName: "up.bin", + signedUrl: "", + url: `${s3Endpoint(echo, "ip")}/${BUCKET}/up.bin`, + }); + }); + } + + test("D10o: deleteFile sends a DELETE and answers success", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + await echo.answer(S3_PATH, { status: HTTP_NO_CONTENT, contentType: XML_CONTENT_TYPE, body: "" }); + const appId = await s3App(page, apiUser, echo, credentials, "ip", "DeleteFile", { bucket: BUCKET, fileName: OBJECT_KEY }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + expectSecretNotSent(await echo.received(), credentials, "D10o"); + expectBucketRequest(onlyRecord(await echo.received()), echo, { method: "DELETE", pathAndQuery: `${BUCKET}/${OBJECT_KEY}?x-id=DeleteObject`, credentials }, "deleteFile"); + expect(envelopeOf(answer).data, "the plugin's own answer").toEqual({ success: true }); + }); + }); + + test("D10p: a service error of a bucket call answers the query as failed with the service's message", async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + await echo.answer(S3_PATH, { status: HTTP_FORBIDDEN, contentType: XML_CONTENT_TYPE, body: ACCESS_DENIED_XML }); + const denied = await s3App(page, apiUser, echo, credentials, "ip", "ListObjects", { bucket: BUCKET }); + + expectFailed(await runDraft(page, denied), ACCESS_DENIED_TEXT); + const afterListing = await echo.received(); + expectBucketRequest(onlyRecord(afterListing), echo, { method: "GET", pathAndQuery: `${BUCKET}/?delimiter=&max-keys=10&prefix=`, credentials }, "the denied listObjects"); + + await echo.answer(S3_PATH, { status: HTTP_NOT_FOUND, contentType: XML_CONTENT_TYPE, body: `NoSuchKeyThe specified key does not exist.` }); + const missing = await s3App(page, apiUser, echo, credentials, "ip", "ReadFile", { bucket: BUCKET, fileName: "absent.txt" }); + + expectFailed(await runDraft(page, missing), "The specified key does not exist."); + const records = await echo.received(); + expect(records, "the echo holds exactly the listing and the read").toHaveLength(2); + expectBucketRequest(records[1] as EchoRecord, echo, { method: "GET", pathAndQuery: `${BUCKET}/absent.txt?x-id=GetObject`, credentials }, "the failing readFile"); + expectSecretNotSent(records, credentials, "the denied calls"); + }); + + test("D10q: a bucket call without a bucket sends nothing", BUCKET_CHECK_DETAILS, async ({ page, apiUser, echo }) => { + const credentials = credentialsOf(uniqueMarker()); + await echo.answer(S3_PATH, { status: HTTP_OK, contentType: XML_CONTENT_TYPE, body: OBJECTS_XML }); + const sdkText = "Empty value provided for input HTTP label: Bucket."; + const rows: Array<{ variant: string; action: Record; message: string }> = [ + // the one operation that checks the bucket itself + { variant: "ListObjects", action: { bucket: "" }, message: "Bucket is required" }, + // NSD-8 candidate: the others hand the SDK's own text to the user (measured) + { variant: "ReadFile", action: { bucket: "", fileName: OBJECT_KEY }, message: sdkText }, + { variant: "UploadData", action: { bucket: "", fileName: OBJECT_KEY, encoding: "utf8", data: "x" }, message: sdkText }, + { variant: "DeleteFile", action: { bucket: "", fileName: OBJECT_KEY }, message: sdkText }, + ]; + for (const row of rows) { + const appId = await s3App(page, apiUser, echo, credentials, "ip", row.variant, row.action); + expectFailed(await runDraft(page, appId), row.message); + } + expect(await echo.received(), "no call without a bucket reached the echo").toEqual([]); + + // positive control: the same data source and a bucket does send its request, so an empty echo above is not an echo that cannot be reached + const control = await s3App(page, apiUser, echo, credentials, "ip", "ListObjects", { bucket: BUCKET }); + expectSucceeded(await runDraft(page, control)); + const records = await echo.received(); + expectBucketRequest(onlyRecord(records), echo, { method: "GET", pathAndQuery: `${BUCKET}/?delimiter=&max-keys=10&prefix=`, credentials }, "the control listObjects"); + expectSecretNotSent(records, credentials, "the control listObjects"); + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index b9c68c60f1..6854a3ed5d 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -24,6 +24,7 @@ import { OPEN_API_FIXTURE_SCHEME, OPEN_API_FIXTURE_SPEC, parseBasicAuthorization, + parseSigV4Authorization, } from "../../src/datasource/node-plugins"; /** @@ -293,6 +294,57 @@ test.describe("node-service data source helpers", { tag: [TAGS.NODE_SERVICE] }, } }); + test("the dynamodb and s3 recordings are the form's body and the editor's saved queries (one per action), with no value of the recording session", () => { + const expectations = [ + { id: "dynamodb", variants: { "": "Query", ListTables: "ListTables", GetItem: "GetItem", PutItem: "PutItem" } }, + { id: "s3", variants: { "": "listBuckets", ListObjects: "listObjects", ReadFile: "readFile", UploadData: "uploadData", DeleteFile: "deleteFile" } }, + ]; + for (const { id, variants } of expectations) { + const datasource = recordedPluginDatasource(id); + expect(datasource.type, `${id}: the data source type`).toBe(id); + expect(Object.keys(datasource), `${id}: no workspace id`).toEqual(["name", "type", "datasourceConfig"]); + expect(datasource.datasourceConfig, `${id}: the form's fields, with placeholders and the form's default region`).toEqual({ + accessKey: "placeholder", + secretKey: "placeholder", + endpointUrl: NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL, + region: "us-west-1", + authConfigType: "NO_AUTH", + sslCertVerificationType: "VERIFY_CA_CERT", + }); + const files = [`${id}Datasource.json`]; + for (const [variant, actionName] of Object.entries(variants)) { + const query = recordedPluginQuery(id, variant); + expect(query.compType, `${id}${variant}: the query type`).toBe(id); + expect(query.comp.actionName, `${id}${variant}: the recorded action`).toBe(actionName); + expect(Object.keys(query), `${id}${variant}: only what the builder keeps`).toEqual(["compType", "comp"]); + expect(query.comp.headers, `${id}${variant}: the editor's empty header row`).toEqual([{ key: "", value: "" }]); + files.push(`${id}${variant}Query.json`); + } + const text = files.map((file) => readFileSync(join(RECORDED_PLUGINS_DIR, id, file), "utf8")).join("\n"); + expect(text, `${id}: a 24-hex id`).not.toMatch(/\b[0-9a-f]{24}\b/); + expect(text, `${id}: an echo address`).not.toContain("e2e-echo"); + expect(text, `${id}: an epoch of 10 digits or more`).not.toMatch(/\b\d{10,}\b/); + } + expect(recordedPluginQuery("dynamodb", "GetItem").comp.action, "dynamodb GetItem: the table and the parameters JSON text, as the editor saved them").toEqual({ + tableName: "", + params: JSON.stringify({ Key: { id: 1 } }, null, 4), + }); + expect(recordedPluginQuery("s3", "ListObjects").comp.action, "s3 listObjects: the editor's defaults (the limit is saved as text)").toEqual({ + bucket: "", + prefix: "", + delimiter: "", + limit: "10", + returnSignedUrl: false, + }); + }); + + test("recordedPluginQuery with a variant reads Query.json, refuses a variant that is not a file name part and names the missing file", () => { + expect(recordedPluginQuery("s3", "DeleteFile").comp.actionName).toBe("deleteFile"); + expect(recordedPluginQuery("s3", ""), "an empty variant is the plain recording").toEqual(recordedPluginQuery("s3")); + expect(() => recordedPluginQuery("s3", "../turso/turso")).toThrow(RecordedFixtureError); + expect(() => recordedPluginQuery("s3", "NoSuchAction")).toThrow("s3NoSuchActionQuery"); + }); + test("parseBasicAuthorization decodes user and password, and reads anything else as not Basic credentials", () => { const header = (text: string): string => `Basic ${Buffer.from(text, "utf8").toString("base64")}`; expect(parseBasicAuthorization(header("user:secret"))).toEqual({ user: "user", password: "secret" }); @@ -307,6 +359,21 @@ test.describe("node-service data source helpers", { tag: [TAGS.NODE_SERVICE] }, expect(parseBasicAuthorization("Basic ***"), "not base64").toBeUndefined(); }); + test("parseSigV4Authorization reads key, scope, signed headers and signature, and reads anything else as not a SigV4 header", () => { + const signature = "a".repeat(64); + const header = `AWS4-HMAC-SHA256 Credential=E2EKEY1/20261124/us-west-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=${signature}`; + expect(parseSigV4Authorization(header)).toEqual({ accessKey: "E2EKEY1", date: "20261124", region: "us-west-1", service: "s3", signedHeaders: ["host", "x-amz-date"], signature }); + expect(parseSigV4Authorization(undefined), "no header").toBeUndefined(); + expect(parseSigV4Authorization([header]), "a repeated header").toBeUndefined(); + expect(parseSigV4Authorization(header.replace("AWS4-HMAC-SHA256", "AWS4-HMAC-SHA512")), "another algorithm").toBeUndefined(); + expect(parseSigV4Authorization(header.replace("aws4_request", "aws5_request")), "another terminator").toBeUndefined(); + expect(parseSigV4Authorization(header.replace("/s3/", "/")), "a scope without a service").toBeUndefined(); + expect(parseSigV4Authorization(header.replace(signature, "a".repeat(63))), "a short signature").toBeUndefined(); + expect(parseSigV4Authorization(header.replace(signature, "A".repeat(64))), "an upper-case signature").toBeUndefined(); + expect(parseSigV4Authorization(`${header} `), "trailing text").toBeUndefined(); + expect(parseSigV4Authorization("Basic dXNlcjpwdw=="), "another scheme").toBeUndefined(); + }); + test("the recorded placeholder host is under the reserved .invalid TLD", () => { expect(new URL(NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL).hostname.endsWith(".invalid")).toBe(true); }); diff --git a/e2e/tests/foundation/security-echo.spec.ts b/e2e/tests/foundation/security-echo.spec.ts index 35a9866f84..39456d3f6d 100644 --- a/e2e/tests/foundation/security-echo.spec.ts +++ b/e2e/tests/foundation/security-echo.spec.ts @@ -1,10 +1,11 @@ import { spawn, type ChildProcess } from "node:child_process"; import { createServer } from "node:net"; +import { readFileSync } from "node:fs"; import { join } from "node:path"; import { expect, test } from "@playwright/test"; -import { ECHO_ENV, ECHO_PATHS, ECHO_TARGET_PREFIX, npmRegistryPath } from "../../src/constants"; +import { ECHO_ENV, ECHO_IP_ENV, ECHO_PATHS, ECHO_TARGET_PREFIX, npmRegistryPath } from "../../src/constants"; import { n8nDatasourceBody } from "../../src/api/client"; -import { echoBaseUrl, echoReadPrefix, echoTargetPath, recordsContain, type EchoRecord } from "../../src/security/echo"; +import { echoBaseUrl, echoReadPrefix, echoUrlByIp, echoTargetPath, recordsContain, type EchoRecord } from "../../src/security/echo"; /** * Stack-free unit tests of the echo sidecar (scripts/echo-server.js, started here as a child process on a loopback port, no @@ -152,6 +153,33 @@ test.describe("echo helpers", () => { expect(() => echoBaseUrl({ [ECHO_ENV]: "" })).toThrow(ECHO_ENV); }); + test("echoUrlByIp swaps the host for the IP, keeps scheme, port, path and query, and throws, naming the variable, when it is missing or not an IPv4 address", () => { + const env = { [ECHO_IP_ENV]: "172.30.0.5" }; + expect(echoUrlByIp("http://e2e-echo:8080/t/1-0-0-ab", env)).toBe("http://172.30.0.5:8080/t/1-0-0-ab"); + expect(echoUrlByIp("http://e2e-echo:8080/t/x/s3?a=1", env)).toBe("http://172.30.0.5:8080/t/x/s3?a=1"); + expect(echoUrlByIp("http://e2e-echo:8080", env), "no trailing slash is added").toBe("http://172.30.0.5:8080"); + expect(echoUrlByIp("https://e2e-echo/t/x", env), "a default port stays implicit").toBe("https://172.30.0.5/t/x"); + expect(() => echoUrlByIp("http://e2e-echo:8080/t/x", {})).toThrow(ECHO_IP_ENV); + expect(() => echoUrlByIp("http://e2e-echo:8080/t/x", { [ECHO_IP_ENV]: "" })).toThrow(ECHO_IP_ENV); + expect(() => echoUrlByIp("http://e2e-echo:8080/t/x", { [ECHO_IP_ENV]: "e2e-echo" })).toThrow(`${ECHO_IP_ENV} is not an IPv4 address`); + expect(() => echoUrlByIp("not a url", env)).toThrow(); + for (const invalid of ["999.999.999.999", "256.1.1.1", "1.2.3.256", "01.2.3.4", "1.2.3.04", "1.2.3", "1.2.3.4.5", "1.2.3.", "e2e-echo", " 1.2.3.4", "1.2.3.4 "]) { + expect(() => echoUrlByIp("http://e2e-echo:8080/t/x", { [ECHO_IP_ENV]: invalid }), `${JSON.stringify(invalid)} is refused`).toThrow(`${ECHO_IP_ENV} is not an IPv4 address`); + } + // a URL that has no host to replace (an opaque path) leaves the assignment without effect: that is detected, not returned as if it were swapped + expect(() => echoUrlByIp("mailto:someone@example.test", env)).toThrow(`${ECHO_IP_ENV} could not replace the host`); + for (const valid of ["0.0.0.0", "10.0.0.1", "192.168.64.3", "255.255.255.255"]) { + expect(echoUrlByIp("http://e2e-echo:8080/t/x", { [ECHO_IP_ENV]: valid }), `${valid} is accepted`).toBe(`http://${valid}:8080/t/x`); + } + }); + + test("the run script passes the echo IP to the runner next to the echo URL, from the address start_echo measured", () => { + const script = readFileSync(join(__dirname, "..", "..", "scripts", "run-in-docker.sh"), "utf8"); + expect(script).toContain(`-e ${ECHO_IP_ENV}="$ECHO_IP"`); + expect(script).toContain(`-e ${ECHO_ENV}="http://\${ECHO_ALIAS}:\${ECHO_PORT}"`); + expect(script, "ECHO_IP is set from docker inspect in start_echo").toContain('ECHO_IP="$(docker inspect'); + }); + test("recordsContain finds a needle in the path, a header (also a repeated one) or the body, and returns a boolean", () => { const record = (patch: Partial): EchoRecord => ({ method: "GET", path: "/t/x/p", headers: {}, body: "", ...patch }); expect(recordsContain([record({})], "needle")).toBe(false); From d90c6600132e73a59f21713b7af4b0c2044e0b37 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 19:36:14 +0100 Subject: [PATCH 13/20] test: add Supabase Storage node-service data source scenarios Adds recorded Supabase Storage data source and query fixtures, one per action, and scenarios that point the plugin's project URL at the run's echo target: every request the storage client sends is asserted in full (method, path, query, body, header set), the API key is asserted to appear only in its two headers and in no answer, and the answers each operation returns, signed URLs and the published view after a click are covered. Four behaviours are characterised and annotated as defect candidates: a storage error message is replaced by a placeholder object, the signed URL expiry is sent as an epoch time in milliseconds computed once per process, the listObjects search field is never sent, and only listObjects checks for an empty bucket. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 2 +- e2e/README.md | 20 +- .../supabaseCreateSignedUrlQuery.json | 16 + .../plugins/supabase/supabaseDatasource.json | 10 + .../supabase/supabaseDeleteFileQuery.json | 16 + .../supabase/supabaseListObjectsQuery.json | 21 + .../dsl/plugins/supabase/supabaseQuery.json | 13 + .../supabase/supabaseReadFileQuery.json | 18 + .../supabase/supabaseUploadDataQuery.json | 20 + .../plugin-supabase-storage.spec.ts | 688 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 40 + 11 files changed, 856 insertions(+), 8 deletions(-) create mode 100644 e2e/fixtures/dsl/plugins/supabase/supabaseCreateSignedUrlQuery.json create mode 100644 e2e/fixtures/dsl/plugins/supabase/supabaseDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/supabase/supabaseDeleteFileQuery.json create mode 100644 e2e/fixtures/dsl/plugins/supabase/supabaseListObjectsQuery.json create mode 100644 e2e/fixtures/dsl/plugins/supabase/supabaseQuery.json create mode 100644 e2e/fixtures/dsl/plugins/supabase/supabaseReadFileQuery.json create mode 100644 e2e/fixtures/dsl/plugins/supabase/supabaseUploadDataQuery.json create mode 100644 e2e/tests/datasource/plugin-supabase-storage.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index 4792894d68..a6729c84a5 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,7 +129,7 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `tests/datasource/plugin-supabase-storage.spec.ts`, D11; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). diff --git a/e2e/README.md b/e2e/README.md index 1a7f6601b2..bbb4f44e43 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -210,7 +210,7 @@ e2e/ fixtures/sql/init.sql PostgreSQL data: items, products, notes fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb`, `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate), `dynamodb` and `s3` (the form's body, and one query recording per action because the saved query differs by action: `Query.json` is the editor's default action, the others are `Query.json`, loaded by `recordedPluginQuery(id, "")`: `dynamodb` Query, ListTables, GetItem, PutItem; `s3` listBuckets, ListObjects, ReadFile, UploadData, DeleteFile) + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb`, `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate), `supabase` (the form's body, and one query recording per action: `supabaseQuery.json` is listBuckets, the others are `supabaseQuery.json`: ListObjects, ReadFile, UploadData, DeleteFile, CreateSignedUrl), `dynamodb` and `s3` (the form's body, and one query recording per action because the saved query differs by action: `Query.json` is the editor's default action, the others are `Query.json`, loaded by `recordedPluginQuery(id, "")`: `dynamodb` Query, ListTables, GetItem, PutItem; `s3` listBuckets, ListObjects, ReadFile, UploadData, DeleteFile) src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -255,15 +255,16 @@ Test titles carry these ids. - D8 the Open API wrapper plugins of node-service with a server URL (CouchDB, Jira, Datadog, WooCommerce, Supabase Management API) against the echo sidecar: one read-only operation each reaches the server URL (the target's path survives as the base path) with its credentials and answers the canned data, CouchDB JWT credential alone and with a Basic one (observation), WooCommerce server URL forms and refusal of v1/v2, a trailing slash after the API path doubles it (NSD-5 candidate), concurrent queries against two server URLs each reach their own server (`@node-service`). - D9 the Open API wrapper plugins of node-service with a server URL (Lowcoder API, OpenAI, APITemplate.io, Carbone, UiPath) against the echo sidecar: one read-only operation each reaches the server URL with its credentials and answers the canned data (Carbone `get_status` sends no token: observation), every Lowcoder spec version, an OpenAI chat completion posts its JSON body, OpenAI on spec version v1.0 sends no key (NSD-7 candidate), an error status answered as success (NSD-4 candidate), UiPath fails every query and its query configuration request (HTTP 500) and sends nothing (NSD-6 candidate; its desired behaviour is quarantined), concurrent queries against two server URLs each reach their own server (`@node-service`). - D10 the DynamoDB and S3 plugins of node-service (AWS SDK v3) against the echo sidecar: a DynamoDB call is a signed JSON POST to `/ddb/` (`x-amz-target`, credential scope with the access key and region, the secret never sent), GetItem, PutItem and Query wrap the request's values and unwrap the answer's typed attributes, a service error fails the query with its message, the published view after a click; the S3 connection test lists the buckets (API and the form's Test Connection button), a refused test answers `code` 500 with the service's text (HTTP 200), a listBuckets query answers the names, every call that takes a bucket (listObjects with and without a presigned URL, readFile, uploadData, deleteFile) is path-style `/s3//` on the echo's IP address, a service error fails the query, a bucket call without a bucket sends nothing (readFile, uploadData and deleteFile show the SDK's text, NSD-8 candidate) (`@node-service`; the signed request's shape and the answer's path into the app, not the vendor service). +- D11 the Supabase Storage plugin of node-service (`supabase-js`, project URL `/sb`) against the echo sidecar: every operation (listBuckets, listObjects, readFile, uploadData, deleteFile, createSignedUrl) sends its Storage API request below `/sb/storage/v1` with the key in `apikey` and `authorization` and nowhere else, a trailing slash of the project URL changes nothing, a storage error fails the query with `{"size":0,"timeout":0}` and not the API's message (NSD-9 candidate), the signed-URL validity is an epoch time in milliseconds (NSD-10 candidate), the `search` field of listObjects is not sent (NSD-11 candidate), only listObjects refuses an empty bucket (NSD-12 candidate), the published view after a click (`@node-service`; the request shape and the answer's path into the app, not Supabase). - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue -Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the current suite, `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (794 tests): 44 failed, 750 passed. The baseline from a clean worktree of the previous commit (770 tests, same command and image): 43 failed, 727 passed. The failing sets are the same except `SEC-R09d`, which is intermittent on both (5 repeats: 3 failed with the current tree, 2 failed on the baseline). The 44 failures are 25 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`, and `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag and by the baseline, not analysed one by one). No node-service scenario failed.): -default **794 tests in 113 files**; with `E2E_INCLUDE_QUARANTINE=1` **808 in 114**; with `E2E_INCLUDE_SUPERADMIN=1` **799 in 113**; with both of those **813 in 114**; -with `E2E_INCLUDE_INSERT_ALL=1` **906 in 114**; with all three opt-in variables **925 in 115** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: +Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 794-test suite taken before the Supabase Storage scenarios (D11) existed, `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (794 tests; it says nothing about D11, whose evidence is the `--repeat-each=10 --workers=4` gate of `tests/datasource/plugin-supabase-storage.spec.ts` on `3.0.0-e2e` and on `3.0.1-e2e`, 210 passed on each): 44 failed, 750 passed. The baseline from a clean worktree of the previous commit (770 tests, same command and image): 43 failed, 727 passed. The failing sets are the same except `SEC-R09d`, which is intermittent on both (5 repeats: 3 failed with the current tree, 2 failed on the baseline). The 44 failures are 25 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`, and `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag and by the baseline, not analysed one by one). No node-service scenario of that run failed.): +default **816 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **830 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **821 in 114**; with both of those **835 in 115**; +with `E2E_INCLUDE_INSERT_ALL=1` **928 in 115**; with all three opt-in variables **947 in 116** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 94 in 9 files (the 24 unit tests of `foundation/node-plugins.spec.ts` plus the 70 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each); a selection tag, they stay in the default run). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 116 in 10 files (the 25 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -327,6 +328,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/plugin-openapi-wrappers-data.spec.ts | D8: CouchDB, Jira, Datadog, WooCommerce and the Supabase Management API against the echo sidecar (server URL ``, one read-only operation of each bundled document). D8a couchdb `GET /_all_dbs` with `Authorization: Basic` of the configured user and password, D8b jira `GET /rest/api/3/myself` with Basic, D8c datadog `GET /api/v1/validate` with `dd-api-key` and `dd-application-key`, D8d woocommerce `GET /wp-json/wc/v3/products?context=view&order=asc&orderby=date&status=any&type=simple&stock_status=instock` with Basic, D8e supabaseApi `GET /v1/projects` with `Authorization: Bearer `; each asserts echo empty before, exactly one request (method, full path and query, no body, the complete header set) and the canned body as the query's data; D8f couchdb: a JWT credential alone is sent as `Authorization`, with a Basic credential too only the Basic one is (observation), each request asserted completely; D8g woocommerce: a plain, a slash-terminated and an already `/wp-json/wc/v3` server URL each give the API path once, `/wc/v1` and `/wc/v2` are refused with `only woocommerce api v3 is supported` and send nothing; D8h woocommerce: a server URL ending in `/wp-json/wc/v3/` gets the API path twice (NSD-5 candidate); D8i couchdb, woocommerce and datadog: 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 11 | | datasource/plugin-openapi-wrappers-apps.spec.ts | D9: the Lowcoder API, OpenAI, APITemplate.io, Carbone and UiPath against the echo sidecar (server URL ``, one read-only operation of each bundled document). D9a lowcoder `GET /api/users/currentUser` with `Authorization: Bearer `, D9b OpenAI (spec version v2.3) `GET /models` with `Authorization: Bearer `, D9c apiTemplate `GET /v2/list-templates` with `x-api-key`, D9d carboneIo `GET /status` with NO credential header (observation: that operation lists no security scheme), D9e carboneIo `GET /template/` with `Authorization: Bearer ` and `carbone-version: 4`; each asserts echo empty before, exactly one request (method, full path and query, body, the complete header set) and the canned body as the query's data; D9f lowcoder: spec versions v1.0 to v1.3 send the same request; D9g OpenAI: a chat completion `POST /chat/completions` carries the JSON body, `content-type`, `content-length` and the key, and answers the canned completion; D9h OpenAI: spec version v1.0, chosen or by default, sends no `Authorization` header while v2.3 with the same key does (NSD-7 candidate); D9i apiTemplate: a canned 404 body is reported as a successful result (NSD-4 candidate); D9j uiPath: a query fails with the message `Maximum call stack size exceeded` and sends no request, after a control that another wrapper's query reaches the same echo target (NSD-6 candidate); D9k uiPath: the form's query configuration request for the UiPath document answers 500 / code 5000 `get dynamic config error`, while the identical request for apiTemplate answers success and lists its operations (NSD-6 candidate; the test asserts the failure and the control, not its cause); D9l uiPath (`@quarantine`, not counted in the default run): the folders query should reach `GET /odata/Folders` with `Bearer ` exactly and answer the canned data, fails today; D9m lowcoder, apiTemplate, carboneIo and OpenAI: 8, 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 15 (+1 `@quarantine`) | | datasource/plugin-aws-sdk.spec.ts | D10: DynamoDB and S3 against the echo sidecar (endpoints `/ddb` and `/s3`; bucket calls on the echo's IP address). Measured on 3.0.0-e2e and 3.0.1-e2e (the SDK version printed in its user agent is 3.668.0 on 3.0.0-e2e; the tests match the shape, not the version): the SDK keeps the endpoint's path, DynamoDB posts to `/ddb/`, S3 without a bucket gets `/s3/?x-id=ListBuckets`, and with a bucket on an IP-address endpoint it is path-style (`/s3//`, `Host` the IP address). Every request a D10 test makes is asserted completely: method, path and query, body, the whole header set (per-request values by shape: date, invocation id, user agents, signature), the credential scope (access key, date, region, service) and the signed-header list, and every D10 test that sends a request also asserts that the secret key is in no header, path or body of the echo's records (with a control that the access key is: it travels in the credential scope). The rows of D10q that send nothing assert that the echo holds no record, after which a control call with a bucket is asserted completely. The presigned URL of D10l is asserted by its stable query parameters and by shape, not by value. D10a DynamoDB ListTables (region `eu-central-1` in the scope, body `{TableName: "", Limit: 10}`, answer without `$metadata`), D10b GetItem wraps the key and unwraps a string, a number, a string set and a boolean, D10c PutItem wraps a number, a string and a boolean, D10d Query keeps the expression and unwraps the items, D10e a 400 `ResourceNotFoundException` fails the query (`Requested resource not found`, one request), D10f the published view after a click, D10g the connection test (`code` 1, `success`, `data` true; one `GET /s3/?x-id=ListBuckets`), D10h a 403 test answers HTTP 200 with `code` 500, `success` false and `Failed to connect data source: Access Denied.`, and the same body succeeds once the endpoint answers 200, D10i the form's Test Connection button shows that text, then `Connection Successful`, D10j listBuckets answers `[{name}]`, D10k listObjects is path-style on the IP with `delimiter`, `max-keys` and `prefix` and answers name, size, time, file URL, D10l `returnSignedUrl` adds a presigned URL (`X-Amz-Expires=300`, signed header `host`, no extra request), D10m readFile as text and base64, D10n uploadData of text and of base64 without a content type (`application/octet-stream`), D10o deleteFile, D10p a 403 and a 404 fail the query with the service's text, D10q a bucket call without a bucket sends nothing: listObjects says `Bucket is required`, readFile, uploadData and deleteFile say `Empty value provided for input HTTP label: Bucket.` (NSD-8 candidate), after a control that a call with a bucket reaches the echo. Not covered: a real DynamoDB or S3 service, the SDK's retry of a 5xx answer | @node-service | 19 | +| datasource/plugin-supabase-storage.spec.ts | D11: the Supabase Storage plugin against the echo sidecar (project URL `/sb`; the Storage API is `/sb/storage/v1/...`). Measured on 3.0.0-e2e and 3.0.1-e2e (same requests and answers; supabase-js 2.45.4 in `x-client-info`, matched by shape): the client keeps the project URL's path with or without a trailing slash and derives no host name; every request carries `apikey: `, `authorization: Bearer `, the `node-fetch` user agent, `accept-encoding: gzip,deflate` and `connection: close`. Every request a D11 test makes is asserted completely (method, path and query, body, the whole header set), and every test that sends one also asserts that the key is in no header besides those two, no path or body, and no answer of the query (the whole query answer; in D11q the view's whole `q.data` as text); control: it is in those two. D11a listBuckets `GET /bucket` and the buckets as the API answered, D11b the project URL with and without a trailing slash reach the same path, D11c listObjects `POST /object/list/` with `{limit: 10, offset: 0, sortBy: {column: name, order: asc}, prefix}` and the public URL of each file in the answer, D11d limit, offset and sort order of the query, D11e the `search` field is not sent (NSD-11 candidate), D11f `returnSignedUrl` adds `POST /object/sign/` with `{expiresIn, paths}` and the signed URL in the answer, D11g readFile as text and base64 (`GET /object//`, answer `{data, type}`), D11h readFile with a transform goes to `/render/image/authenticated//?width=10`, D11i uploadData of text `POST /object//` with the text, its content type, `cache-control: max-age=3600` and `x-upsert: false`, D11j base64 without a content type sends an empty `content-type` header (observation), D11k uploadData with `returnSignedUrl` uploads then signs, D11l deleteFile `DELETE /object/` with `{prefixes: [name]}`, D11m createSignedUrl sends `expiresIn` as an integer above 1e12, an epoch time in milliseconds computed once (the second query, asserted completely too, sends the same number; the bounds allow one hour of clock skew and a plugin load up to six hours old; NSD-10 candidate, also asserted in D11f and D11k), D11n a 400, a 404 and a 401 answer fail the query with `{"size":0,"timeout":0}` instead of the answer's message, each followed by a control that the same query succeeds once the API answers 200 (NSD-9 candidate), D11o the signing and the listing fail the same way, each followed by a control that both succeed once the API answers 200 on their paths, D11p an empty bucket: listObjects says `Bucket is required` and sends nothing, readFile, uploadData, deleteFile and createSignedUrl send requests with an empty bucket segment (NSD-12 candidate), D11q the published view shows the bucket name only after the click (echo empty before, one request after). Not covered: a real Supabase project; the connection test (none is wired up for this plugin) | @node-service | 21 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -477,7 +479,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb and s3 recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization` | @node-service | 24 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization` | @node-service | 25 | | foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources) | none | 27 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | @@ -525,6 +527,10 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-6 candidate | the UiPath plugin cannot run: `getSchemaExample` (`plugins/openApi/util.ts`) recurses without end on a circular schema of the bundled document, so the query configuration (`POST /api/datasources/getPluginDynamicConfig`, path `$.queryConfig`) answers 500 / code 5000 `get dynamic config error` (the editor lists no operation and cannot save a UiPath query) and every query fails with `Maximum call stack size exceeded` before any request is sent; the cause (`RangeError: Maximum call stack size exceeded` at `getSchemaExample`, from a circular schema) was read in the app container's node-service log while recording, not asserted: the suite asserts only the HTTP 500 / code 5000 of the configuration request, the query's failure message and that no request is sent; measured on 3.0.0-e2e and 3.0.1-e2e. Whether UiPath sends its `Authorization` header (a doubled `Bearer`, or none) cannot be measured today. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9j and D9k assert today's behaviour after a control that another plugin reaches the echo / lists its operations (characterisation, default run), annotation `{type:"defect", description:"NSD-6 candidate"}`; D9l asserts the desired behaviour (`GET /odata/Folders` with `Authorization: Bearer ` exactly), `@quarantine`, same annotation; they change when the plugin runs | | NSD-7 candidate | an OpenAI data source on spec version `v1.0` (the version an empty choice selects) sends no `Authorization` header: the plugin hands the key over as `ApiKeyAuth.value`, the security scheme of the `v2.3` document, while the `v1.0` document names its scheme `ApiKey`; with `v2.3` the same key is sent as `Authorization: Bearer `; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9h asserts today's behaviour after a control that v2.3 sends the key to the same echo (characterisation, default run), annotation `{type:"defect", description:"NSD-7 candidate"}`; it changes when the key reaches the `v1.0` document's scheme | | NSD-8 candidate | the S3 plugin checks the bucket itself only for `listObjects` (`Bucket is required`); `readFile`, `uploadData` and `deleteFile` with an empty bucket reach the AWS SDK, which refuses before any request with its own text `Empty value provided for input HTTP label: Bucket.`, so the user sees an SDK message and the checks are inconsistent; no request is sent in any of the four cases; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-aws-sdk.spec.ts` D10q asserts today's messages after a control that a call with a bucket reaches the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-8 candidate"}`; it changes when the three operations check the bucket like `listObjects` | +| NSD-9 candidate | a storage error answer of the Supabase Storage plugin (any status: 400, 401 and 404 measured) fails the query with `{"size":0,"timeout":0}`, the JSON of node-fetch's `Response`, not with the API's message (`e2e-storage-error` in the canned answer): storage-js recognises an HTTP error only as an instance of the global `Response`, and node-service's proxy fetch answers with node-fetch's class; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11n and D11o assert today's message after a control that the same query succeeds when the API answers 200 (characterisation, default run), annotation `{type:"defect", description:"NSD-9 candidate"}`; they change when the message of the answer reaches the user | +| NSD-10 candidate | the Supabase Storage plugin sends the signed-URL validity as `expiresIn: Date.now() + 5 minutes` in milliseconds (13 digits, about 1.8e12 when measured), computed once when node-service loads the plugin, where the API takes seconds: every signing request of one node-service process carries the same number; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11f, D11k and D11m assert the magnitude (above 1e12, and within clock-skew and plugin-age allowances of now plus five minutes) and, in D11m, that two queries send the same value (characterisation, default run), annotation `{type:"defect", description:"NSD-10 candidate"}`; they change when the validity is 300 | +| NSD-11 candidate | the `search` field of the Supabase Storage listObjects query is never sent: the request body is `{limit, offset, sortBy, prefix}` whatever the field holds; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11e asserts today's body after a positive control that the query's prefix travels (characterisation, default run), annotation `{type:"defect", description:"NSD-11 candidate"}`; it changes when the search text is sent | +| NSD-12 candidate | the Supabase Storage plugin checks the bucket itself only for listObjects (`Bucket is required`); readFile, uploadData, deleteFile and createSignedUrl with an empty bucket send a request whose path has an empty bucket segment (`GET /object//x.txt`, `POST /object//x.txt`, `DELETE /object/`, `POST /object/sign//x.txt`), and the queries succeed against a server that answers; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11p asserts today's requests next to listObjects refusing the same empty bucket and sending nothing (characterisation, default run), annotation `{type:"defect", description:"NSD-12 candidate"}`; it changes when the four operations check the bucket like listObjects | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/fixtures/dsl/plugins/supabase/supabaseCreateSignedUrlQuery.json b/e2e/fixtures/dsl/plugins/supabase/supabaseCreateSignedUrlQuery.json new file mode 100644 index 0000000000..336bf375da --- /dev/null +++ b/e2e/fixtures/dsl/plugins/supabase/supabaseCreateSignedUrlQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "supabase", + "comp": { + "actionName": "createSignedUrl", + "action": { + "bucket": "", + "fileName": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/supabase/supabaseDatasource.json b/e2e/fixtures/dsl/plugins/supabase/supabaseDatasource.json new file mode 100644 index 0000000000..8adddf3689 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/supabase/supabaseDatasource.json @@ -0,0 +1,10 @@ +{ + "name": "supabase", + "type": "supabase", + "datasourceConfig": { + "projectUrl": "http://placeholder.invalid", + "apiKey": "placeholder", + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} diff --git a/e2e/fixtures/dsl/plugins/supabase/supabaseDeleteFileQuery.json b/e2e/fixtures/dsl/plugins/supabase/supabaseDeleteFileQuery.json new file mode 100644 index 0000000000..cf7d16d1fc --- /dev/null +++ b/e2e/fixtures/dsl/plugins/supabase/supabaseDeleteFileQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "supabase", + "comp": { + "actionName": "deleteFile", + "action": { + "bucket": "", + "fileName": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/supabase/supabaseListObjectsQuery.json b/e2e/fixtures/dsl/plugins/supabase/supabaseListObjectsQuery.json new file mode 100644 index 0000000000..e346ba7111 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/supabase/supabaseListObjectsQuery.json @@ -0,0 +1,21 @@ +{ + "compType": "supabase", + "comp": { + "actionName": "listObjects", + "action": { + "bucket": "", + "path": "", + "search": "", + "limit": "10", + "offset": "", + "sortBy": "{\n \"column\": \"name\",\n \"order\": \"asc\"\n}", + "returnSignedUrl": false + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/supabase/supabaseQuery.json b/e2e/fixtures/dsl/plugins/supabase/supabaseQuery.json new file mode 100644 index 0000000000..7635f06977 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/supabase/supabaseQuery.json @@ -0,0 +1,13 @@ +{ + "compType": "supabase", + "comp": { + "actionName": "listBuckets", + "action": {}, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/supabase/supabaseReadFileQuery.json b/e2e/fixtures/dsl/plugins/supabase/supabaseReadFileQuery.json new file mode 100644 index 0000000000..a766ef5b40 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/supabase/supabaseReadFileQuery.json @@ -0,0 +1,18 @@ +{ + "compType": "supabase", + "comp": { + "actionName": "readFile", + "action": { + "bucket": "", + "fileName": "", + "encoding": "base64", + "transform": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/dsl/plugins/supabase/supabaseUploadDataQuery.json b/e2e/fixtures/dsl/plugins/supabase/supabaseUploadDataQuery.json new file mode 100644 index 0000000000..57745c67d0 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/supabase/supabaseUploadDataQuery.json @@ -0,0 +1,20 @@ +{ + "compType": "supabase", + "comp": { + "actionName": "uploadData", + "action": { + "bucket": "", + "fileName": "", + "encoding": "base64", + "data": "", + "contentType": "", + "returnSignedUrl": false + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/tests/datasource/plugin-supabase-storage.spec.ts b/e2e/tests/datasource/plugin-supabase-storage.spec.ts new file mode 100644 index 0000000000..0f2cca5e43 --- /dev/null +++ b/e2e/tests/datasource/plugin-supabase-storage.spec.ts @@ -0,0 +1,688 @@ +import { randomBytes } from "node:crypto"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, TAGS } from "../../src/constants"; +import { appDsl, button, nodePluginQuery, stackItems } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { boundText, boundTextTestId, openSeededView } from "../../src/components/scenario"; +import { expect, test } from "../../src/fixtures"; +import { recordsContain, type EchoRecord, type EchoTarget } from "../../src/security/echo"; + +/** + * D11: the Supabase Storage plugin of node-service (`server/node-service/src/plugins/supabase/run.ts`, the plugin id `supabase`; + * the Management API plugin `supabaseApi` is D8). It builds a `supabase-js` client for the data source's `projectUrl` with node-service's + * proxy `fetch` and calls the Storage API below `/storage/v1`. The project URL is the test's own echo target plus `/sb`, so + * the tests prove the request the client builds and the path of the canned answer into the app. They are NOT a fidelity test of + * Supabase. + * + * Measured on the images `3.0.0-e2e` and `3.0.1-e2e` (same requests and answers on both; supabase-js 2.45.4 prints itself in `x-client-info`): + * - The client keeps the path of the project URL, with or without a trailing slash: `/sb/storage/v1/...`. The host is the one of + * the project URL (the `e2e-echo` alias): no host name is derived from it, so every request reaches the echo. + * - The API key travels in two headers, `apikey: ` and `authorization: Bearer `; the tests assert both and that the key is + * in no other header, path or body of any request, nor in any answer of the query. + * - Requests carry the proxy fetch's `node-fetch` user agent, `accept-encoding: gzip,deflate` and `connection: close`. + * + * Not covered: a real Supabase project, the data source form's connection test (the plugin wires none: its validator is not registered). + */ +const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; + +/** + * Candidate defect: a storage error answer (any status) fails the query with `{"size":0,"timeout":0}`, the JSON of node-fetch's own + * `Response`, not with the message of the answer: storage-js recognises an HTTP error only as an instance of the global `Response`, and + * the proxy fetch answers with node-fetch's class. + */ +const ERROR_TEXT_DEFECT = { type: "defect", description: "NSD-9 candidate" } as const; +/** + * Candidate defect: the signed-URL validity the plugin sends as `expiresIn` is `Date.now() + 5 minutes` in milliseconds (a 13-digit number + * of the order of 1.8e12), computed once when node-service loads the plugin, while the API takes seconds. + */ +const EXPIRY_DEFECT = { type: "defect", description: "NSD-10 candidate" } as const; +/** Candidate defect: the `search` field of listObjects is read by the query form and never sent. */ +const SEARCH_DEFECT = { type: "defect", description: "NSD-11 candidate" } as const; +/** Candidate defect: only listObjects checks the bucket (`Bucket is required`); the other operations send a request for an empty bucket name. */ +const EMPTY_BUCKET_DEFECT = { type: "defect", description: "NSD-12 candidate" } as const; +/** Observation: an upload without a content type sends an empty `content-type` header (the editor's default is an empty text). */ +const EMPTY_CONTENT_TYPE_OBSERVATION = { type: "observation", description: "an upload without a content type sends an empty content-type header" } as const; + +const HTTP_OK = 200; +const HTTP_UNAUTHORIZED = 401; +const HTTP_BAD_REQUEST = 400; +const HTTP_NOT_FOUND = 404; +const QUERY_CODE_OK = "OK"; +const QUERY_CODE_FAILED = "FAILED"; +const MARKER_BYTES = 4; +const QUERY_ID = "q1"; +const QUERY_NAME = "q"; +const BUTTON_TEST_ID = "e2e-supabase-run"; +const RESULT_NAME = "label"; +const RAW_NAME = "raw"; +const SUCCESS_NAME = "succeeded"; +const JSON_CONTENT_TYPE = "application/json"; +const TEXT_CONTENT_TYPE = "text/plain"; +const SUPABASE_PLUGIN = "supabase"; + +/** The project URL of every test is the echo target plus this path; the Storage API lives below `STORAGE_PATH` of it. */ +const PROJECT_PATH = "/sb"; +const STORAGE_PATH = "/storage/v1"; + +/** What node-service's proxy fetch sends on every request (measured). */ +const NODE_FETCH_AGENT = "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"; +const ACCEPT_ENCODING = "gzip,deflate"; +const CONNECTION_CLOSE = "close"; +const ACCEPT_ANY = "*/*"; +const CLIENT_INFO = /^supabase-js-node\/\d+\.\d+\.\d+$/; +/** What a normalised header holds instead of a value that differs per image. */ +const SHAPE_OK = ""; +const SHAPE_BAD = ""; +/** The header storage-js adds to every upload (measured). */ +const UPLOAD_CACHE_CONTROL = "max-age=3600"; +const UPLOAD_UPSERT = "false"; + +/** The message of every failed storage call today: the JSON of node-fetch's `Response` (NSD-9). */ +const LOST_ERROR_TEXT = '{"size":0,"timeout":0}'; +const CANNED_ERROR_MESSAGE = "e2e-storage-error"; +const BUCKET_REQUIRED = "Bucket is required"; + +/** + * The validity of a signed URL the plugin intends (`expiresIn` is built from `1000 * 60 * 5`) and the smallest value that cannot be a + * number of seconds of any sensible validity: an epoch time in milliseconds after the year 2001 is larger than `1e12`. + */ +const INTENDED_EXPIRY_MS = 1000 * 60 * 5; +const EPOCH_MS_FLOOR = 1e12; +/** + * The app container's clock and the runner's clock are two clocks (two containers of one host here, but a remote Docker host would differ): + * the value is the container's time, the bound is the runner's. One hour is generous for any sane skew and still ten times smaller than the + * gap between milliseconds and seconds, so it cannot hide a plugin that sends seconds (the `EPOCH_MS_FLOOR` guard decides that). + */ +const CLOCK_SKEW_ALLOWANCE_MS = 60 * 60 * 1000; +/** + * The value is computed once, when node-service loads the plugin, so it is as old as the container (a run of this spec starts a fresh one): + * the lower bound allows a container that is up to six hours old, a bound no gate or full run of this suite comes near. + */ +const MAX_PLUGIN_AGE_MS = 6 * 60 * 60 * 1000; + +const BUCKET = "e2e"; +const FILE = "a.txt"; +const PREFIX = "p"; +/** The path and the search text of D11e: distinctive, so a record that holds them proves the field travelled. */ +const SEARCH_PREFIX = "e2e-prefix-folder"; +const SEARCH_TEXT = "e2e-search-needle"; +const TIMESTAMP = "2020-01-01T00:00:00.000Z"; + +/** Canned Storage API answers. */ +const BUCKETS = [{ id: BUCKET, name: BUCKET, owner: "e2e-owner", public: false, created_at: TIMESTAMP, updated_at: TIMESTAMP }]; +const LISTED_FILES = [{ name: FILE, id: "e2e-id", updated_at: TIMESTAMP, metadata: { size: 5 } }]; +const UPLOAD_ANSWER = { Key: `${BUCKET}/up.txt`, Id: "e2e-upload-id" }; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +function onlyRecord(records: EchoRecord[]): EchoRecord { + expect(records, "the echo received exactly one request").toHaveLength(1); + return records[0] as EchoRecord; +} + +/** The API key of a test: a value that must reach the echo only in the two headers that carry it. */ +function keyOf(marker: string): string { + return `e2eSecretKey${marker}`; +} + +/** The URL of the Storage API below the echo target, as the plugin's results show it (`url`, `signedUrl`). */ +function storageUrl(echo: EchoTarget): string { + return `${echo.url}${PROJECT_PATH}${STORAGE_PATH}`; +} + +/** What one recorded storage request must look like. `json` is the parsed body of a JSON request, `rawBody` the exact text of any other. */ +interface ExpectedStorageRequest { + method: string; + /** Path and query below `/sb/storage/v1`. */ + path: string; + key: string; + json?: unknown; + rawBody?: string; + /** The `content-type` of a request that has a body (JSON requests default to `application/json`). */ + contentType?: string; + /** Further stable headers (`cache-control`, `x-upsert`). */ + extraHeaders?: Record; +} + +/** + * Asserts one recorded storage request completely: method, path and query, body (a JSON body member for member, other bodies as text), + * the COMPLETE header set (each header's value; `x-client-info` by shape) and that the API key is in exactly the headers `apikey` and + * `authorization` (`Bearer `). + */ +function expectStorageRequest(record: EchoRecord, echo: EchoTarget, expected: ExpectedStorageRequest, label: string): void { + expect(record.method, `${label}: the method`).toBe(expected.method); + expect(record.path, `${label}: the path and query`).toBe(`${echo.path}${PROJECT_PATH}${STORAGE_PATH}${expected.path}`); + const hasBody = expected.json !== undefined || expected.rawBody !== undefined; + if (expected.json !== undefined) { + expect(JSON.parse(record.body), `${label}: the JSON body, member for member`).toEqual(expected.json); + } else { + expect(record.body, `${label}: the body`).toBe(expected.rawBody ?? ""); + } + const clientInfo = record.headers["x-client-info"]; + expect( + { ...record.headers, "x-client-info": typeof clientInfo === "string" && CLIENT_INFO.test(clientInfo) ? SHAPE_OK : SHAPE_BAD }, + `${label}: the complete header set`, + ).toEqual({ + apikey: expected.key, + authorization: `Bearer ${expected.key}`, + "x-client-info": SHAPE_OK, + accept: ACCEPT_ANY, + "user-agent": NODE_FETCH_AGENT, + "accept-encoding": ACCEPT_ENCODING, + host: new URL(echo.url).host, + connection: CONNECTION_CLOSE, + ...(hasBody ? { "content-length": String(Buffer.byteLength(record.body)), "content-type": expected.contentType ?? JSON_CONTENT_TYPE } : {}), + ...expected.extraHeaders, + }); +} + +/** + * The API key is in the headers `apikey` and `authorization` by design (asserted by `expectStorageRequest`) and nowhere else: with those two + * removed, no header, path or body of any request holds it, and no answer of the query does. Positive control: the unstripped records do hold it. + */ +function expectKeyOnlyInItsHeaders(records: EchoRecord[], key: string, answers: Array<{ json: unknown }>, label: string): void { + expect(recordsContain(records, key), `${label}: positive control, the key reaches the echo in its two headers`).toBe(true); + const stripped = records.map((record) => { + const { apikey: _apikey, authorization: _authorization, ...others } = record.headers; + return { ...record, headers: others }; + }); + expect(recordsContain(stripped, key), `${label}: the key is in no other header, path or body`).toBe(false); + for (const answer of answers) expect(JSON.stringify(answer.json).includes(key), `${label}: the key is in no answer of the query`).toBe(false); +} + +/** Asserts a signed-URL body's `expiresIn` (NSD-10) and returns it; the rest of the body is asserted by the caller. */ +function expiresInOf(record: EchoRecord, label: string): number { + const value = (JSON.parse(record.body) as { expiresIn?: unknown }).expiresIn; + expect(typeof value === "number" && Number.isInteger(value), `${label}: expiresIn is an integer number`).toBe(true); + const expiresIn = value as number; + expect(expiresIn, `${label}: expiresIn is an epoch time in milliseconds (13 digits), not a number of seconds`).toBeGreaterThan(EPOCH_MS_FLOOR); + expect(expiresIn, `${label}: it was computed before this request, as now plus five minutes at most (allowing for clock skew)`).toBeLessThanOrEqual(Date.now() + INTENDED_EXPIRY_MS + CLOCK_SKEW_ALLOWANCE_MS); + expect(expiresIn, `${label}: it is not older than the plugin's load time plus five minutes (allowing for clock skew)`).toBeGreaterThanOrEqual(Date.now() - MAX_PLUGIN_AGE_MS - CLOCK_SKEW_ALLOWANCE_MS); + return expiresIn; +} + +/** A data source from the recording whose project URL is the echo target's `/sb` (`suffix` appended, e.g. a slash) and whose key is `key`. */ +async function supabaseDatasource(page: Page, apiUser: RegisteredUser, echo: EchoTarget, key: string, suffix = ""): Promise { + return createNodePluginDatasource(page.request, { + orgId: apiUser.orgId, + recorded: recordedPluginDatasource(SUPABASE_PLUGIN), + config: { projectUrl: `${echo.url}${PROJECT_PATH}${suffix}`, apiKey: key }, + }); +} + +/** A saved app with one manual query of the recorded `variant` (not published: the draft runs with `viewMode: false`). */ +async function supabaseApp(page: Page, apiUser: RegisteredUser, echo: EchoTarget, key: string, variant: string, action: Record, suffix = ""): Promise { + const datasourceId = await supabaseDatasource(page, apiUser, echo, key, suffix); + const query = nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery(SUPABASE_PLUGIN, variant), action }); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: "e2e-supabase", dsl: appDsl([], { queries: [query] }) }); + return appId; +} + +async function runDraft(page: Page, appId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId: QUERY_ID, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +function expectSucceeded(answer: RawAnswer): void { + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); +} + +function expectFailed(answer: RawAnswer, message: string): void { + expectRan(answer); + expect({ success: envelopeOf(answer).success, queryCode: envelopeOf(answer).queryCode, message: envelopeOf(answer).message, data: envelopeOf(answer).data }, "the query failed with the measured message").toEqual({ + success: false, + queryCode: QUERY_CODE_FAILED, + message, + data: null, + }); +} + +/** Makes the echo answer everything below the storage API of this test's project with `body`, unless a longer sub-path has its own answer. */ +async function answerStorage(echo: EchoTarget, subPath: string, status: number, body: unknown, contentType = JSON_CONTENT_TYPE): Promise { + await echo.answer(`${PROJECT_PATH}${STORAGE_PATH}${subPath}`, { status, contentType, body: typeof body === "string" ? body : JSON.stringify(body) }); +} + +test.describe("Supabase Storage data source against the echo", NODE_SERVICE_DETAILS, () => { + test("D11a: listBuckets is a GET of the bucket list with the key in apikey and authorization", async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, "/bucket", HTTP_OK, BUCKETS); + const appId = await supabaseApp(page, apiUser, echo, key, "", {}); + expect(await echo.received(), "before the run the echo holds nothing of this test").toEqual([]); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + expectStorageRequest(onlyRecord(records), echo, { method: "GET", path: "/bucket", key }, "listBuckets"); + expectKeyOnlyInItsHeaders(records, key, [answer], "listBuckets"); + expect(envelopeOf(answer).data, "the buckets exactly as the API answered").toEqual(BUCKETS); + }); + + for (const row of [ + { title: "without a trailing slash", suffix: "" }, + { title: "with a trailing slash", suffix: "/" }, + ]) { + test(`D11b: a project URL ${row.title} keeps its path and reaches the storage API below it`, async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, "/bucket", HTTP_OK, BUCKETS); + const appId = await supabaseApp(page, apiUser, echo, key, "", {}, row.suffix); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + // the same path with and without the slash: `/sb/storage/v1/bucket`, never `/storage/v1/bucket` + const records = await echo.received(); + expectStorageRequest(onlyRecord(records), echo, { method: "GET", path: "/bucket", key }, `project URL ${row.title}`); + expectKeyOnlyInItsHeaders(records, key, [answer], `project URL ${row.title}`); + expect(envelopeOf(answer).data, "the buckets").toEqual(BUCKETS); + }); + } + + test("D11c: listObjects posts the prefix with the editor's defaults and answers each file with its public URL", async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, `/object/list/${BUCKET}`, HTTP_OK, LISTED_FILES); + const appId = await supabaseApp(page, apiUser, echo, key, "ListObjects", { bucket: BUCKET, path: PREFIX }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + // bucket in the PATH, not the host; the recorded defaults: limit 10, offset 0 (an empty text), sort by name ascending + expectStorageRequest( + onlyRecord(records), + echo, + { method: "POST", path: `/object/list/${BUCKET}`, key, json: { limit: 10, offset: 0, sortBy: { column: "name", order: "asc" }, prefix: PREFIX } }, + "listObjects", + ); + expectKeyOnlyInItsHeaders(records, key, [answer], "listObjects"); + expect(envelopeOf(answer).data, "the listed file and the public URL of it below the project URL, no signed URL").toEqual([ + { ...LISTED_FILES[0], url: `${storageUrl(echo)}/object/public/${BUCKET}/${PREFIX}/${FILE}` }, + ]); + }); + + test("D11d: listObjects sends the limit, the offset and the sort order of the query", async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, `/object/list/${BUCKET}`, HTTP_OK, []); + const sortBy = { column: "updated_at", order: "desc" }; + const appId = await supabaseApp(page, apiUser, echo, key, "ListObjects", { bucket: BUCKET, path: "", limit: 3, offset: 2, sortBy: JSON.stringify(sortBy) }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + expectStorageRequest(onlyRecord(records), echo, { method: "POST", path: `/object/list/${BUCKET}`, key, json: { limit: 3, offset: 2, sortBy, prefix: "" } }, "listObjects with paging"); + expectKeyOnlyInItsHeaders(records, key, [answer], "listObjects with paging"); + expect(envelopeOf(answer).data, "an empty listing is an empty list").toEqual([]); + }); + + test("D11e: the search field of listObjects is not sent", { annotation: SEARCH_DEFECT }, async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, `/object/list/${BUCKET}`, HTTP_OK, []); + const searched = await supabaseApp(page, apiUser, echo, key, "ListObjects", { bucket: BUCKET, path: SEARCH_PREFIX, search: SEARCH_TEXT }); + + const answer = await runDraft(page, searched); + + expectSucceeded(answer); + const records = await echo.received(); + // NSD-11 candidate: the body is exactly the one of a query with no search, the other fields travel (positive control inside the same body) + expectStorageRequest( + onlyRecord(records), + echo, + { method: "POST", path: `/object/list/${BUCKET}`, key, json: { limit: 10, offset: 0, sortBy: { column: "name", order: "asc" }, prefix: SEARCH_PREFIX } }, + "listObjects with a search text", + ); + expect(recordsContain(records, SEARCH_TEXT), "the search text is in no header, path or body").toBe(false); + expect(recordsContain(records, SEARCH_PREFIX), "positive control: the prefix of the same query reaches the echo").toBe(true); + expectKeyOnlyInItsHeaders(records, key, [answer], "listObjects with a search text"); + }); + + test("D11f: listObjects with returnSignedUrl signs every listed path in one more request", { annotation: EXPIRY_DEFECT }, async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + const signedPath = `/object/sign/${BUCKET}/${PREFIX}/${FILE}?token=t1`; + await answerStorage(echo, `/object/list/${BUCKET}`, HTTP_OK, LISTED_FILES); + await answerStorage(echo, `/object/sign/${BUCKET}`, HTTP_OK, [{ error: null, path: `${PREFIX}/${FILE}`, signedURL: signedPath }]); + const appId = await supabaseApp(page, apiUser, echo, key, "ListObjects", { bucket: BUCKET, path: PREFIX, returnSignedUrl: true }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + expect(records, "the echo holds the listing and the signing").toHaveLength(2); + expectStorageRequest(records[0] as EchoRecord, echo, { method: "POST", path: `/object/list/${BUCKET}`, key, json: { limit: 10, offset: 0, sortBy: { column: "name", order: "asc" }, prefix: PREFIX } }, "the listing"); + // NSD-10 candidate: an epoch time in milliseconds where the API takes seconds + const expiresIn = expiresInOf(records[1] as EchoRecord, "the signing"); + expectStorageRequest(records[1] as EchoRecord, echo, { method: "POST", path: `/object/sign/${BUCKET}`, key, json: { expiresIn, paths: [`${PREFIX}/${FILE}`] } }, "the signing"); + expectKeyOnlyInItsHeaders(records, key, [answer], "listObjects with signed URLs"); + expect(envelopeOf(answer).data, "the file with its signed URL (the API's relative URL below the project's storage URL) and its public URL").toEqual([ + { ...LISTED_FILES[0], signedUrl: `${storageUrl(echo)}${signedPath}`, url: `${storageUrl(echo)}/object/public/${BUCKET}/${PREFIX}/${FILE}` }, + ]); + }); + + for (const row of [ + { title: "text", encoding: "utf8", expected: "hello e2e" }, + { title: "base64 (the default)", encoding: undefined, expected: Buffer.from("hello e2e", "utf8").toString("base64") }, + ]) { + test(`D11g: readFile as ${row.title} downloads the object and answers its data and content type`, async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, `/object/${BUCKET}`, HTTP_OK, "hello e2e", TEXT_CONTENT_TYPE); + const appId = await supabaseApp(page, apiUser, echo, key, "ReadFile", { bucket: BUCKET, fileName: "dir/a b.txt", ...(row.encoding ? { encoding: row.encoding } : {}) }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + // the object name is percent-encoded in the path, bucket first + expectStorageRequest(onlyRecord(records), echo, { method: "GET", path: `/object/${BUCKET}/dir/a%20b.txt`, key }, "readFile"); + expectKeyOnlyInItsHeaders(records, key, [answer], "readFile"); + expect(envelopeOf(answer).data, "the data in the requested encoding and the answer's content type").toEqual({ data: row.expected, type: TEXT_CONTENT_TYPE }); + }); + } + + test("D11h: readFile with a transform downloads the rendered image and sends the transform as query parameters", async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, `/render/image`, HTTP_OK, "image-bytes", "image/png"); + const appId = await supabaseApp(page, apiUser, echo, key, "ReadFile", { bucket: BUCKET, fileName: "x.png", encoding: "utf8", transform: JSON.stringify({ width: 10 }) }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + expectStorageRequest(onlyRecord(records), echo, { method: "GET", path: `/render/image/authenticated/${BUCKET}/x.png?width=10`, key }, "readFile with a transform"); + expectKeyOnlyInItsHeaders(records, key, [answer], "readFile with a transform"); + expect(envelopeOf(answer).data, "the rendered bytes and their content type").toEqual({ data: "image-bytes", type: "image/png" }); + }); + + test("D11i: uploadData of text with a content type posts the text and answers the stored path", async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, `/object/${BUCKET}`, HTTP_OK, UPLOAD_ANSWER); + const appId = await supabaseApp(page, apiUser, echo, key, "UploadData", { bucket: BUCKET, fileName: "up.txt", encoding: "utf8", data: "hello up", contentType: TEXT_CONTENT_TYPE }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + expectStorageRequest( + onlyRecord(records), + echo, + { method: "POST", path: `/object/${BUCKET}/up.txt`, key, rawBody: "hello up", contentType: TEXT_CONTENT_TYPE, extraHeaders: { "cache-control": UPLOAD_CACHE_CONTROL, "x-upsert": UPLOAD_UPSERT } }, + "uploadData", + ); + expectKeyOnlyInItsHeaders(records, key, [answer], "uploadData"); + expect(envelopeOf(answer).data, "the path the API answered, its id and the full path").toEqual({ path: "up.txt", id: UPLOAD_ANSWER.Id, fullPath: UPLOAD_ANSWER.Key }); + }); + + test("D11j: uploadData of base64 without a content type posts the decoded bytes with an empty content-type header", { annotation: EMPTY_CONTENT_TYPE_OBSERVATION }, async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, `/object/${BUCKET}`, HTTP_OK, UPLOAD_ANSWER); + const appId = await supabaseApp(page, apiUser, echo, key, "UploadData", { bucket: BUCKET, fileName: "up.txt", data: Buffer.from("hello", "utf8").toString("base64") }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + expectStorageRequest( + onlyRecord(records), + echo, + { method: "POST", path: `/object/${BUCKET}/up.txt`, key, rawBody: "hello", contentType: "", extraHeaders: { "cache-control": UPLOAD_CACHE_CONTROL, "x-upsert": UPLOAD_UPSERT } }, + "uploadData without a content type", + ); + expectKeyOnlyInItsHeaders(records, key, [answer], "uploadData without a content type"); + expect(envelopeOf(answer).data, "the stored path").toEqual({ path: "up.txt", id: UPLOAD_ANSWER.Id, fullPath: UPLOAD_ANSWER.Key }); + }); + + test("D11k: uploadData with returnSignedUrl uploads, then asks for a signed URL of the same name", { annotation: EXPIRY_DEFECT }, async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + const signedPath = `/object/sign/${BUCKET}/up.txt?token=t2`; + await answerStorage(echo, `/object/${BUCKET}`, HTTP_OK, UPLOAD_ANSWER); + await answerStorage(echo, `/object/sign/${BUCKET}`, HTTP_OK, { signedURL: signedPath }); + const appId = await supabaseApp(page, apiUser, echo, key, "UploadData", { bucket: BUCKET, fileName: "up.txt", encoding: "utf8", data: "hello up", contentType: TEXT_CONTENT_TYPE, returnSignedUrl: true }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + expect(records, "the echo holds the upload and the signing").toHaveLength(2); + expectStorageRequest( + records[0] as EchoRecord, + echo, + { method: "POST", path: `/object/${BUCKET}/up.txt`, key, rawBody: "hello up", contentType: TEXT_CONTENT_TYPE, extraHeaders: { "cache-control": UPLOAD_CACHE_CONTROL, "x-upsert": UPLOAD_UPSERT } }, + "the upload", + ); + const expiresIn = expiresInOf(records[1] as EchoRecord, "the signing"); + expectStorageRequest(records[1] as EchoRecord, echo, { method: "POST", path: `/object/sign/${BUCKET}/up.txt`, key, json: { expiresIn } }, "the signing"); + expectKeyOnlyInItsHeaders(records, key, [answer], "uploadData with a signed URL"); + expect(envelopeOf(answer).data, "the stored path and the signed URL below the project's storage URL").toEqual({ + path: "up.txt", + id: UPLOAD_ANSWER.Id, + fullPath: UPLOAD_ANSWER.Key, + signedUrl: `${storageUrl(echo)}${signedPath}`, + }); + }); + + test("D11l: deleteFile sends a DELETE with the name in a prefixes list and answers success", async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, `/object/${BUCKET}`, HTTP_OK, []); + const appId = await supabaseApp(page, apiUser, echo, key, "DeleteFile", { bucket: BUCKET, fileName: FILE }); + + const answer = await runDraft(page, appId); + + expectSucceeded(answer); + const records = await echo.received(); + expectStorageRequest(onlyRecord(records), echo, { method: "DELETE", path: `/object/${BUCKET}`, key, json: { prefixes: [FILE] } }, "deleteFile"); + expectKeyOnlyInItsHeaders(records, key, [answer], "deleteFile"); + expect(envelopeOf(answer).data, "the plugin's own answer, not the API's").toEqual({ success: true }); + }); + + test("D11m: createSignedUrl posts the validity and answers the signed URL below the project's storage URL", { annotation: EXPIRY_DEFECT }, async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + const signedPath = `/object/sign/${BUCKET}/${FILE}?token=t3`; + await answerStorage(echo, `/object/sign/${BUCKET}`, HTTP_OK, { signedURL: signedPath }); + const first = await supabaseApp(page, apiUser, echo, key, "CreateSignedUrl", { bucket: BUCKET, fileName: FILE }); + + const answer = await runDraft(page, first); + + expectSucceeded(answer); + const records = await echo.received(); + const firstRecord = onlyRecord(records); + // NSD-10 candidate: the value is an epoch time in milliseconds, not a number of seconds + const expiresIn = expiresInOf(firstRecord, "the first signing"); + expectStorageRequest(firstRecord, echo, { method: "POST", path: `/object/sign/${BUCKET}/${FILE}`, key, json: { expiresIn } }, "createSignedUrl"); + expectKeyOnlyInItsHeaders(records, key, [answer], "createSignedUrl"); + expect(envelopeOf(answer).data, "the signed URL").toEqual({ signedUrl: `${storageUrl(echo)}${signedPath}` }); + + // the value is computed once per node-service process: a second query, later, sends the very same number + const second = await supabaseApp(page, apiUser, echo, key, "CreateSignedUrl", { bucket: BUCKET, fileName: FILE }); + const secondAnswer = await runDraft(page, second); + expectSucceeded(secondAnswer); + const afterSecond = await echo.received(); + expect(afterSecond, "the echo holds both signings").toHaveLength(2); + expect(expiresInOf(afterSecond[1] as EchoRecord, "the second signing"), "the second signing carries the same expiresIn").toBe(expiresIn); + expectStorageRequest(afterSecond[1] as EchoRecord, echo, { method: "POST", path: `/object/sign/${BUCKET}/${FILE}`, key, json: { expiresIn } }, "createSignedUrl, second query"); + expect(envelopeOf(secondAnswer).data, "the second signed URL").toEqual({ signedUrl: `${storageUrl(echo)}${signedPath}` }); + expectKeyOnlyInItsHeaders(afterSecond, key, [answer, secondAnswer], "both createSignedUrl queries"); + }); + + test.describe("a storage error answer fails the query with the text of node-fetch's response", () => { + const rows = [ + { + title: "listBuckets 400", + variant: "", + action: {}, + subPath: "/bucket", + status: HTTP_BAD_REQUEST, + request: { method: "GET", path: "/bucket" }, + okBody: BUCKETS, + okData: BUCKETS, + }, + { + title: "readFile 404", + variant: "ReadFile", + action: { bucket: BUCKET, fileName: "absent.txt", encoding: "utf8" }, + subPath: `/object/${BUCKET}`, + status: HTTP_NOT_FOUND, + request: { method: "GET", path: `/object/${BUCKET}/absent.txt` }, + okBody: "present", + okData: { data: "present", type: JSON_CONTENT_TYPE }, + }, + { + title: "listBuckets 401", + variant: "", + action: {}, + subPath: "/bucket", + status: HTTP_UNAUTHORIZED, + request: { method: "GET", path: "/bucket" }, + okBody: BUCKETS, + okData: BUCKETS, + }, + ]; + for (const row of rows) { + test(`D11n: ${row.title}`, { annotation: ERROR_TEXT_DEFECT }, async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, row.subPath, row.status, { statusCode: String(row.status), error: "e2e", message: CANNED_ERROR_MESSAGE }); + const appId = await supabaseApp(page, apiUser, echo, key, row.variant, row.action); + + const failed = await runDraft(page, appId); + + // NSD-9 candidate: the message of the answer is lost, node-fetch's Response is printed instead + expectFailed(failed, LOST_ERROR_TEXT); + const afterFailure = await echo.received(); + expectStorageRequest(onlyRecord(afterFailure), echo, { ...row.request, key }, `the failing ${row.title}`); + + // control: the same query on the same data source succeeds once the API answers 200, so the answer decided + await answerStorage(echo, row.subPath, HTTP_OK, row.okBody); + const control = await runDraft(page, appId); + + expectSucceeded(control); + expect(envelopeOf(control).data, "control: the canned success data").toEqual(row.okData); + const records = await echo.received(); + expect(records, "the echo holds the failing and the control request").toHaveLength(2); + expectStorageRequest(records[1] as EchoRecord, echo, { ...row.request, key }, `the control ${row.title}`); + expectKeyOnlyInItsHeaders(records, key, [failed, control], row.title); + }); + } + + test("D11o: createSignedUrl and listObjects fail the same way", { annotation: ERROR_TEXT_DEFECT }, async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, "", HTTP_BAD_REQUEST, { statusCode: "400", error: "e2e", message: CANNED_ERROR_MESSAGE }); + const signing = await supabaseApp(page, apiUser, echo, key, "CreateSignedUrl", { bucket: BUCKET, fileName: FILE }); + const listing = await supabaseApp(page, apiUser, echo, key, "ListObjects", { bucket: BUCKET }); + + const signingAnswer = await runDraft(page, signing); + const listingAnswer = await runDraft(page, listing); + + expectFailed(signingAnswer, LOST_ERROR_TEXT); + expectFailed(listingAnswer, LOST_ERROR_TEXT); + const records = await echo.received(); + expect(records, "the echo holds the signing and the listing").toHaveLength(2); + expectStorageRequest(records[0] as EchoRecord, echo, { method: "POST", path: `/object/sign/${BUCKET}/${FILE}`, key, json: { expiresIn: expiresInOf(records[0] as EchoRecord, "the signing") } }, "the failing signing"); + expectStorageRequest(records[1] as EchoRecord, echo, { method: "POST", path: `/object/list/${BUCKET}`, key, json: { limit: 10, offset: 0, sortBy: { column: "name", order: "asc" }, prefix: "" } }, "the failing listing"); + expectKeyOnlyInItsHeaders(records, key, [signingAnswer, listingAnswer], "the failing calls"); + + // control: the same two queries succeed once the API answers 200 on those paths, so the answers decided + const signedPath = `/object/sign/${BUCKET}/${FILE}?token=t5`; + await answerStorage(echo, "/object/sign", HTTP_OK, { signedURL: signedPath }); + await answerStorage(echo, "/object/list", HTTP_OK, []); + const signedAnswer = await runDraft(page, signing); + const listedAnswer = await runDraft(page, listing); + + expectSucceeded(signedAnswer); + expectSucceeded(listedAnswer); + expect(envelopeOf(signedAnswer).data, "control: the signed URL").toEqual({ signedUrl: `${storageUrl(echo)}${signedPath}` }); + expect(envelopeOf(listedAnswer).data, "control: the empty listing").toEqual([]); + const all = await echo.received(); + expect(all, "the echo holds the two failing and the two control requests").toHaveLength(4); + expectStorageRequest(all[2] as EchoRecord, echo, { method: "POST", path: `/object/sign/${BUCKET}/${FILE}`, key, json: { expiresIn: expiresInOf(all[2] as EchoRecord, "the control signing") } }, "the control signing"); + expectStorageRequest(all[3] as EchoRecord, echo, { method: "POST", path: `/object/list/${BUCKET}`, key, json: { limit: 10, offset: 0, sortBy: { column: "name", order: "asc" }, prefix: "" } }, "the control listing"); + expectKeyOnlyInItsHeaders(all, key, [signingAnswer, listingAnswer, signedAnswer, listedAnswer], "the failing and the control calls"); + }); + }); + + test("D11p: only listObjects refuses an empty bucket; the other operations send a request for it", { annotation: EMPTY_BUCKET_DEFECT }, async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, "/object", HTTP_OK, UPLOAD_ANSWER); + await answerStorage(echo, "/object/sign", HTTP_OK, { signedURL: "/object/sign/x?token=t4" }); + const listing = await supabaseApp(page, apiUser, echo, key, "ListObjects", { bucket: "" }); + + const refused = await runDraft(page, listing); + expectFailed(refused, BUCKET_REQUIRED); + expect(await echo.received(), "listObjects sent nothing").toEqual([]); + + // NSD-12 candidate: the other four send a request whose path has an empty bucket segment + const rows: Array<{ variant: string; action: Record; request: Omit }> = [ + { variant: "ReadFile", action: { bucket: "", fileName: "x.txt", encoding: "utf8" }, request: { method: "GET", path: "/object//x.txt" } }, + { + variant: "UploadData", + action: { bucket: "", fileName: "x.txt", encoding: "utf8", data: "x", contentType: TEXT_CONTENT_TYPE }, + request: { method: "POST", path: "/object//x.txt", rawBody: "x", contentType: TEXT_CONTENT_TYPE, extraHeaders: { "cache-control": UPLOAD_CACHE_CONTROL, "x-upsert": UPLOAD_UPSERT } }, + }, + { variant: "DeleteFile", action: { bucket: "", fileName: "x.txt" }, request: { method: "DELETE", path: "/object/", json: { prefixes: ["x.txt"] } } }, + { variant: "CreateSignedUrl", action: { bucket: "", fileName: "x.txt" }, request: { method: "POST", path: "/object/sign//x.txt" } }, + ]; + const answers: RawAnswer[] = [refused]; + for (const [index, row] of rows.entries()) { + const appId = await supabaseApp(page, apiUser, echo, key, row.variant, row.action); + const answer = await runDraft(page, appId); + answers.push(answer); + expectSucceeded(answer); + const records = await echo.received(); + expect(records, `${row.variant}: exactly one more request reached the echo`).toHaveLength(index + 1); + const record = records[index] as EchoRecord; + const request = row.variant === "CreateSignedUrl" ? { ...row.request, json: { expiresIn: expiresInOf(record, row.variant) } } : row.request; + expectStorageRequest(record, echo, { ...request, key }, `${row.variant} with an empty bucket`); + } + expectKeyOnlyInItsHeaders(await echo.received(), key, answers, "the empty-bucket calls"); + }); + + test("D11q: the published view shows the bucket name after a click", async ({ page, apiUser, echo }) => { + const key = keyOf(uniqueMarker()); + await answerStorage(echo, "/bucket", HTTP_OK, BUCKETS); + const datasourceId = await supabaseDatasource(page, apiUser, echo, key); + // before the first run `q.data` is not a list + const expression = `{{${QUERY_NAME}.data ? ${QUERY_NAME}.data[0].name : ""}}`; + const view = await openSeededView( + page, + apiUser.orgId, + "e2e-supabase-view", + stackItems([ + button({ id: "b1", name: "button1", text: "Run", testId: BUTTON_TEST_ID, onClickQuery: QUERY_NAME }), + boundText({ id: "t1", name: RESULT_NAME, expression }), + // `success` also reads `true` before the first run (measured on the Turso view), so only the state after the click proves anything + boundText({ id: "t2", name: SUCCESS_NAME, expression: `{{String(${QUERY_NAME}.success)}}` }), + // the whole answer of the query as text, to search it for the key + boundText({ id: "t3", name: RAW_NAME, expression: `{{JSON.stringify(${QUERY_NAME}.data)}}` }), + ]), + { queries: [nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery(SUPABASE_PLUGIN, ""), action: {} })] }, + ); + + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "before the click the text is empty").toHaveText(""); + expect(await echo.received(), "before the click the echo holds nothing of this test").toEqual([]); + await view.buttonByTestId(BUTTON_TEST_ID).click(); + await expect(view.byTestId(boundTextTestId(SUCCESS_NAME)), "after the click the query succeeded").toHaveText("true"); + await expect(view.byTestId(boundTextTestId(RESULT_NAME)), "after the click the text shows the bucket's name").toHaveText(BUCKET); + const records = await echo.received(); + expectStorageRequest(onlyRecord(records), echo, { method: "GET", path: "/bucket", key }, "the click's listBuckets"); + const shownAnswer = (await view.byTestId(boundTextTestId(RAW_NAME)).textContent()) ?? ""; + expect(JSON.parse(shownAnswer), "the whole answer the view holds is the canned buckets").toEqual(BUCKETS); + expectKeyOnlyInItsHeaders(records, key, [{ json: JSON.parse(shownAnswer) }], "the click's listBuckets"); + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index 6854a3ed5d..63807d7bf5 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -338,6 +338,46 @@ test.describe("node-service data source helpers", { tag: [TAGS.NODE_SERVICE] }, }); }); + test("the supabase recordings are the form's body and the editor's saved queries (one per action), with no value of the recording session", () => { + const datasource = recordedPluginDatasource("supabase"); + expect(datasource.type, "the data source type").toBe("supabase"); + expect(Object.keys(datasource), "no workspace id").toEqual(["name", "type", "datasourceConfig"]); + expect(datasource.datasourceConfig, "the form's fields, with placeholders").toEqual({ + projectUrl: NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL, + apiKey: "placeholder", + authConfigType: "NO_AUTH", + sslCertVerificationType: "VERIFY_CA_CERT", + }); + const variants = { "": "listBuckets", ListObjects: "listObjects", ReadFile: "readFile", UploadData: "uploadData", DeleteFile: "deleteFile", CreateSignedUrl: "createSignedUrl" }; + const files = ["supabaseDatasource.json"]; + for (const [variant, actionName] of Object.entries(variants)) { + const query = recordedPluginQuery("supabase", variant); + expect(query.compType, `supabase${variant}: the query type`).toBe("supabase"); + expect(query.comp.actionName, `supabase${variant}: the recorded action`).toBe(actionName); + expect(Object.keys(query), `supabase${variant}: only what the builder keeps`).toEqual(["compType", "comp"]); + expect(query.comp.headers, `supabase${variant}: the editor's empty header row`).toEqual([{ key: "", value: "" }]); + files.push(`supabase${variant}Query.json`); + } + const text = files.map((file) => readFileSync(join(RECORDED_PLUGINS_DIR, "supabase", file), "utf8")).join("\n"); + expect(text, "a 24-hex id").not.toMatch(/\b[0-9a-f]{24}\b/); + expect(text, "an echo address").not.toContain("e2e-echo"); + expect(text, "an epoch of 10 digits or more").not.toMatch(/\b\d{10,}\b/); + expect(recordedPluginQuery("supabase", "").comp.action, "listBuckets has no parameters").toEqual({}); + expect(recordedPluginQuery("supabase", "ListObjects").comp.action, "listObjects: the editor's defaults (the limit is saved as text, the sort order as JSON text)").toEqual({ + bucket: "", + path: "", + search: "", + limit: "10", + offset: "", + sortBy: JSON.stringify({ column: "name", order: "asc" }, null, 4), + returnSignedUrl: false, + }); + expect(recordedPluginQuery("supabase", "ReadFile").comp.action, "readFile: base64 is the editor's default encoding").toEqual({ bucket: "", fileName: "", encoding: "base64", transform: "" }); + expect(recordedPluginQuery("supabase", "UploadData").comp.action, "uploadData").toEqual({ bucket: "", fileName: "", encoding: "base64", data: "", contentType: "", returnSignedUrl: false }); + expect(recordedPluginQuery("supabase", "DeleteFile").comp.action, "deleteFile").toEqual({ bucket: "", fileName: "" }); + expect(recordedPluginQuery("supabase", "CreateSignedUrl").comp.action, "createSignedUrl").toEqual({ bucket: "", fileName: "" }); + }); + test("recordedPluginQuery with a variant reads Query.json, refuses a variant that is not a file name part and names the missing file", () => { expect(recordedPluginQuery("s3", "DeleteFile").comp.actionName).toBe("deleteFile"); expect(recordedPluginQuery("s3", ""), "an empty variant is the plain recording").toEqual(recordedPluginQuery("s3")); From 84e3c53a7f96eb606dca38c6810f48df6bab8635 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 20:58:14 +0100 Subject: [PATCH 14/20] test: add an opt-in sidecar mechanism and Firebird node-service scenarios Adds an opt-in way to run node-service data source tests that need a real server which does not speak HTTP. With E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 the run script starts a pinned Firebird server on the run network, waits until it answers, makes it reachable from both the app container and the test runner, and removes it on exit even when the run fails. Without the flag nothing extra is started and the tests tagged @node-service-sidecar are neither listed nor run. The flag is refused on the non-default stack profiles. The outbound-host rule in AGENTS.md now names the opt-in sidecars. Adds recorded Firebird data source and query fixtures and scenarios for the connection test, queries and rows, parameter binding in SQL order, error messages, and the published view. A failing query that never detaches is characterised and annotated as a defect candidate. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 13 +- e2e/README.md | 34 +- .../plugins/firebird/firebirdDatasource.json | 15 + .../dsl/plugins/firebird/firebirdQuery.json | 16 + e2e/fixtures/firebird/init.sql | 26 ++ e2e/scripts/run-in-docker.sh | 85 ++++- e2e/src/constants.ts | 27 ++ e2e/src/datasource/firebird.ts | 46 +++ e2e/src/run-selection.ts | 13 +- e2e/tests/datasource/plugin-firebird.spec.ts | 343 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 110 +++++- e2e/tests/foundation/run-selection.spec.ts | 149 +++++++- 12 files changed, 845 insertions(+), 32 deletions(-) create mode 100644 e2e/fixtures/dsl/plugins/firebird/firebirdDatasource.json create mode 100644 e2e/fixtures/dsl/plugins/firebird/firebirdQuery.json create mode 100644 e2e/fixtures/firebird/init.sql create mode 100644 e2e/src/datasource/firebird.ts create mode 100644 e2e/tests/datasource/plugin-firebird.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index a6729c84a5..37352ca13d 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -74,7 +74,7 @@ Accepted exceptions: - Editor-built apps are allowed when the editor flow is the subject (`tests/editor/`, `smoke/editor-drag.spec.ts`, M3). MUST NOT: -- Hard-code credentials, host names, ports or generated resource ids: use `uniqueEmail`, `TEST_PASSWORD`, `POSTGRES`, +- Hard-code credentials, host names, ports or generated resource ids: use `uniqueEmail`, `TEST_PASSWORD`, `POSTGRES`, `FIREBIRD`, `APP_PAGE`, ids returned by the API. Deterministic DSL item ids and test ids local to one spec are fine. - Let tests depend on each other or on test order. @@ -129,7 +129,8 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `tests/datasource/plugin-supabase-storage.spec.ts`, D11; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `tests/datasource/plugin-supabase-storage.spec.ts`, D11; `tests/datasource/plugin-firebird.spec.ts`, D12, which also wears the opt-in tag of the next bullet; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service-sidecar`: a node-service data source test that needs a sidecar of its own because the plugin does not speak HTTP (today Firebird, `tests/datasource/plugin-firebird.spec.ts`, D12; `TAGS.NODE_SERVICE_SIDECAR`). Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of the default run (neither listed nor run, and `run-in-docker.sh` starts no such container), in only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` (default stack only). A spec that calls `firebirdConnection()` must tag every test with it (a guard in `foundation/run-selection.spec.ts` parses the spec: write `{ tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }` on the describe or the test, not through a variable). Never put the tag text in a test title: the default `grepInvert` matches titles too and would drop the test. The helper that reads a sidecar's host variable throws when it is unset, so a test selected without its sidecar fails loudly. Later sidecars add their container under the same flag. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). @@ -170,9 +171,9 @@ MUST NOT: `test-results`, `playwright-report`), and do not run `playwright test` directly while a stack of this checkout runs. - Edit anything in `e2e/evidence/` (git-ignored, local). Do not cite it as if it were in git. - Reach a real external host, switch the guard off, or add a route that allows another origin. Only `@npm` tests need - the app container to reach the npm registry. The one place the backend may be pointed at is the run's own echo sidecar (`echo` fixture, `src/security/echo.ts`); never give a data source or a registry entry any other URL. + the app container to reach the npm registry. The places the backend may be pointed at are the run's own echo sidecar (`echo` fixture, `src/security/echo.ts`) and, only in a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, the opt-in node-service sidecars: today the Firebird sidecar (`firebirdConnection()`, `src/datasource/firebird.ts`). Later opt-in sidecars add their names to this sentence. Never give a data source or a registry entry any other URL, and never rely on a placeholder host failing to resolve: every connection of a sidecar test goes to the sidecar. - Import `test` from `@playwright/test` in a spec that opens a page or uses the stack: the network guard exists only in the `test` of `src/fixtures.ts` (accepted exception for stack-free unit specs below). -- Commit secrets. The PostgreSQL password in `src/constants.ts` is the throw-away one of the sidecar. +- Commit secrets. The PostgreSQL password in `src/constants.ts` is the throw-away one of the sidecar. The Firebird password in `src/constants.ts` is likewise the throw-away one of its own sidecar. - Let the super admin's password (`E2E_SUPERUSER_PASSWORD`, new every run, set by `run-in-docker.sh`) reach a command line, log, trace, report, test title, annotation or error message; keep `set -x` off in the script. Never give the password to a matcher as the expected or received value (`expect(text).not.toContain(password)` prints it when it fails): assert `text.includes(password)` is `false`. The sign-in lives in an automatic worker fixture (`superAdminState`) because a request context created inside a test lands in its trace; do not sign the super admin in from a test or a helper, and create no request context in a helper. Every test that uses the `superAdmin` fixture carries `TAGS.SUPERADMIN` (a guard in `foundation/run-selection.spec.ts` checks it by parsing the spec with the TypeScript compiler: write the tag as `TAGS.SUPERADMIN` in the test's or its describe's details, a mention in a comment or title does not count). The super admin is ONE account shared by all workers: never switch its workspace or change its password. It hangs once the stack holds more than about 420 workspaces (README, security section): the SEC-R16 tests therefore carry `@superadmin` and run only on request (`E2E_INCLUDE_SUPERADMIN=1`); keep such runs short. - Duplicate a helper that exists: @@ -192,6 +193,7 @@ MUST NOT: | negative and counter reads, local storage | `expectTextStays`, `countAfterEquals`, `parseCounter`, `rawLocalStorage` | `src/logic/helpers.ts` | | media | `PNG_RED`, `PNG_BLUE`, `WAV`, `WEBM`, `MP4`, `PDF`, `PDF_RAW_B64` | `src/media.ts` | | security actors, quarantine, answers, tokens | `Actor`, `adminOfApiUser`, `joinWorkspace`, `makeDeveloper`, `makeAdmin`, `grantApp`, `seedPrivateApp`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `securityTestDetails`, `securityCandidateDetails`, `expectAnswer`, `expectDeniedAs`, `forgeApiKeyToken`, `forgeUnsignedToken`, `withRandomSignature`, `tokenIsSignedWith`, `superAdminCredentials`, `SUPER_ADMIN_ENV`, `enterpriseAdmin` (ENTERPRISE stack: an actor the super admin makes admin of the one workspace), `echoTargetPath`, `echoReadPrefix`, `echoBaseUrl`, `echoUrlByIp` (an echo target URL with its host replaced by the echo's IP address, `E2E_ECHO_IP`: for a plugin that derives a host name from its endpoint, e.g. an S3 bucket call; never address a bucket of the `e2e-echo` alias), `recordsContain` (requests the SERVER makes, read back from the HTTP echo sidecar: the `echo` fixture gives a test its own target `url` and `received()`; a denial must follow a positive control that the echo does receive from that path; compare a secret with `recordsContain(...)` as a boolean, never as a matcher's value) (the `actor`, `superAdmin` and `echo` fixtures are in `src/fixtures.ts`; the raw-answer helper `apiRaw` and the other security API helpers are in `src/api/client.ts`) | `src/security/actors.ts`, `scene.ts`, `quarantine.ts`, `assertions.ts`, `tokens.ts`, `super-admin.ts`, `enterprise.ts`, `echo.ts` | +| Firebird sidecar connection (opt-in sidecar: throws `FirebirdSidecarMissingError` when `E2E_FIREBIRD_HOST` is unset), the rows of `fixtures/firebird/init.sql` | `firebirdConnection`, `FirebirdSidecarMissingError`, `FIREBIRD_ITEMS` | `src/datasource/firebird.ts` | | pages | `EditorPage`, `AppViewPage`, `PropertyPanel`, `QueryPanel`, `TableView`, `ExtensionsPanel`, `AppListPage`, `AuthPage`, `LoginPage`, `UserMenu`, `SettingPage`, `DatasourcePage` | `src/pages/` | Accepted exception to the `test` import rule: stack-free unit specs that open no browser page (no `page`, no app) may @@ -267,6 +269,8 @@ e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 # gene E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --grep @quarantine E2E_INCLUDE_INSERT_ALL=1 e2e/scripts/run-in-docker.sh --grep @insert-all --workers=4 # S1 gate, once E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin # SEC-R16a, R16b (R16c, R16d also need E2E_INCLUDE_QUARANTINE=1) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-firebird.spec.ts # D12 gate: starts the Firebird sidecar (image pull, a few seconds) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # only the tests that need a sidecar e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/modules/module-editor-host.spec.ts # M3 gate E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/security/enterprise.spec.ts # ENTERPRISE stack gate (its own stack; never at the same time as another run) E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_ENTERPRISE_TAKEOVER=1 E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh # SEC-E05 ALONE, on its own stack @@ -280,6 +284,7 @@ Directory `e2e/` (no stack; `--reporter=list` is required so no report files are LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_INCLUDE_QUARANTINE=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_INCLUDE_SUPERADMIN=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # adds the D12 tests E2E_INCLUDE_INSERT_ALL=1 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_SUPERADMIN=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_STACK_PROFILE=enterprise LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # the SEC-E tests only ``` diff --git a/e2e/README.md b/e2e/README.md index bbb4f44e43..eb3a75c3b7 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; Firebird (node-firebird over TCP, D12) runs against a Firebird sidecar of its own that only a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` starts, and a default run neither starts it nor lists or runs those tests; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -37,6 +37,12 @@ lifecycle (insert, save, publish, load) is covered by S1 when `@insert-all` runs - **PostgreSQL sidecar:** `postgres:17-alpine` (pinned by digest) with `fixtures/sql/init.sql`: `items` (2 rows), `products` (25 shared read-only rows), `notes` (writes, owner-scoped). Host name in `E2E_POSTGRES_HOST`; connection constants are `POSTGRES` in `src/constants.ts`. +- **Firebird sidecar (opt-in):** the Firebird plugin of node-service speaks the Firebird wire protocol over TCP, which the HTTP echo cannot stand in for, so its tests (D12, `tests/datasource/plugin-firebird.spec.ts`) run against a real Firebird server. It is OPT-IN: + - **Flag and tag:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` (`RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS`) and the tag `@node-service-sidecar` (`TAGS.NODE_SERVICE_SIDECAR`), worn next to `@node-service`. The default selection leaves the tag out (`excludedTags` in `src/run-selection.ts`), exactly like `@superadmin`. + - **A default run** (no flag) starts no Firebird container, pulls no Firebird image, passes no `E2E_FIREBIRD_HOST` to the runner, and neither lists nor runs the D12 tests (`--list` shows 0 for `--grep @node-service-sidecar`). **A run with the flag** starts the sidecar after the echo, waits until a SELECT of the seeded table through the image's own `isql` answers over TCP, gives the app container and the runner the entry `--add-host e2e-firebird:` (the same reason as the echo's: the name must not fall back to an outside resolver), passes `E2E_FIREBIRD_HOST=e2e-firebird` to the runner, and removes the container in the cleanup trap however the run ends. The flag is refused on another stack profile (those runs select no sidecar test). A test selected without the sidecar fails with a named error (`firebirdConnection()` throws when the host variable is unset). + - **Image:** `firebirdsql/firebird:3.0.12`, pinned by tag and digest (`sha256:e45c9bc4fdacaaddc1980a05b7bb8b297f09fe019eadefb059006efe4dafe875`; `FIREBIRD_IMAGE` overrides it), data from `fixtures/firebird/init.sql` (`FB_ITEMS`, 3 read-only rows; `FB_NOTES`, writes scoped by owner), throw-away user and password in `FIREBIRD` of `src/constants.ts` and in the script. Why this one, measured with node-firebird 1.1.9 (the version node-service installs) from the runner: 3.0.12, 4.0.5 and 5.0.4 all refuse the attach with the image's defaults (3.0.12 and 5.0.4: "Incompatible wire encryption levels requested on client and server", WireCrypt `Required`; 4.0.5: "Error occurred during login"). 4.0.5 and 5.0.4 attached with `FIREBIRD_CONF_AuthServer=Srp,Legacy_Auth` plus `FIREBIRD_CONF_WireCrypt=Disabled` (one attempt each). 3.0.12 attached with `FIREBIRD_CONF_WireCrypt=Enabled` or `FIREBIRD_USE_LEGACY_AUTH=true`, but with its default Srp login 12 of 100 attaches failed with "Your user name and password are not defined" (node-firebird's client-side Srp; also seen through the app: 4 of 14 queries of one probe), while with `FIREBIRD_USE_LEGACY_AUTH=true` 100 of 100 attached. The sidecar therefore runs 3.0.12 with `FIREBIRD_USE_LEGACY_AUTH=true` (Legacy_Auth first, WireCrypt `Enabled`). Limit of that choice: Legacy_Auth compares only the first eight characters of a password (measured: a wrong password that shares them attached), so the wrong password of D12b differs within them; the sidecar is not evidence about the Srp login of Firebird 3, 4 or 5, which node-firebird 1.1.9 fails at random. + - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar` (or name the spec file). + - **Cost, measured here:** image 156 MB (`docker image inspect`), a cold pull of the pinned digest took 3 s (a fast link and a warm registry mirror: expect more elsewhere), the container accepted the readiness SELECT within about 3 s of starting (the script logged `Firebird sidecar ready after 0s`: the wait ran after the PostgreSQL wait of 2 s), and a gate of 110 tests ran in about 23 s. Runs without the flag pay nothing. - **HTTP echo sidecar** (`scripts/echo-server.js`, started by `run-in-docker.sh` on the already pinned runner image, so no extra image or download; network alias `e2e-echo`, port 8080; the runner gets `E2E_ECHO_URL` and the sidecar's IP address on the run network as `E2E_ECHO_IP`): the target of the requests the SERVER makes inside the app container (node-service's npm registry proxy, the n8n plugin). It records `{ method, path, headers, body }` of every request in @@ -126,6 +132,7 @@ e2e/scripts/run-in-docker.sh -g "sign-up through the UI" # one test b e2e/scripts/run-in-docker.sh --grep @smoke # by tag: @smoke @core @slow @npm E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --grep @quarantine E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin # SEC-R16a, SEC-R16b (R16c, R16d also need E2E_INCLUDE_QUARANTINE=1) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # D12, the Firebird sidecar tests (starts the sidecar) E2E_INCLUDE_INSERT_ALL=1 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh # everything on the default stack (not the @enterprise tests) E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh tests/security/enterprise.spec.ts # the ENTERPRISE stack, SEC-E01 to E04, E06a, E06b, E07a, E07b E2E_STACK_PROFILE=signup-disabled e2e/scripts/run-in-docker.sh tests/auth/signup-disabled.spec.ts # the stack with e-mail sign-up switched off, LC-AU20 to AU24 @@ -179,6 +186,9 @@ data; its tests are untagged. | `LOWCODER_E2E_IMAGE` | run-in-docker.sh | app image (default `...:3.0.0-e2e`; a missing default image stops the run) | | `PLAYWRIGHT_IMAGE` | run-in-docker.sh | runner image; version must equal `@playwright/test` in `package-lock.json` (1.64.0) | | `POSTGRES_IMAGE` | run-in-docker.sh | PostgreSQL sidecar image | +| `FIREBIRD_IMAGE` | run-in-docker.sh | Firebird sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | +| `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | script and config | non-empty, default stack only (any other profile stops the script): start the Firebird sidecar and include the `@node-service-sidecar` tests (D12) | +| `E2E_FIREBIRD_HOST` | set by run-in-docker.sh | the Firebird sidecar's network alias, only in a run with the flag; `firebirdConnection()` reads it | | `E2E_INCLUDE_QUARANTINE`, `E2E_INCLUDE_INSERT_ALL`, `E2E_INCLUDE_SUPERADMIN` | script and config | non-empty: include that opt-in group | | `E2E_STACK_PROFILE` | run-in-docker.sh, config | `default` (the default), `signup-disabled` (the app container gets `LOWCODER_EMAIL_SIGNUP_ENABLED=false` and the run keeps only the `@signup-disabled` tests; `E2E_INCLUDE_QUARANTINE` is the only flag that applies) or `enterprise`: the app container gets `LOWCODER_WORKSPACE_MODE=ENTERPRISE` and the run keeps only the `@enterprise` tests (`grep`); another value stops the run. On the enterprise profile `E2E_INCLUDE_QUARANTINE` opens nothing extra (no enterprise test is quarantined any more), `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` change nothing (the stack has one workspace, so the D-47 limit does not arise). A `--grep` of the command line narrows the profile's selection further; it does not replace it (measured with Playwright 1.64: enterprise profile with `--grep SEC-R01b` lists 0 tests, with `--grep SEC-E02` lists 1, with the default profile `--grep SEC-E02` lists 0) | | `E2E_INCLUDE_ENTERPRISE_TAKEOVER` | run-in-docker.sh, config | non-empty, enterprise profile only (any other profile stops the script): run SEC-E05 alone | @@ -208,9 +218,10 @@ e2e/ scripts/ run-in-docker.sh, build-e2e-image.sh, app-host.sh, echo-server.js (the HTTP echo sidecar and the mail sink) fixtures/mail/ the two mails the 3.0.0 image sent (reset, invitation), with placeholders for address, token and code fixtures/sql/init.sql PostgreSQL data: items, products, notes + fixtures/firebird/init.sql Firebird sidecar data (opt-in sidecar): FB_ITEMS, FB_NOTES fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb`, `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate), `supabase` (the form's body, and one query recording per action: `supabaseQuery.json` is listBuckets, the others are `supabaseQuery.json`: ListObjects, ReadFile, UploadData, DeleteFile, CreateSignedUrl), `dynamodb` and `s3` (the form's body, and one query recording per action because the saved query differs by action: `Query.json` is the editor's default action, the others are `Query.json`, loaded by `recordedPluginQuery(id, "")`: `dynamodb` Query, ListTables, GetItem, PutItem; `s3` listBuckets, ListObjects, ReadFile, UploadData, DeleteFile) + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb`, `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate), `firebird` (the form's body with the sidecar's own host, port, database path and throw-away login, because the host cannot be a placeholder, and the editor's saved query; recorded in a session on a stack with the sidecar), `supabase` (the form's body, and one query recording per action: `supabaseQuery.json` is listBuckets, the others are `supabaseQuery.json`: ListObjects, ReadFile, UploadData, DeleteFile, CreateSignedUrl), `dynamodb` and `s3` (the form's body, and one query recording per action because the saved query differs by action: `Query.json` is the editor's default action, the others are `Query.json`, loaded by `recordedPluginQuery(id, "")`: `dynamodb` Query, ListTables, GetItem, PutItem; `s3` listBuckets, ListObjects, ReadFile, UploadData, DeleteFile) src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -256,15 +267,16 @@ Test titles carry these ids. - D9 the Open API wrapper plugins of node-service with a server URL (Lowcoder API, OpenAI, APITemplate.io, Carbone, UiPath) against the echo sidecar: one read-only operation each reaches the server URL with its credentials and answers the canned data (Carbone `get_status` sends no token: observation), every Lowcoder spec version, an OpenAI chat completion posts its JSON body, OpenAI on spec version v1.0 sends no key (NSD-7 candidate), an error status answered as success (NSD-4 candidate), UiPath fails every query and its query configuration request (HTTP 500) and sends nothing (NSD-6 candidate; its desired behaviour is quarantined), concurrent queries against two server URLs each reach their own server (`@node-service`). - D10 the DynamoDB and S3 plugins of node-service (AWS SDK v3) against the echo sidecar: a DynamoDB call is a signed JSON POST to `/ddb/` (`x-amz-target`, credential scope with the access key and region, the secret never sent), GetItem, PutItem and Query wrap the request's values and unwrap the answer's typed attributes, a service error fails the query with its message, the published view after a click; the S3 connection test lists the buckets (API and the form's Test Connection button), a refused test answers `code` 500 with the service's text (HTTP 200), a listBuckets query answers the names, every call that takes a bucket (listObjects with and without a presigned URL, readFile, uploadData, deleteFile) is path-style `/s3//` on the echo's IP address, a service error fails the query, a bucket call without a bucket sends nothing (readFile, uploadData and deleteFile show the SDK's text, NSD-8 candidate) (`@node-service`; the signed request's shape and the answer's path into the app, not the vendor service). - D11 the Supabase Storage plugin of node-service (`supabase-js`, project URL `/sb`) against the echo sidecar: every operation (listBuckets, listObjects, readFile, uploadData, deleteFile, createSignedUrl) sends its Storage API request below `/sb/storage/v1` with the key in `apikey` and `authorization` and nowhere else, a trailing slash of the project URL changes nothing, a storage error fails the query with `{"size":0,"timeout":0}` and not the API's message (NSD-9 candidate), the signed-URL validity is an epoch time in milliseconds (NSD-10 candidate), the `search` field of listObjects is not sent (NSD-11 candidate), only listObjects refuses an empty bucket (NSD-12 candidate), the published view after a click (`@node-service`; the request shape and the answer's path into the app, not Supabase). +- D12 the Firebird plugin of node-service against the opt-in Firebird sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): the connection test attaches, a wrong password and a missing database file fail it with the server's text, a named parameter answers the lower-cased row, every column type of the seeded table, parameters bound in SQL order, not object order, an unknown parameter is refused with its name, an INSERT is read back by its own owner, a SQL error is the failed query's message, the lower-case option, a failing query leaves its attachment open (NSD-13 candidate), and the runner reaches the sidecar over TCP. - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue -Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 794-test suite taken before the Supabase Storage scenarios (D11) existed, `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (794 tests; it says nothing about D11, whose evidence is the `--repeat-each=10 --workers=4` gate of `tests/datasource/plugin-supabase-storage.spec.ts` on `3.0.0-e2e` and on `3.0.1-e2e`, 210 passed on each): 44 failed, 750 passed. The baseline from a clean worktree of the previous commit (770 tests, same command and image): 43 failed, 727 passed. The failing sets are the same except `SEC-R09d`, which is intermittent on both (5 repeats: 3 failed with the current tree, 2 failed on the baseline). The 44 failures are 25 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`, and `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag and by the baseline, not analysed one by one). No node-service scenario of that run failed.): -default **816 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **830 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **821 in 114**; with both of those **835 in 115**; -with `E2E_INCLUDE_INSERT_ALL=1` **928 in 115**; with all three opt-in variables **947 in 116** (the takeover variable changes nothing on the default stack). With `E2E_STACK_PROFILE=enterprise`: +Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 827-test suite after the opt-in sidecar mechanism and the Firebird scenarios (D12) landed, `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (no variable set): 44 failed, 783 passed. It started no Firebird container (the containers seen once a second during the run were the app, the echo, PostgreSQL and the runner) and ran no D12 test (they are not in the listing). The baseline from a clean worktree of the previous commit (816 tests, same command and image): 44 failed, 772 passed. The failing sets differ by two tests, each intermittent by the evidence at hand: `SEC-R09d` failed in the baseline and not in the current run, and `logic/triggers.spec.ts` "an automatic query with periodic runs repeatedly, a manual one does not (page clock)" failed in the current run and not in the baseline (it passed 10 of 10 in a `--repeat-each=10 --workers=4` run of its own afterwards; one run each, so neither is classified further). The 44 failures of the current run are 24 `@security`, 17 `@lifecycle` and 3 others (`components/npm-components.spec.ts` calendar, `@npm`; `apps/card-menu.spec.ts` export and import, `@core`; the periodic trigger above); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag and by the baseline, not analysed one by one). No node-service scenario failed. The D12 evidence is a separate gate, `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-firebird.spec.ts`: 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e`.): +default **827 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **841 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **832 in 114**; with both of those **846 in 115**; +with `E2E_INCLUDE_INSERT_ALL=1` **939 in 115**; with all three opt-in variables **958 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **838 in 115** (the 11 D12 tests of the Firebird sidecar, which no other variable lists), and **969 in 117** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 116 in 10 files (the 25 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 122 in 10 files (the 31 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **133 in 11 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests); `@node-service-sidecar` 0 (**11 in 1 file** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -313,7 +325,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | editor/js-query.spec.ts | a JS query written in the editor runs | @core | 1 | | editor/drop-size.spec.ts | a component dropped right after ready has width above 0 (D-5) | @quarantine | 1 | -### datasource (80) +### datasource (101 default, 112 with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`) | File | Proves | Tags | Tests | |---|---|---|---| @@ -329,6 +341,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/plugin-openapi-wrappers-apps.spec.ts | D9: the Lowcoder API, OpenAI, APITemplate.io, Carbone and UiPath against the echo sidecar (server URL ``, one read-only operation of each bundled document). D9a lowcoder `GET /api/users/currentUser` with `Authorization: Bearer `, D9b OpenAI (spec version v2.3) `GET /models` with `Authorization: Bearer `, D9c apiTemplate `GET /v2/list-templates` with `x-api-key`, D9d carboneIo `GET /status` with NO credential header (observation: that operation lists no security scheme), D9e carboneIo `GET /template/` with `Authorization: Bearer ` and `carbone-version: 4`; each asserts echo empty before, exactly one request (method, full path and query, body, the complete header set) and the canned body as the query's data; D9f lowcoder: spec versions v1.0 to v1.3 send the same request; D9g OpenAI: a chat completion `POST /chat/completions` carries the JSON body, `content-type`, `content-length` and the key, and answers the canned completion; D9h OpenAI: spec version v1.0, chosen or by default, sends no `Authorization` header while v2.3 with the same key does (NSD-7 candidate); D9i apiTemplate: a canned 404 body is reported as a successful result (NSD-4 candidate); D9j uiPath: a query fails with the message `Maximum call stack size exceeded` and sends no request, after a control that another wrapper's query reaches the same echo target (NSD-6 candidate); D9k uiPath: the form's query configuration request for the UiPath document answers 500 / code 5000 `get dynamic config error`, while the identical request for apiTemplate answers success and lists its operations (NSD-6 candidate; the test asserts the failure and the control, not its cause); D9l uiPath (`@quarantine`, not counted in the default run): the folders query should reach `GET /odata/Folders` with `Bearer ` exactly and answer the canned data, fails today; D9m lowcoder, apiTemplate, carboneIo and OpenAI: 8, 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 15 (+1 `@quarantine`) | | datasource/plugin-aws-sdk.spec.ts | D10: DynamoDB and S3 against the echo sidecar (endpoints `/ddb` and `/s3`; bucket calls on the echo's IP address). Measured on 3.0.0-e2e and 3.0.1-e2e (the SDK version printed in its user agent is 3.668.0 on 3.0.0-e2e; the tests match the shape, not the version): the SDK keeps the endpoint's path, DynamoDB posts to `/ddb/`, S3 without a bucket gets `/s3/?x-id=ListBuckets`, and with a bucket on an IP-address endpoint it is path-style (`/s3//`, `Host` the IP address). Every request a D10 test makes is asserted completely: method, path and query, body, the whole header set (per-request values by shape: date, invocation id, user agents, signature), the credential scope (access key, date, region, service) and the signed-header list, and every D10 test that sends a request also asserts that the secret key is in no header, path or body of the echo's records (with a control that the access key is: it travels in the credential scope). The rows of D10q that send nothing assert that the echo holds no record, after which a control call with a bucket is asserted completely. The presigned URL of D10l is asserted by its stable query parameters and by shape, not by value. D10a DynamoDB ListTables (region `eu-central-1` in the scope, body `{TableName: "", Limit: 10}`, answer without `$metadata`), D10b GetItem wraps the key and unwraps a string, a number, a string set and a boolean, D10c PutItem wraps a number, a string and a boolean, D10d Query keeps the expression and unwraps the items, D10e a 400 `ResourceNotFoundException` fails the query (`Requested resource not found`, one request), D10f the published view after a click, D10g the connection test (`code` 1, `success`, `data` true; one `GET /s3/?x-id=ListBuckets`), D10h a 403 test answers HTTP 200 with `code` 500, `success` false and `Failed to connect data source: Access Denied.`, and the same body succeeds once the endpoint answers 200, D10i the form's Test Connection button shows that text, then `Connection Successful`, D10j listBuckets answers `[{name}]`, D10k listObjects is path-style on the IP with `delimiter`, `max-keys` and `prefix` and answers name, size, time, file URL, D10l `returnSignedUrl` adds a presigned URL (`X-Amz-Expires=300`, signed header `host`, no extra request), D10m readFile as text and base64, D10n uploadData of text and of base64 without a content type (`application/octet-stream`), D10o deleteFile, D10p a 403 and a 404 fail the query with the service's text, D10q a bucket call without a bucket sends nothing: listObjects says `Bucket is required`, readFile, uploadData and deleteFile say `Empty value provided for input HTTP label: Bucket.` (NSD-8 candidate), after a control that a call with a bucket reaches the echo. Not covered: a real DynamoDB or S3 service, the SDK's retry of a 5xx answer | @node-service | 19 | | datasource/plugin-supabase-storage.spec.ts | D11: the Supabase Storage plugin against the echo sidecar (project URL `/sb`; the Storage API is `/sb/storage/v1/...`). Measured on 3.0.0-e2e and 3.0.1-e2e (same requests and answers; supabase-js 2.45.4 in `x-client-info`, matched by shape): the client keeps the project URL's path with or without a trailing slash and derives no host name; every request carries `apikey: `, `authorization: Bearer `, the `node-fetch` user agent, `accept-encoding: gzip,deflate` and `connection: close`. Every request a D11 test makes is asserted completely (method, path and query, body, the whole header set), and every test that sends one also asserts that the key is in no header besides those two, no path or body, and no answer of the query (the whole query answer; in D11q the view's whole `q.data` as text); control: it is in those two. D11a listBuckets `GET /bucket` and the buckets as the API answered, D11b the project URL with and without a trailing slash reach the same path, D11c listObjects `POST /object/list/` with `{limit: 10, offset: 0, sortBy: {column: name, order: asc}, prefix}` and the public URL of each file in the answer, D11d limit, offset and sort order of the query, D11e the `search` field is not sent (NSD-11 candidate), D11f `returnSignedUrl` adds `POST /object/sign/` with `{expiresIn, paths}` and the signed URL in the answer, D11g readFile as text and base64 (`GET /object//`, answer `{data, type}`), D11h readFile with a transform goes to `/render/image/authenticated//?width=10`, D11i uploadData of text `POST /object//` with the text, its content type, `cache-control: max-age=3600` and `x-upsert: false`, D11j base64 without a content type sends an empty `content-type` header (observation), D11k uploadData with `returnSignedUrl` uploads then signs, D11l deleteFile `DELETE /object/` with `{prefixes: [name]}`, D11m createSignedUrl sends `expiresIn` as an integer above 1e12, an epoch time in milliseconds computed once (the second query, asserted completely too, sends the same number; the bounds allow one hour of clock skew and a plugin load up to six hours old; NSD-10 candidate, also asserted in D11f and D11k), D11n a 400, a 404 and a 401 answer fail the query with `{"size":0,"timeout":0}` instead of the answer's message, each followed by a control that the same query succeeds once the API answers 200 (NSD-9 candidate), D11o the signing and the listing fail the same way, each followed by a control that both succeed once the API answers 200 on their paths, D11p an empty bucket: listObjects says `Bucket is required` and sends nothing, readFile, uploadData, deleteFile and createSignedUrl send requests with an empty bucket segment (NSD-12 candidate), D11q the published view shows the bucket name only after the click (echo empty before, one request after). Not covered: a real Supabase project; the connection test (none is wired up for this plugin) | @node-service | 21 | +| datasource/plugin-firebird.spec.ts | D12: the Firebird plugin against the opt-in Firebird sidecar (Firebird 3.0.12, `fixtures/firebird/init.sql`; host, port, database path and login of the sidecar written over the recorded form body). Measured on 3.0.0-e2e and 3.0.1-e2e. D12a the connection test answers `code` 1, `success` true, `data` true; D12b a wrong password answers `code` 500 with `Failed to connect data source: Your user name and password are not defined. Ask your database\nadministrator to set up a Firebird login\n.` and a missing database file with the server's `I/O error for file ...` (the right fields attach first); D12c `SELECT ID, NAME FROM FB_ITEMS WHERE ID = :id` with `{"id": 2}` answers `[{id: 2, name: "beta"}]`; D12d the three seeded rows with `price` as a number and a NULL as `null`; D12e parameters bind in the order the names appear in the SQL, not the key order of the parameter object (`CAST(:first AS INTEGER) - CAST(:second AS INTEGER)` with 10 and 3 answers 7 whichever order the object lists them); D12f an unknown name fails with `Named parameter "missing" not found in Query Parameters object.` (the same SQL with the name present runs); D12g an INSERT answers `{}` and is read back by the test's own owner (the owner has no row before); D12h a syntax error and an unknown table answer the server's text; D12i `lowercaseKeys: false` answers upper-case keys; D12j a query that fails after the attach leaves its attachment open on the server, a succeeding one does not: two failing runs of a statement that tags its attachment with a per-test context variable leave exactly two tagged attachments in `MON$CONTEXT_VARIABLES`, and a succeeding tagged run does not add a third (NSD-13 candidate, `defect` annotation); D12k the runner connects to the sidecar's port 3050, and a closed port of the same host is refused. Limits: `role`, `blobAsText` and Firebird 4 and 5 are not covered; the sidecar authenticates with Legacy_Auth (see the architecture bullet) | @node-service @node-service-sidecar (opt-in) | 11 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -473,14 +486,14 @@ first makes sure some admin exists (accepting both answers), so none depends on SEC-R09d (D-38) left the quarantine: the check took the workspace of the first id of a `HashSet`; each id is now decided in its own workspace (Java unit and MongoDB integration tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)). Accounting of the earlier 3.0.0 run `E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --workers=4 --reporter=list --grep "@quarantine" tests/security` (measured before the `@superadmin` tag existed and before the reassessment, so it listed 44 tests, 19 of which have since left the quarantine): 44 listed, 43 failed, 1 passed (SEC-R09d); the two quarantined tests of `foundation/security-helpers.spec.ts` are outside that folder. -### foundation (294 default, 297 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) +### foundation (306 default, 309 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) | File | Proves | Tags | Tests | |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization` | @node-service | 25 | -| foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources) | none | 27 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization`, and the Firebird sidecar helpers: `firebirdConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the firebird recordings (form fields with the sidecar's values, one query, no session value), `fixtures/firebird/init.sql` equals `FIREBIRD_ITEMS`, the script's Firebird constants equal `FIREBIRD`, and the run script starts, waits for and passes the sidecar only inside `if node_service_sidecars_enabled` | @node-service | 31 | +| foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources), `@node-service-sidecar` (excluded by default, included by `E2E_INCLUDE_NODE_SERVICE_SIDECARS`, independent of the other flags, never selected on the enterprise and signup-disabled stacks), and the guard that every test of a spec that calls `firebirdConnection` carries `@node-service-sidecar` (same parsing; synthetic sources) | none | 32 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | | foundation/module-host.spec.ts | module created through the API works in a host; republish rules | none | 2 | @@ -531,6 +544,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-10 candidate | the Supabase Storage plugin sends the signed-URL validity as `expiresIn: Date.now() + 5 minutes` in milliseconds (13 digits, about 1.8e12 when measured), computed once when node-service loads the plugin, where the API takes seconds: every signing request of one node-service process carries the same number; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11f, D11k and D11m assert the magnitude (above 1e12, and within clock-skew and plugin-age allowances of now plus five minutes) and, in D11m, that two queries send the same value (characterisation, default run), annotation `{type:"defect", description:"NSD-10 candidate"}`; they change when the validity is 300 | | NSD-11 candidate | the `search` field of the Supabase Storage listObjects query is never sent: the request body is `{limit, offset, sortBy, prefix}` whatever the field holds; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11e asserts today's body after a positive control that the query's prefix travels (characterisation, default run), annotation `{type:"defect", description:"NSD-11 candidate"}`; it changes when the search text is sent | | NSD-12 candidate | the Supabase Storage plugin checks the bucket itself only for listObjects (`Bucket is required`); readFile, uploadData, deleteFile and createSignedUrl with an empty bucket send a request whose path has an empty bucket segment (`GET /object//x.txt`, `POST /object//x.txt`, `DELETE /object/`, `POST /object/sign//x.txt`), and the queries succeed against a server that answers; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11p asserts today's requests next to listObjects refusing the same empty bucket and sending nothing (characterisation, default run), annotation `{type:"defect", description:"NSD-12 candidate"}`; it changes when the four operations check the bucket like listObjects | +| NSD-13 candidate | the Firebird plugin never detaches a connection when its query fails after the attach (`firebirdsql/run.ts`: `detachAsync()` comes after the awaited query, and the unknown-parameter check also runs after the attach), so the attachment stays open on the server; a succeeding query detaches. Measured on 3.0.0-e2e and 3.0.1-e2e against the Firebird sidecar: after two failing runs of a statement that tags its attachment (`RDB$SET_CONTEXT`, then a division by zero) `MON$CONTEXT_VARIABLES` holds exactly 2 attachments with the tag, and a succeeding tagged run leaves it at 2. The id is provisional until the owner assigns one | `datasource/plugin-firebird.spec.ts` D12j, `defect` annotation `NSD-13 candidate`; passes today, expect it to fail once the plugin detaches in `finally` | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/fixtures/dsl/plugins/firebird/firebirdDatasource.json b/e2e/fixtures/dsl/plugins/firebird/firebirdDatasource.json new file mode 100644 index 0000000000..154c6b4554 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/firebird/firebirdDatasource.json @@ -0,0 +1,15 @@ +{ + "name": "firebird", + "type": "firebird", + "datasourceConfig": { + "host": "e2e-firebird", + "database": "/var/lib/firebird/data/e2e.fdb", + "port": 3050, + "username": "e2euser", + "password": "e2e-firebird-password", + "lowercaseKeys": true, + "blobAsText": true, + "authConfigType": "NO_AUTH", + "sslCertVerificationType": "VERIFY_CA_CERT" + } +} diff --git a/e2e/fixtures/dsl/plugins/firebird/firebirdQuery.json b/e2e/fixtures/dsl/plugins/firebird/firebirdQuery.json new file mode 100644 index 0000000000..e79fd9cf24 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/firebird/firebirdQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "firebird", + "comp": { + "actionName": "Query", + "action": { + "sql": "SELECT ID, NAME FROM FB_ITEMS WHERE ID = :id", + "params": "{\"id\": 1}" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} diff --git a/e2e/fixtures/firebird/init.sql b/e2e/fixtures/firebird/init.sql new file mode 100644 index 0000000000..f433296001 --- /dev/null +++ b/e2e/fixtures/firebird/init.sql @@ -0,0 +1,26 @@ +-- Data of the Firebird sidecar that run-in-docker.sh starts only with E2E_INCLUDE_NODE_SERVICE_SIDECARS=1. The image runs this file +-- once, with isql, when it creates the database /var/lib/firebird/data/e2e.fdb (see the FIREBIRD_* values of the script). Must equal FIREBIRD_ITEMS +-- in e2e/src/datasource/firebird.ts. + +-- Read-only rows for the query tests. No test writes them. `NOTE` is NULL on the second row. +CREATE TABLE FB_ITEMS ( + ID INTEGER NOT NULL PRIMARY KEY, + NAME VARCHAR(40) NOT NULL, + PRICE NUMERIC(9, 2) NOT NULL, + NOTE VARCHAR(40) +); +COMMIT; +INSERT INTO FB_ITEMS (ID, NAME, PRICE, NOTE) VALUES (1, 'alpha', 1.50, 'first'); +INSERT INTO FB_ITEMS (ID, NAME, PRICE, NOTE) VALUES (2, 'beta', 2.25, NULL); +INSERT INTO FB_ITEMS (ID, NAME, PRICE, NOTE) VALUES (3, 'gamma', 10.00, 'third'); +COMMIT; + +-- Rows the write tests insert. Every test writes only rows with its own OWNER value, so tests running in parallel never see each +-- other's rows. +CREATE TABLE FB_NOTES ( + ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + OWNER VARCHAR(80) NOT NULL, + BODY VARCHAR(200) NOT NULL +); +CREATE INDEX FB_NOTES_OWNER_IDX ON FB_NOTES (OWNER); +COMMIT; diff --git a/e2e/scripts/run-in-docker.sh b/e2e/scripts/run-in-docker.sh index ee4599b447..93d09115a5 100755 --- a/e2e/scripts/run-in-docker.sh +++ b/e2e/scripts/run-in-docker.sh @@ -23,6 +23,11 @@ ## tests); independent of E2E_INCLUDE_QUARANTINE. Nightly: E2E_INCLUDE_INSERT_ALL=1 $0 --grep @insert-all ## E2E_INCLUDE_SUPERADMIN set to 1 to also run the @superadmin tests (SEC-R16a to SEC-R16d, the instance super admin; ## independent of the other flags). Run: E2E_INCLUDE_SUPERADMIN=1 $0 --grep @superadmin +## E2E_INCLUDE_NODE_SERVICE_SIDECARS set to 1 to also start the sidecars of the node-service data sources whose protocol is not HTTP +## (today a Firebird server, FIREBIRD_IMAGE below) and run their @node-service-sidecar tests; independent of the +## other flags, default stack only (any other profile is an error). Without it the run starts none of them, +## neither lists nor runs those tests, and pulls no extra image. +## Run only these: E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 $0 --grep @node-service-sidecar ## E2E_STACK_PROFILE which stack to start: `default` (the all-in-one image in its SAAS workspace mode; the default) or ## `enterprise` (the same image with LOWCODER_WORKSPACE_MODE=ENTERPRISE: one workspace shared by every ## user; it runs only the @enterprise tests, SEC-E01 to SEC-E04, E06a, E06b) or `signup-disabled` (the same @@ -36,6 +41,7 @@ ## It is quarantined, so it needs E2E_INCLUDE_QUARANTINE=1 as well: ## E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_ENTERPRISE_TAKEOVER=1 E2E_STACK_PROFILE=enterprise $0 ## POSTGRES_IMAGE PostgreSQL sidecar for the data source tests (pinned by digest) +## FIREBIRD_IMAGE Firebird sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS ## E2E_HOST_PORT also publish the app on 127.0.0.1: to look at it in a browser while the run lasts ## ## Set by the script for each run (a value of the caller is overwritten; the password is new every run, never printed, @@ -64,6 +70,13 @@ ## `--add-host e2e-echo:`, not through DNS: should the sidecar die, the name still points at that ## private address and the request fails locally (refused or unreachable) instead of the name resolving on an external resolver. ## +## Only with E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 it also starts a Firebird sidecar (FIREBIRD_IMAGE, data of fixtures/firebird/init.sql) under the +## alias e2e-firebird, port 3050: the target of the Firebird data source of node-service (the plugin speaks the Firebird wire protocol over TCP, +## which the echo cannot stand in for). It starts after the echo, so the app can resolve the alias through `--add-host e2e-firebird:` like +## the echo (the same reason), and the runner gets the alias as E2E_FIREBIRD_HOST. The script waits until a SELECT of the seeded table through +## the image's own isql answers over TCP, and `cleanup` removes the container however the run ends. Its credentials are throw-away constants +## that must equal FIREBIRD in e2e/src/constants.ts. Without the flag nothing of this runs: no container, no image pull, no variable for the runner. +## ## Not covered: Firefox and WebKit (only Chromium runs), the multi-container compose setup, databases other than ## PostgreSQL. ## @@ -81,6 +94,21 @@ readonly POSTGRES_IMAGE="${POSTGRES_IMAGE:-$DEFAULT_POSTGRES_IMAGE}" readonly POSTGRES_DATABASE="shop" readonly POSTGRES_USER="postgres" readonly POSTGRES_PASSWORD="e2e-postgres-password" +# Firebird sidecar of the @node-service-sidecar tests, started only with E2E_INCLUDE_NODE_SERVICE_SIDECARS. Tag and digest of the image: +# 3.0.12 with Legacy_Auth first (below): node-firebird 1.1.9 attached 100 of 100 times; with the image's default Srp, 12 of 100 attaches failed +# with "Your user name and password are not defined" (README, "Firebird sidecar"). The values below must equal FIREBIRD in e2e/src/constants.ts; +# they are throw-away, the container dies with the run. +readonly DEFAULT_FIREBIRD_IMAGE="firebirdsql/firebird:3.0.12@sha256:e45c9bc4fdacaaddc1980a05b7bb8b297f09fe019eadefb059006efe4dafe875" +readonly FIREBIRD_IMAGE="${FIREBIRD_IMAGE:-$DEFAULT_FIREBIRD_IMAGE}" +readonly FIREBIRD_DATABASE_FILE="e2e.fdb" +readonly FIREBIRD_DATABASE_PATH="/var/lib/firebird/data/$FIREBIRD_DATABASE_FILE" +readonly FIREBIRD_USER="e2euser" +readonly FIREBIRD_PASSWORD="e2e-firebird-password" +readonly FIREBIRD_ROOT_PASSWORD="e2e-firebird-root-password" +# The image's switch for Legacy_Auth before Srp and WireCrypt `Enabled` instead of `Required` (node-firebird 1.1.9 has no wire encryption) +readonly FIREBIRD_USE_LEGACY_AUTH="true" +readonly FIREBIRD_ALIAS="e2e-firebird" +readonly FIREBIRD_PORT=3050 # The instance super admin of the throw-away stack; the domain equals TEST_EMAIL_DOMAIN in e2e/src/constants.ts; the suite # reads the name from E2E_SUPERUSER_USERNAME (SUPER_ADMIN_ENV). The password is generated per run (generate_superuser_password). readonly SUPERUSER_USERNAME="e2e-superadmin@example.test" @@ -113,6 +141,7 @@ readonly APP_CONTAINER="${NAME_PREFIX}-app" readonly POSTGRES_CONTAINER="${NAME_PREFIX}-pg" readonly RUNNER_CONTAINER="${NAME_PREFIX}-runner" readonly ECHO_CONTAINER="${NAME_PREFIX}-echo" +readonly FIREBIRD_CONTAINER="${NAME_PREFIX}-fb" # The alias and port the app container and the runner use; E2E_ECHO_URL below is built from them (the suite reads it by ECHO_ENV in e2e/src/constants.ts) readonly ECHO_ALIAS="e2e-echo" readonly ECHO_PORT=8080 @@ -122,6 +151,9 @@ readonly ECHO_HEALTH_PATH="/__e2e/health" readonly ECHO_SCRIPT="$SCRIPT_DIR/echo-server.js" # Set by start_echo: the sidecar's IP on the run network (used for --add-host of the app and the runner) ECHO_IP="" +# Set by start_firebird (only with E2E_INCLUDE_NODE_SERVICE_SIDECARS): the extra `--add-host` and `-e` arguments of the app and the runner. Empty otherwise. +SIDECAR_ADD_HOST=() +SIDECAR_RUNNER_ENV=() log() { echo "[$(date +%H:%M:%S)] $*" @@ -133,11 +165,16 @@ fail() { } cleanup() { - docker rm -f "$RUNNER_CONTAINER" "$APP_CONTAINER" "$POSTGRES_CONTAINER" "$ECHO_CONTAINER" > /dev/null 2>&1 || true + docker rm -f "$RUNNER_CONTAINER" "$APP_CONTAINER" "$POSTGRES_CONTAINER" "$ECHO_CONTAINER" "$FIREBIRD_CONTAINER" > /dev/null 2>&1 || true docker network rm "$NETWORK" > /dev/null 2>&1 || true } trap cleanup EXIT +# True when the run was asked for the node-service sidecars (the variable is set and not empty). +node_service_sidecars_enabled() { + [ -n "${E2E_INCLUDE_NODE_SERVICE_SIDECARS:-}" ] +} + check_stack_profile() { case "$STACK_PROFILE" in "$DEFAULT_PROFILE" | "$ENTERPRISE_PROFILE" | "$SIGNUP_DISABLED_PROFILE") ;; @@ -146,6 +183,9 @@ check_stack_profile() { if [ -n "${E2E_INCLUDE_ENTERPRISE_TAKEOVER:-}" ] && [ "$STACK_PROFILE" != "$ENTERPRISE_PROFILE" ]; then fail "E2E_INCLUDE_ENTERPRISE_TAKEOVER needs E2E_STACK_PROFILE=$ENTERPRISE_PROFILE" fi + if node_service_sidecars_enabled && [ "$STACK_PROFILE" != "$DEFAULT_PROFILE" ]; then + fail "E2E_INCLUDE_NODE_SERVICE_SIDECARS needs E2E_STACK_PROFILE=$DEFAULT_PROFILE (the other stacks run no @node-service-sidecar test)" + fi } # Version of @playwright/test locked in package-lock.json @@ -198,7 +238,7 @@ start_app() { profile_env=(-e "LOWCODER_EMAIL_SIGNUP_ENABLED=false") fi log "Starting $APP_IMAGE as $APP_CONTAINER (stack profile $STACK_PROFILE)" - docker run -d --name "$APP_CONTAINER" --network "$NETWORK" --network-alias "$E2E_APP_HOST" --add-host "${ECHO_ALIAS}:${ECHO_IP}" "${publish[@]}" "${profile_env[@]}" \ + docker run -d --name "$APP_CONTAINER" --network "$NETWORK" --network-alias "$E2E_APP_HOST" --add-host "${ECHO_ALIAS}:${ECHO_IP}" "${SIDECAR_ADD_HOST[@]}" "${publish[@]}" "${profile_env[@]}" \ -e LOWCODER_PUBLIC_URL="http://${E2E_APP_HOST}:${APP_PORT}/" \ -e LOWCODER_SUPERUSER_USERNAME -e LOWCODER_SUPERUSER_PASSWORD \ -e LOWCODER_ADMIN_SMTP_HOST="$ECHO_ALIAS" -e LOWCODER_ADMIN_SMTP_PORT="$MAIL_PORT" \ @@ -254,6 +294,37 @@ wait_for_echo() { log "Echo sidecar ready after ${waited}s" } +# The init script runs once, with isql, when the image creates the database; the server starts after it, so a SELECT of the seeded table over +# TCP (127.0.0.1 inside the container: not the embedded engine) means the data is there and the server answers. The image's own isql, so no +# client is needed here. +start_firebird() { + log "Starting $FIREBIRD_IMAGE as $FIREBIRD_CONTAINER (alias $FIREBIRD_ALIAS, port $FIREBIRD_PORT)" + docker run -d --name "$FIREBIRD_CONTAINER" --network "$NETWORK" --network-alias "$FIREBIRD_ALIAS" \ + -e FIREBIRD_ROOT_PASSWORD="$FIREBIRD_ROOT_PASSWORD" -e FIREBIRD_USER="$FIREBIRD_USER" -e FIREBIRD_PASSWORD="$FIREBIRD_PASSWORD" \ + -e FIREBIRD_DATABASE="$FIREBIRD_DATABASE_FILE" -e FIREBIRD_USE_LEGACY_AUTH="$FIREBIRD_USE_LEGACY_AUTH" \ + -v "$E2E_DIR/fixtures/firebird":/docker-entrypoint-initdb.d:ro \ + "$FIREBIRD_IMAGE" > /dev/null + local firebird_ip + firebird_ip="$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$FIREBIRD_CONTAINER")" + [ -n "$firebird_ip" ] || fail "no IP address for $FIREBIRD_CONTAINER on $NETWORK" + SIDECAR_ADD_HOST=(--add-host "${FIREBIRD_ALIAS}:${firebird_ip}") + SIDECAR_RUNNER_ENV=(-e "E2E_FIREBIRD_HOST=${FIREBIRD_ALIAS}") + log "Firebird sidecar is $FIREBIRD_ALIAS = $firebird_ip" +} + +wait_for_firebird() { + local waited=0 + until echo "SELECT COUNT(*) FROM FB_ITEMS;" | docker exec -i "$FIREBIRD_CONTAINER" /opt/firebird/bin/isql -b -user "$FIREBIRD_USER" -password "$FIREBIRD_PASSWORD" "127.0.0.1:${FIREBIRD_DATABASE_PATH}" > /dev/null 2>&1; do + if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then + docker logs --tail "$LOG_TAIL_LINES" "$FIREBIRD_CONTAINER" >&2 || true + fail "the Firebird sidecar did not become ready within ${STARTUP_TIMEOUT}s" + fi + sleep "$POLL_INTERVAL" + waited=$((waited + POLL_INTERVAL)) + done + log "Firebird sidecar ready after ${waited}s" +} + wait_for_app() { local waited=0 log "Waiting for $READY_PATH (at most ${STARTUP_TIMEOUT}s)" @@ -276,7 +347,7 @@ run_tests() { log "Running Playwright from $PLAYWRIGHT_IMAGE" local status=0 # --init and --ipc=host: recommended by Playwright for Chromium in Docker (https://playwright.dev/docs/docker) - docker run --rm --name "$RUNNER_CONTAINER" --network "$NETWORK" --add-host "${ECHO_ALIAS}:${ECHO_IP}" --init --ipc=host \ + docker run --rm --name "$RUNNER_CONTAINER" --network "$NETWORK" --add-host "${ECHO_ALIAS}:${ECHO_IP}" "${SIDECAR_ADD_HOST[@]}" --init --ipc=host \ --user "$(id -u):$(id -g)" -e HOME=/tmp \ -e CI="${CI:-}" \ -e LOWCODER_BASE_URL="http://${E2E_APP_HOST}:${APP_PORT}" \ @@ -287,6 +358,8 @@ run_tests() { -e E2E_INCLUDE_INSERT_ALL="${E2E_INCLUDE_INSERT_ALL:-}" \ -e E2E_INCLUDE_SUPERADMIN="${E2E_INCLUDE_SUPERADMIN:-}" \ -e E2E_INCLUDE_ENTERPRISE_TAKEOVER="${E2E_INCLUDE_ENTERPRISE_TAKEOVER:-}" \ + -e E2E_INCLUDE_NODE_SERVICE_SIDECARS="${E2E_INCLUDE_NODE_SERVICE_SIDECARS:-}" \ + "${SIDECAR_RUNNER_ENV[@]}" \ -e E2E_STACK_PROFILE="$STACK_PROFILE" \ -e E2E_SUPERUSER_USERNAME -e E2E_SUPERUSER_PASSWORD \ -v "$E2E_DIR":/work -w /work \ @@ -309,8 +382,14 @@ generate_superuser_password docker network create "$NETWORK" > /dev/null start_postgres start_echo +if node_service_sidecars_enabled; then + start_firebird +fi start_app wait_for_postgres wait_for_echo +if node_service_sidecars_enabled; then + wait_for_firebird +fi wait_for_app run_tests "$@" diff --git a/e2e/src/constants.ts b/e2e/src/constants.ts index 65d70706a1..bc281a74eb 100644 --- a/e2e/src/constants.ts +++ b/e2e/src/constants.ts @@ -219,6 +219,13 @@ export const TAGS = { * (`--grep @node-service`), not an opt-in one: these tests stay in the default run. */ NODE_SERVICE: "@node-service", + /** + * The node-service data source tests that need a sidecar of their own because the plugin's protocol is not HTTP (today the + * Firebird tests, `tests/datasource/plugin-firebird.spec.ts`). Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of + * the default run (neither listed nor run, and the run script starts no such sidecar), in only with + * `E2E_INCLUDE_NODE_SERVICE_SIDECARS` (see src/run-selection.ts and scripts/run-in-docker.sh). + */ + NODE_SERVICE_SIDECAR: "@node-service-sidecar", } as const; /** Environment variables that widen the run beyond the default selection (read by playwright.config.ts). */ @@ -228,6 +235,11 @@ export const RUN_FLAGS = { INCLUDE_SUPERADMIN: "E2E_INCLUDE_SUPERADMIN", /** Enterprise profile only: run SEC-E05 (`@enterprise-takeover`) and nothing else. */ INCLUDE_ENTERPRISE_TAKEOVER: "E2E_INCLUDE_ENTERPRISE_TAKEOVER", + /** + * Default stack only: also start the sidecars of the node-service data sources whose protocol is not HTTP (Firebird) and run + * their `@node-service-sidecar` tests. Without it the run starts none of them. + */ + INCLUDE_NODE_SERVICE_SIDECARS: "E2E_INCLUDE_NODE_SERVICE_SIDECARS", } as const; /** Environment variable that picks the stack a run is made for; `run-in-docker.sh` sets it for the runner (read by playwright.config.ts). */ @@ -280,6 +292,21 @@ export const POSTGRES = { PASSWORD: "e2e-postgres-password", } as const; +/** + * The Firebird sidecar that scripts/run-in-docker.sh starts on the run's network ONLY when `E2E_INCLUDE_NODE_SERVICE_SIDECARS` is set + * (see fixtures/firebird/init.sql). The run script passes the host name (the sidecar's network alias); the rest is fixed there and must + * equal the `FIREBIRD_*` values of the script. The user and the password are the throw-away ones of the sidecar (the container is removed + * when the run ends and nothing else uses them): never real secrets. + */ +export const FIREBIRD = { + HOST_ENV: "E2E_FIREBIRD_HOST", + PORT: 3050, + /** The database file inside the sidecar: the image's data directory plus `FIREBIRD_DATABASE` of the script. */ + DATABASE: "/var/lib/firebird/data/e2e.fdb", + USERNAME: "e2euser", + PASSWORD: "e2e-firebird-password", +} as const; + export const SEEDED_ITEM_NAMES = ["alpha", "beta"] as const; /** Component type, panel search text, drop position and generated name of the button the editor tests drop. */ diff --git a/e2e/src/datasource/firebird.ts b/e2e/src/datasource/firebird.ts new file mode 100644 index 0000000000..360e000c2c --- /dev/null +++ b/e2e/src/datasource/firebird.ts @@ -0,0 +1,46 @@ +import { FIREBIRD, RUN_FLAGS } from "../constants"; + +/** Where a Firebird data source connects: the sidecar of the run, as the app container reaches it (by the sidecar's network alias). */ +export interface FirebirdConnection { + host: string; + port: number; + database: string; + username: string; + password: string; +} + +/** The sidecar's host variable is not set: the run did not start the Firebird sidecar. */ +export class FirebirdSidecarMissingError extends Error { + constructor() { + super( + `${FIREBIRD.HOST_ENV} is not set: the Firebird sidecar was not started. Run the suite through e2e/scripts/run-in-docker.sh with ${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}=1.`, + ); + this.name = "FirebirdSidecarMissingError"; + } +} + +/** + * The connection to the run's Firebird sidecar from the environment. Throws `FirebirdSidecarMissingError` when the run script did not + * set the host variable (it does so only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`), so a test that was selected without its sidecar + * fails loudly instead of passing vacuously or connecting to a name that happens to resolve elsewhere. Reads only `env`. + */ +export function firebirdConnection(env: NodeJS.ProcessEnv = process.env): FirebirdConnection { + const host = env[FIREBIRD.HOST_ENV]; + if (!host) throw new FirebirdSidecarMissingError(); + return { host, port: FIREBIRD.PORT, database: FIREBIRD.DATABASE, username: FIREBIRD.USERNAME, password: FIREBIRD.PASSWORD }; +} + +/** A row of `FB_ITEMS` as the plugin answers it (lower-cased keys, `NUMERIC(9,2)` as a number, a NULL as `null`). */ +export interface FirebirdItem { + id: number; + name: string; + price: number; + note: string | null; +} + +/** The rows `fixtures/firebird/init.sql` inserts into the read-only table `FB_ITEMS`, in `ID` order. Must equal that file. */ +export const FIREBIRD_ITEMS: readonly FirebirdItem[] = [ + { id: 1, name: "alpha", price: 1.5, note: "first" }, + { id: 2, name: "beta", price: 2.25, note: null }, + { id: 3, name: "gamma", price: 10, note: "third" }, +]; diff --git a/e2e/src/run-selection.ts b/e2e/src/run-selection.ts index 411a643530..dddd93a376 100644 --- a/e2e/src/run-selection.ts +++ b/e2e/src/run-selection.ts @@ -8,6 +8,11 @@ export interface RunFlags { includeInsertAll: boolean; /** Tests tagged `@superadmin` (SEC-R16a to SEC-R16d: they break a stack that holds more than ~420 workspaces, D-47). */ includeSuperAdmin: boolean; + /** + * Tests tagged `@node-service-sidecar` (the node-service data sources that need a sidecar of their own, Firebird): they need the + * run script to start that sidecar, which it does only for this flag. Default stack only: the other stacks select their own tags. + */ + includeNodeServiceSidecars: boolean; /** * Enterprise profile only: run SEC-E05 (`@enterprise-takeover`) and NOTHING else of the stack, because it replaces the * super admin's password. Ignored on the default profile (the test is `@enterprise` as well and never runs there). @@ -46,14 +51,15 @@ export function runFlagsFromEnv(env: Record): RunFla includeInsertAll: !!env[RUN_FLAGS.INCLUDE_INSERT_ALL], includeSuperAdmin: !!env[RUN_FLAGS.INCLUDE_SUPERADMIN], includeEnterpriseTakeover: !!env[RUN_FLAGS.INCLUDE_ENTERPRISE_TAKEOVER], + includeNodeServiceSidecars: !!env[RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS], stackProfile: stackProfileFromEnv(env), }; } /** - * The tags a run leaves out. Default profile: each opt-in tag unless its own flag is set (the three flags are + * The tags a run leaves out. Default profile: each opt-in tag unless its own flag is set (the four flags are * independent), and always `@enterprise`, `@enterprise-takeover` and `@signup-disabled`. Signup-disabled profile: `@quarantine` unless its flag is set. Enterprise profile: `@quarantine` unless its flag is set, - * and `@enterprise-takeover` unless ITS flag is set; the other two flags do not apply there (`@insert-all` tests are outside + * and `@enterprise-takeover` unless ITS flag is set; the other three flags (insert-all, super admin, node-service sidecars) do not apply there (`@insert-all` and `@node-service-sidecar` tests are outside * the `@enterprise` selection anyway, and the super admin of that stack is a member of ONE workspace, so the D-47 capacity * limit behind `@superadmin` does not arise: SEC-E01 to E06a and SEC-E07a, E07b use it and carry the tag for the guard of * tests/foundation/run-selection.spec.ts). @@ -72,6 +78,7 @@ export function excludedTags(flags: RunFlags): string[] { ...(flags.includeQuarantine ? [] : [TAGS.QUARANTINE]), ...(flags.includeInsertAll ? [] : [TAGS.INSERT_ALL]), ...(flags.includeSuperAdmin ? [] : [TAGS.SUPERADMIN]), + ...(flags.includeNodeServiceSidecars ? [] : [TAGS.NODE_SERVICE_SIDECAR]), TAGS.ENTERPRISE, TAGS.ENTERPRISE_TAKEOVER, TAGS.SIGNUP_DISABLED, @@ -80,7 +87,7 @@ export function excludedTags(flags: RunFlags): string[] { /** * The `grepInvert` of the Playwright config: one alternation of the excluded tags, `undefined` when nothing is left - * out. Default profile, no flag: `/@quarantine|@insert-all|@superadmin|@enterprise|@enterprise-takeover/` (the default run); + * out. Default profile, no flag: `/@quarantine|@insert-all|@superadmin|@node-service-sidecar|@enterprise|@enterprise-takeover|@signup-disabled/` (the default run); * in between, the alternation of the tags whose flag is not set, the two enterprise tags always last. Enterprise profile: * `/@quarantine|@enterprise-takeover/` by default, `/@quarantine/` with the takeover flag only, `/@enterprise-takeover/` * with the quarantine flag only. A test tagged with several opt-in tags runs only when all their flags are set (SEC-E05 carries diff --git a/e2e/tests/datasource/plugin-firebird.spec.ts b/e2e/tests/datasource/plugin-firebird.spec.ts new file mode 100644 index 0000000000..e06beba96e --- /dev/null +++ b/e2e/tests/datasource/plugin-firebird.spec.ts @@ -0,0 +1,343 @@ +import { randomBytes } from "node:crypto"; +import { connect } from "node:net"; +import type { Page } from "@playwright/test"; +import { + createApp, + createNodePluginDatasource, + executeAppQueryRaw, + nodePluginDatasourceBody, + testDatasourceRaw, + type RawAnswer, + type RegisteredUser, +} from "../../src/api/client"; +import { API_OK, FIREBIRD, NEGATIVE_EVENT_WINDOW_MS, TAGS } from "../../src/constants"; +import { appDsl, nodePluginQuery } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { FIREBIRD_ITEMS, firebirdConnection } from "../../src/datasource/firebird"; +import { expect, test } from "../../src/fixtures"; + +/** + * D12: the Firebird plugin of node-service (`server/node-service/src/plugins/firebirdsql/`, the plugin id `firebird`), run against the + * Firebird sidecar of the run (`scripts/run-in-docker.sh` starts it only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`; the data is + * `fixtures/firebird/init.sql`). The plugin speaks the Firebird wire protocol with node-firebird, so the HTTP echo cannot stand in. Every + * connection of these tests goes to the sidecar: the host of the data source is the sidecar's alias from `E2E_FIREBIRD_HOST`, never a + * placeholder. The data source reaches node-service through the normal API with the form's recorded body, the host, port, database path, + * user and password of the sidecar written over its fields. + * + * Measured on the images `3.0.0-e2e` and `3.0.1-e2e` against the sidecar (Firebird 3.0.12, Legacy_Auth first): + * - A row is an object with lower-cased keys (the form's default `lowercaseKeys: true`); `NUMERIC(9,2)` is a number, a NULL is `null`; + * an INSERT answers `{}` (the plugin's `result || {}`). + * - A named `:param` is replaced by `?` and read from the saved `params` JSON, in the order the names appear in the SQL (a name may be + * used twice). The SQL text is scanned for `:name` everywhere, string literals included. + * - A server error reaches the app as the failed query's message, the server's own text. + * + * Not covered: the data source options `role` (node-firebird 1.1.9 failed to attach when the role named one the user holds, measured + * once on the sidecar, not pursued), `blobAsText` and the connection pool; Firebird 4 and 5 (the sidecar is Firebird 3.0.12). + */ + +/** + * Candidate defect: a query that fails after the attach (a SQL error or an unknown named parameter) never detaches (`run.ts`: `detachAsync` + * comes after the awaited query and is skipped when it throws), so the attachment stays open on the server. A successful query does detach. + */ +const LEAKED_ATTACHMENT_DEFECT = { type: "defect", description: "NSD-13 candidate" } as const; + +const HTTP_OK = 200; +const CODE_CONNECT_FAILED = 500; +const QUERY_CODE_OK = "OK"; +const QUERY_CODE_FAILED = "FAILED"; +const MARKER_BYTES = 4; +const QUERY_ID = "q1"; +const FIREBIRD_PLUGIN = "firebird"; +const CONNECT_FAILED_PREFIX = "Failed to connect data source: "; + +/** The server's text for a wrong password and for a database file that does not exist (measured; the first has line breaks and a final dot). */ +const WRONG_PASSWORD_TEXT = "Your user name and password are not defined. Ask your database\nadministrator to set up a Firebird login\n"; +const MISSING_DATABASE_FILE = "/var/lib/firebird/data/e2e-missing.fdb"; +const MISSING_DATABASE_TEXT = `I/O error for file "${MISSING_DATABASE_FILE}", Error while trying to open file.`; +/** + * Differs from the sidecar's password within its first eight characters on purpose: the sidecar authenticates with Legacy_Auth, which + * compares only the first eight characters of a password (measured: `e2e-firebird-wrong-password`, which shares them, attached). + */ +const WRONG_PASSWORD = "wrong-e2e-password"; + +const SELECT_ITEM_BY_ID = "SELECT ID, NAME FROM FB_ITEMS WHERE ID = :id"; +const SELECT_ALL_ITEMS = "SELECT ID, NAME, PRICE, NOTE FROM FB_ITEMS ORDER BY ID"; +/** A subtraction is not commutative: the value tells which parameter was bound to which placeholder. */ +const SELECT_DIFFERENCE = "SELECT CAST(:first AS INTEGER) - CAST(:second AS INTEGER) AS DIFF FROM RDB$DATABASE"; +const DIFFERENCE_FIRST = 10; +const DIFFERENCE_SECOND = 3; +const SELECT_UNKNOWN_PARAMETER = "SELECT ID FROM FB_ITEMS WHERE ID = :missing"; +const INSERT_NOTE = "INSERT INTO FB_NOTES (OWNER, BODY) VALUES (:owner, :body)"; +const SELECT_NOTES = "SELECT OWNER, BODY FROM FB_NOTES WHERE OWNER = :owner"; +const SYNTAX_ERROR_SQL = "SELEC 1"; +const SYNTAX_ERROR_TEXT = "Dynamic SQL Error, SQL error code = -104, Token unknown - line 1, column 1, SELEC"; +const UNKNOWN_TABLE_SQL = "SELECT * FROM FB_NO_SUCH_TABLE"; +const UNKNOWN_TABLE_TEXT = "Dynamic SQL Error, SQL error code = -204, Table unknown, FB_NO_SUCH_TABLE, At line 1, column 15"; +const UNKNOWN_PARAMETER_TEXT = 'Named parameter "missing" not found in Query Parameters object.'; + +/** A port of the sidecar's host where nothing listens: the control that a refused connection is seen as one. */ +const CLOSED_PORT = 3051; +const CONNECT_TIMEOUT_MS = 5000; + +/** + * Leaked-attachment observation. A statement that sets a context variable of the attachment (`RDB$SET_CONTEXT`, `USER_SESSION`) tagged with + * a per-test marker and then fails by dividing by zero leaves the tag in `MON$CONTEXT_VARIABLES` for as long as its attachment lives, so a + * count of the tag counts this test's open attachments only (parallel tests use other tags). The marker is hex: it is placed in the SQL text, + * since a named parameter inside an EXECUTE BLOCK would be rewritten by the plugin too. + */ +const CONTEXT_VARIABLE = "E2E_TAG"; +const LEAK_RUNS = 2; +/** The message of the failing block; the column at its end depends on the length of the tag, so it is matched as digits. */ +const DIVIDE_BY_ZERO_MESSAGE = /^Arithmetic exception, numeric overflow, or string truncation, Integer divide by zero\.The code attempted to divide an integer value by\nan integer divisor of zero\n, At block line: 1, col: \d+$/; + +function failingTaggedSql(tag: string): string { + return `EXECUTE BLOCK AS DECLARE V INTEGER; BEGIN V = 1; RDB$SET_CONTEXT('USER_SESSION', '${CONTEXT_VARIABLE}', '${tag}'); V = V / (V - 1); END`; +} + +function succeedingTaggedSql(tag: string): string { + return `EXECUTE BLOCK AS DECLARE V INTEGER; BEGIN V = 1; RDB$SET_CONTEXT('USER_SESSION', '${CONTEXT_VARIABLE}', '${tag}'); END`; +} + +const COUNT_TAGGED_SQL = `SELECT COUNT(*) AS N FROM MON$CONTEXT_VARIABLES WHERE MON$VARIABLE_NAME = '${CONTEXT_VARIABLE}' AND MON$VARIABLE_VALUE = :tag`; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +/** One saved query: its SQL and the `params` JSON text of the form's "Query Parameters" field. */ +interface FirebirdQuery { + sql: string; + params?: Record; +} + +/** The data source fields of the sidecar over the recorded form body; `overrides` change single fields (a wrong password, a lower-case switch). */ +function sidecarConfig(overrides: Record = {}): Record { + const connection = firebirdConnection(); + return { host: connection.host, port: connection.port, database: connection.database, username: connection.username, password: connection.password, ...overrides }; +} + +async function firebirdDatasource(page: Page, apiUser: RegisteredUser, overrides: Record = {}): Promise { + return createNodePluginDatasource(page.request, { orgId: apiUser.orgId, recorded: recordedPluginDatasource(FIREBIRD_PLUGIN), config: sidecarConfig(overrides) }); +} + +/** A saved app with one manual query per entry of `queries` on one data source (not published: the draft runs with `viewMode: false`). */ +async function firebirdApp(page: Page, apiUser: RegisteredUser, queries: Record, overrides: Record = {}): Promise { + const datasourceId = await firebirdDatasource(page, apiUser, overrides); + const saved = Object.entries(queries).map(([id, query]) => + nodePluginQuery({ + id, + name: id, + datasourceId, + recorded: recordedPluginQuery(FIREBIRD_PLUGIN), + action: { sql: query.sql, params: query.params === undefined ? "" : JSON.stringify(query.params) }, + }), + ); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: "e2e-firebird", dsl: appDsl([], { queries: saved }) }); + return appId; +} + +async function runDraft(page: Page, appId: string, queryId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +function expectSucceeded(answer: RawAnswer): void { + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); +} + +function expectFailed(answer: RawAnswer, message: string): void { + expectRan(answer); + expect( + { success: envelopeOf(answer).success, queryCode: envelopeOf(answer).queryCode, message: envelopeOf(answer).message, data: envelopeOf(answer).data }, + "the query failed with the measured message", + ).toEqual({ success: false, queryCode: QUERY_CODE_FAILED, message, data: null }); +} + +/** The answer of the data source's connection test for the recorded body with `overrides` over the sidecar's fields. */ +async function connectionTest(page: Page, apiUser: RegisteredUser, overrides: Record = {}): Promise { + return testDatasourceRaw(page.request, nodePluginDatasourceBody(recordedPluginDatasource(FIREBIRD_PLUGIN), { orgId: apiUser.orgId, config: sidecarConfig(overrides) })); +} + +/** How a TCP connection to `host:port` ended: `connected`, or the error code Node reports (`ECONNREFUSED`, ...). */ +async function tcpOutcome(host: string, port: number): Promise { + return new Promise((resolve) => { + const socket = connect({ host, port }); + socket.setTimeout(CONNECT_TIMEOUT_MS, () => { + socket.destroy(); + resolve("timeout"); + }); + socket.once("connect", () => { + socket.destroy(); + resolve("connected"); + }); + socket.once("error", (error: NodeJS.ErrnoException) => resolve(error.code ?? error.message)); + }); +} + +test.describe("Firebird data source against its sidecar", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { + test("D12a: the connection test attaches", async ({ page, apiUser }) => { + const answer = await connectionTest(page, apiUser); + + expect({ status: answer.status, code: answer.code }, "the test request was answered").toEqual({ status: HTTP_OK, code: API_OK }); + expect(answer.json, "the connection test answered success with data true").toEqual({ code: API_OK, message: "", data: true, success: true }); + }); + + test("D12b: a wrong password and a missing database file fail the connection test with the server's text", async ({ page, apiUser }) => { + // positive control: the same body with the right fields attaches + expect((await connectionTest(page, apiUser)).json, "positive control, the sidecar's own fields attach").toMatchObject({ success: true, data: true }); + + const wrongPassword = await connectionTest(page, apiUser, { password: WRONG_PASSWORD }); + const missingDatabase = await connectionTest(page, apiUser, { database: MISSING_DATABASE_FILE }); + + expect(wrongPassword.json, "a wrong password").toEqual({ code: CODE_CONNECT_FAILED, message: `${CONNECT_FAILED_PREFIX}${WRONG_PASSWORD_TEXT}.`, success: false }); + expect(missingDatabase.json, "a database file that does not exist").toEqual({ code: CODE_CONNECT_FAILED, message: `${CONNECT_FAILED_PREFIX}${MISSING_DATABASE_TEXT}`, success: false }); + }); + + test("D12c: a query with a named parameter answers the lower-cased row", async ({ page, apiUser }) => { + const appId = await firebirdApp(page, apiUser, { [QUERY_ID]: { sql: SELECT_ITEM_BY_ID, params: { id: 2 } } }); + + const answer = await runDraft(page, appId, QUERY_ID); + + expectSucceeded(answer); + const beta = FIREBIRD_ITEMS[1]; + expect(envelopeOf(answer).data, "the row of id 2, keys in lower case").toEqual([{ id: beta?.id, name: beta?.name }]); + }); + + test("D12d: every column type of the seeded table, in lower-cased keys, in ID order", async ({ page, apiUser }) => { + const appId = await firebirdApp(page, apiUser, { [QUERY_ID]: { sql: SELECT_ALL_ITEMS } }); + + const answer = await runDraft(page, appId, QUERY_ID); + + expectSucceeded(answer); + expect(envelopeOf(answer).data, "the three seeded rows: NUMERIC as a number, a NULL as null").toEqual(FIREBIRD_ITEMS); + }); + + test("D12e: parameters are bound in the order the names appear in the SQL, not the order of the parameter object", async ({ page, apiUser }) => { + // `first` is named before `second` in the SQL; one query lists them in that order, the other in the opposite order + const appId = await firebirdApp(page, apiUser, { + sqlOrder: { sql: SELECT_DIFFERENCE, params: { first: DIFFERENCE_FIRST, second: DIFFERENCE_SECOND } }, + oppositeOrder: { sql: SELECT_DIFFERENCE, params: { second: DIFFERENCE_SECOND, first: DIFFERENCE_FIRST } }, + }); + + const sqlOrder = await runDraft(page, appId, "sqlOrder"); + const oppositeOrder = await runDraft(page, appId, "oppositeOrder"); + + expectSucceeded(sqlOrder); + expectSucceeded(oppositeOrder); + // 10 - 3 = 7; a binder that took the object's key order would answer 3 - 10 = -7 for the second query + expect(envelopeOf(sqlOrder).data, "parameters listed in SQL order").toEqual([{ diff: DIFFERENCE_FIRST - DIFFERENCE_SECOND }]); + expect(envelopeOf(oppositeOrder).data, "parameters listed in the opposite order give the same value").toEqual([{ diff: DIFFERENCE_FIRST - DIFFERENCE_SECOND }]); + }); + + test("D12f: an unknown named parameter is refused with its name", async ({ page, apiUser }) => { + const appId = await firebirdApp(page, apiUser, { + refused: { sql: SELECT_UNKNOWN_PARAMETER, params: { id: 2 } }, + control: { sql: SELECT_UNKNOWN_PARAMETER, params: { missing: 2 } }, + }); + + const control = await runDraft(page, appId, "control"); + const refused = await runDraft(page, appId, "refused"); + + expectSucceeded(control); + expect(envelopeOf(control).data, "positive control: the same SQL with the name present runs").toEqual([{ id: 2 }]); + expectFailed(refused, UNKNOWN_PARAMETER_TEXT); + }); + + test("D12g: an INSERT is read back by the test's own owner", async ({ page, apiUser }) => { + const owner = `e2e-owner-${uniqueMarker()}`; + const body = `e2e-body-${uniqueMarker()}`; + const appId = await firebirdApp(page, apiUser, { + insert: { sql: INSERT_NOTE, params: { owner, body } }, + read: { sql: SELECT_NOTES, params: { owner } }, + }); + + const before = await runDraft(page, appId, "read"); + const inserted = await runDraft(page, appId, "insert"); + const after = await runDraft(page, appId, "read"); + + expectSucceeded(before); + expect(envelopeOf(before).data, "before the insert the owner has no row").toEqual([]); + expectSucceeded(inserted); + expect(envelopeOf(inserted).data, "an INSERT answers an empty object").toEqual({}); + expectSucceeded(after); + expect(envelopeOf(after).data, "after the insert the owner has exactly its row").toEqual([{ owner, body }]); + }); + + test("D12h: a SQL error is the failed query's message", async ({ page, apiUser }) => { + const appId = await firebirdApp(page, apiUser, { + syntax: { sql: SYNTAX_ERROR_SQL }, + table: { sql: UNKNOWN_TABLE_SQL }, + control: { sql: SELECT_ALL_ITEMS }, + }); + + expectSucceeded(await runDraft(page, appId, "control")); + expectFailed(await runDraft(page, appId, "syntax"), SYNTAX_ERROR_TEXT); + expectFailed(await runDraft(page, appId, "table"), UNKNOWN_TABLE_TEXT); + }); + + test("D12i: without the lower-case option the columns keep the server's upper case", async ({ page, apiUser }) => { + const lower = await firebirdApp(page, apiUser, { [QUERY_ID]: { sql: SELECT_ITEM_BY_ID, params: { id: 1 } } }); + const upper = await firebirdApp(page, apiUser, { [QUERY_ID]: { sql: SELECT_ITEM_BY_ID, params: { id: 1 } } }, { lowercaseKeys: false }); + + const lowerAnswer = await runDraft(page, lower, QUERY_ID); + const upperAnswer = await runDraft(page, upper, QUERY_ID); + + const alpha = FIREBIRD_ITEMS[0]; + expectSucceeded(lowerAnswer); + expect(envelopeOf(lowerAnswer).data, "positive control: the form's default lower-cases").toEqual([{ id: alpha?.id, name: alpha?.name }]); + expectSucceeded(upperAnswer); + expect(envelopeOf(upperAnswer).data, "lowercaseKeys false").toEqual([{ ID: alpha?.id, NAME: alpha?.name }]); + }); + + test("D12j: a failing query leaves its attachment open, a succeeding one does not", { annotation: LEAKED_ATTACHMENT_DEFECT }, async ({ page, apiUser }) => { + const tag = uniqueMarker(); + const appId = await firebirdApp(page, apiUser, { + failing: { sql: failingTaggedSql(tag) }, + succeeding: { sql: succeedingTaggedSql(tag) }, + count: { sql: COUNT_TAGGED_SQL, params: { tag } }, + }); + const openAttachments = async (): Promise => { + const answer = await runDraft(page, appId, "count"); + expectSucceeded(answer); + return envelopeOf(answer).data; + }; + + expect(await openAttachments(), "before any run no attachment carries the tag").toEqual([{ n: 0 }]); + for (let run = 0; run < LEAK_RUNS; run += 1) { + const failing = await runDraft(page, appId, "failing"); + expectRan(failing); + expect({ success: envelopeOf(failing).success, queryCode: envelopeOf(failing).queryCode, data: envelopeOf(failing).data }, "the tagged block failed").toEqual({ success: false, queryCode: QUERY_CODE_FAILED, data: null }); + expect(envelopeOf(failing).message, "the division by zero").toMatch(DIVIDE_BY_ZERO_MESSAGE); + } + // the observation sees live attachments: one per failing run + await expect.poll(openAttachments, { message: "the failing runs' attachments are open" }).toEqual([{ n: LEAK_RUNS }]); + + expectSucceeded(await runDraft(page, appId, "succeeding")); + await page.waitForTimeout(NEGATIVE_EVENT_WINDOW_MS); + expect(await openAttachments(), "the succeeding run's attachment is not among the open ones (the count stays at the failing runs')").toEqual([{ n: LEAK_RUNS }]); + }); + + test("D12k: the runner reaches the sidecar over TCP, and a closed port of the same host is refused", async () => { + const connection = firebirdConnection(); + + expect(await tcpOutcome(connection.host, FIREBIRD.PORT), "the sidecar's Firebird port").toBe("connected"); + expect(await tcpOutcome(connection.host, CLOSED_PORT), "positive control: a port nothing listens on is refused").toBe("ECONNREFUSED"); + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index 63807d7bf5..9beeb47fbd 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -4,7 +4,7 @@ import type { AddressInfo } from "node:net"; import { join } from "node:path"; import { expect, test } from "@playwright/test"; import { createNodePluginDatasource, LowcoderApiError, nodePluginDatasourceBody, pluginDynamicConfigRaw, testDatasourceRaw } from "../../src/api/client"; -import { API_OK, API_PATHS, orgDatasourceTypesPath, TAGS } from "../../src/constants"; +import { API_OK, API_PATHS, FIREBIRD, orgDatasourceTypesPath, RUN_FLAGS, TAGS } from "../../src/constants"; import { nodePluginQuery } from "../../src/dsl/builders"; import { parsePluginRecording, @@ -15,6 +15,7 @@ import { type RecordedPluginDatasource, type RecordedPluginQuery, } from "../../src/dsl/recorded"; +import { FIREBIRD_ITEMS, firebirdConnection, FirebirdSidecarMissingError } from "../../src/datasource/firebird"; import { NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL, NODE_PLUGIN_IDS, @@ -581,3 +582,110 @@ test.describe("node-service data source request helpers", { tag: [TAGS.NODE_SERV } }); }); + +/** The alias the run script gives the Firebird sidecar, the host of the recorded form body. */ +const FIREBIRD_ALIAS = "e2e-firebird"; + +/** The text of `scripts/run-in-docker.sh` and of `fixtures/firebird/init.sql`. */ +const RUN_SCRIPT = readFileSync(join(__dirname, "..", "..", "scripts", "run-in-docker.sh"), "utf8"); +const FIREBIRD_INIT_SQL = readFileSync(join(__dirname, "..", "..", "fixtures", "firebird", "init.sql"), "utf8"); + +/** The value of `readonly NAME="value"` in the run script. */ +function scriptConstant(name: string): string | undefined { + return new RegExp(`^readonly ${name}="([^"]*)"$`, "m").exec(RUN_SCRIPT)?.[1]; +} + +/** The lines of `RUN_SCRIPT` that call `fn` as a command (not its definition, not a comment). */ +function callLinesOf(fn: string): string[] { + return RUN_SCRIPT.split("\n").filter((line) => line.trim() === fn); +} + +test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () => { + test("firebirdConnection reads the host from the environment and takes the rest from FIREBIRD", () => { + expect(firebirdConnection({ [FIREBIRD.HOST_ENV]: FIREBIRD_ALIAS })).toEqual({ + host: FIREBIRD_ALIAS, + port: FIREBIRD.PORT, + database: FIREBIRD.DATABASE, + username: FIREBIRD.USERNAME, + password: FIREBIRD.PASSWORD, + }); + }); + + test("firebirdConnection throws a named error that names the variable and the flag when the host is unset or empty", () => { + for (const env of [{}, { [FIREBIRD.HOST_ENV]: "" }]) { + expect(() => firebirdConnection(env), `env ${JSON.stringify(env)}`).toThrow(FirebirdSidecarMissingError); + expect(() => firebirdConnection(env)).toThrow(FIREBIRD.HOST_ENV); + expect(() => firebirdConnection(env)).toThrow(`${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}=1`); + } + }); + + test("the firebird recordings are the form's body and the editor's saved query, with no value of the recording session", () => { + const datasource = recordedPluginDatasource("firebird"); + expect(datasource.type, "the data source type").toBe("firebird"); + expect(Object.keys(datasource), "no workspace id").toEqual(["name", "type", "datasourceConfig"]); + expect(datasource.datasourceConfig, "the form's fields with the sidecar's own values (the host cannot be a placeholder)").toEqual({ + host: FIREBIRD_ALIAS, + database: FIREBIRD.DATABASE, + port: FIREBIRD.PORT, + username: FIREBIRD.USERNAME, + password: FIREBIRD.PASSWORD, + lowercaseKeys: true, + blobAsText: true, + authConfigType: "NO_AUTH", + sslCertVerificationType: "VERIFY_CA_CERT", + }); + const query = recordedPluginQuery("firebird"); + expect(query.compType, "the query type").toBe("firebird"); + expect(query.comp.actionName, "the plugin's one action").toBe("Query"); + expect(Object.keys(query), "only what the builder keeps").toEqual(["compType", "comp"]); + expect(Object.keys(query.comp.action), "the form's two fields").toEqual(["sql", "params"]); + expect(query.comp.headers, "the editor's empty header row").toEqual([{ key: "", value: "" }]); + const text = ["firebirdDatasource.json", "firebirdQuery.json"].map((file) => readFileSync(join(RECORDED_PLUGINS_DIR, "firebird", file), "utf8")).join("\n"); + expect(text, "a 24-hex id").not.toMatch(/\b[0-9a-f]{24}\b/); + expect(text, "an epoch of 10 digits or more").not.toMatch(/\b\d{10,}\b/); + }); + + test("fixtures/firebird/init.sql inserts exactly the rows of FIREBIRD_ITEMS", () => { + const rows = [...FIREBIRD_INIT_SQL.matchAll(/INSERT INTO FB_ITEMS \(ID, NAME, PRICE, NOTE\) VALUES \((\d+), '([^']*)', ([\d.]+), (NULL|'[^']*')\);/g)].map((match) => ({ + id: Number(match[1]), + name: match[2], + price: Number(match[3]), + note: match[4] === "NULL" ? null : (match[4] as string).slice(1, -1), + })); + expect(rows).toEqual(FIREBIRD_ITEMS); + expect(FIREBIRD_INIT_SQL, "the owner-scoped write table the tests insert into").toContain("CREATE TABLE FB_NOTES"); + }); + + test("the run script's Firebird values equal FIREBIRD in the constants", () => { + expect(scriptConstant("FIREBIRD_USER"), "user").toBe(FIREBIRD.USERNAME); + expect(scriptConstant("FIREBIRD_PASSWORD"), "password").toBe(FIREBIRD.PASSWORD); + expect(scriptConstant("FIREBIRD_ALIAS"), "alias").toBe(FIREBIRD_ALIAS); + expect(Number(RUN_SCRIPT.match(/^readonly FIREBIRD_PORT=(\d+)$/m)?.[1]), "port").toBe(FIREBIRD.PORT); + expect(scriptConstant("FIREBIRD_DATABASE_PATH"), "database path is the image's data directory plus the file").toBe("/var/lib/firebird/data/$FIREBIRD_DATABASE_FILE"); + expect(`/var/lib/firebird/data/${scriptConstant("FIREBIRD_DATABASE_FILE")}`, "database file").toBe(FIREBIRD.DATABASE); + expect(scriptConstant("DEFAULT_FIREBIRD_IMAGE"), "the image is pinned by tag and digest").toMatch(/^firebirdsql\/firebird:\d+\.\d+\.\d+@sha256:[0-9a-f]{64}$/); + }); + + test("the run script starts, waits for and passes the Firebird sidecar only under the flag", () => { + const lines = RUN_SCRIPT.split("\n"); + const guardOpen = (line: string): boolean => line.trim() === "if node_service_sidecars_enabled; then"; + for (const fn of ["start_firebird", "wait_for_firebird"]) { + const calls = lines.map((line, index) => ({ line, index })).filter(({ line }) => line.trim() === fn); + expect(calls, `${fn} is called exactly once`).toHaveLength(1); + const call = calls[0] as { index: number }; + expect(guardOpen(lines[call.index - 1] as string), `${fn} is the first line of an if node_service_sidecars_enabled block`).toBe(true); + expect(lines[call.index + 1]?.trim(), `${fn} is the only line of that block`).toBe("fi"); + } + expect(callLinesOf("node_service_sidecars_enabled"), "the guard is a function, never a bare call").toEqual([]); + expect(RUN_SCRIPT, "the guard reads the flag, set and not empty").toContain(`[ -n "\${${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}:-}" ]`); + expect(RUN_SCRIPT, "the flag goes to the runner").toContain(`-e ${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}="\${${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}:-}"`); + // the host variable and the --add-host entries are set only inside start_firebird, so a run without the flag passes neither + const startBody = /start_firebird\(\) \{[\s\S]*?\n\}/.exec(RUN_SCRIPT)?.[0] ?? ""; + expect(startBody, "start_firebird sets the runner's host variable").toContain(`SIDECAR_RUNNER_ENV=(-e "${FIREBIRD.HOST_ENV}=`); + expect(startBody, "start_firebird sets the --add-host entry").toContain("SIDECAR_ADD_HOST=(--add-host"); + const codeLines = lines.filter((line) => !line.trim().startsWith("#")).join("\n"); + expect(codeLines.match(new RegExp(FIREBIRD.HOST_ENV, "g")), "the host variable is named once in the script's code, in start_firebird").toHaveLength(1); + expect(RUN_SCRIPT, "the cleanup trap removes the container").toMatch(/docker rm -f [^\n]*"\$FIREBIRD_CONTAINER"/); + expect(RUN_SCRIPT, "another stack profile with the flag is refused").toContain("E2E_INCLUDE_NODE_SERVICE_SIDECARS needs E2E_STACK_PROFILE=$DEFAULT_PROFILE"); + }); +}); diff --git a/e2e/tests/foundation/run-selection.spec.ts b/e2e/tests/foundation/run-selection.spec.ts index e1885b697a..6e07609f94 100644 --- a/e2e/tests/foundation/run-selection.spec.ts +++ b/e2e/tests/foundation/run-selection.spec.ts @@ -26,6 +26,8 @@ const TITLE_ENTERPRISE = `an enterprise test ${TAGS.SECURITY} ${TAGS.ENTERPRISE} const TITLE_ENTERPRISE_SUPERADMIN = `an enterprise test that uses the super admin ${TAGS.SECURITY} ${TAGS.SUPERADMIN} ${TAGS.ENTERPRISE}`; const TITLE_SIGNUP_DISABLED = `a sign-up test ${TAGS.LIFECYCLE} ${TAGS.SIGNUP_DISABLED}`; const TITLE_SIGNUP_DISABLED_QUARANTINE = `a sign-up test that is also quarantined ${TAGS.LIFECYCLE} ${TAGS.QUARANTINE} ${TAGS.SIGNUP_DISABLED}`; +/** A node-service data source test that needs its sidecar (`@node-service` next to `@node-service-sidecar`). */ +const TITLE_SIDECAR = `a sidecar test ${TAGS.NODE_SERVICE} ${TAGS.NODE_SERVICE_SIDECAR}`; /** SEC-E05: quarantined, enterprise and takeover (the real test carries @superadmin too, which no combination reads on the enterprise profile). */ const TITLE_TAKEOVER = `the takeover test ${TAGS.SECURITY} ${TAGS.QUARANTINE} ${TAGS.ENTERPRISE} ${TAGS.ENTERPRISE_TAKEOVER} ${TAGS.SUPERADMIN}`; const ALL_TITLES = [ @@ -41,6 +43,7 @@ const ALL_TITLES = [ TITLE_TAKEOVER, TITLE_SIGNUP_DISABLED, TITLE_SIGNUP_DISABLED_QUARANTINE, + TITLE_SIDECAR, ]; const DEFAULT_ONLY_TITLES = [TITLE_PLAIN, TITLE_NPM, TITLE_QUARANTINE, TITLE_INSERT_ALL, TITLE_BOTH, TITLE_SUPERADMIN, TITLE_SUPERADMIN_QUARANTINE]; @@ -54,6 +57,7 @@ function flagsOf(overrides: Partial = {}): RunFlags { includeQuarantine: false, includeInsertAll: false, includeSuperAdmin: false, + includeNodeServiceSidecars: false, includeEnterpriseTakeover: false, stackProfile: DEFAULT_STACK, ...overrides, @@ -75,42 +79,42 @@ const COMBINATIONS: Combination[] = [ { description: "neither flag (the default run)", flags: flagsOf(), - expectedSource: "@quarantine|@insert-all|@superadmin|@enterprise|@enterprise-takeover|@signup-disabled", + expectedSource: "@quarantine|@insert-all|@superadmin|@node-service-sidecar|@enterprise|@enterprise-takeover|@signup-disabled", expectedGrepSource: undefined, kept: [TITLE_PLAIN, TITLE_NPM], }, { description: "only E2E_INCLUDE_QUARANTINE (the quarantined tests without the 112 S1 tests)", flags: flagsOf({ includeQuarantine: true }), - expectedSource: "@insert-all|@superadmin|@enterprise|@enterprise-takeover|@signup-disabled", + expectedSource: "@insert-all|@superadmin|@node-service-sidecar|@enterprise|@enterprise-takeover|@signup-disabled", expectedGrepSource: undefined, kept: [TITLE_PLAIN, TITLE_NPM, TITLE_QUARANTINE], }, { description: "only E2E_INCLUDE_INSERT_ALL (S1 without the quarantined tests)", flags: flagsOf({ includeInsertAll: true }), - expectedSource: "@quarantine|@superadmin|@enterprise|@enterprise-takeover|@signup-disabled", + expectedSource: "@quarantine|@superadmin|@node-service-sidecar|@enterprise|@enterprise-takeover|@signup-disabled", expectedGrepSource: undefined, kept: [TITLE_PLAIN, TITLE_NPM, TITLE_INSERT_ALL], }, { description: "only E2E_INCLUDE_SUPERADMIN (the super admin tests that are not quarantined)", flags: flagsOf({ includeSuperAdmin: true }), - expectedSource: "@quarantine|@insert-all|@enterprise|@enterprise-takeover|@signup-disabled", + expectedSource: "@quarantine|@insert-all|@node-service-sidecar|@enterprise|@enterprise-takeover|@signup-disabled", expectedGrepSource: undefined, kept: [TITLE_PLAIN, TITLE_NPM, TITLE_SUPERADMIN], }, { description: "E2E_INCLUDE_SUPERADMIN and E2E_INCLUDE_QUARANTINE (all four SEC-R16 tests)", flags: flagsOf({ includeQuarantine: true, includeSuperAdmin: true }), - expectedSource: "@insert-all|@enterprise|@enterprise-takeover|@signup-disabled", + expectedSource: "@insert-all|@node-service-sidecar|@enterprise|@enterprise-takeover|@signup-disabled", expectedGrepSource: undefined, kept: [TITLE_PLAIN, TITLE_NPM, TITLE_QUARANTINE, TITLE_SUPERADMIN, TITLE_SUPERADMIN_QUARANTINE], }, { description: "all flags on the default stack, the takeover flag included (everything except the enterprise tests)", flags: flagsOf({ includeQuarantine: true, includeInsertAll: true, includeSuperAdmin: true, includeEnterpriseTakeover: true }), - expectedSource: "@enterprise|@enterprise-takeover|@signup-disabled", + expectedSource: "@node-service-sidecar|@enterprise|@enterprise-takeover|@signup-disabled", expectedGrepSource: undefined, kept: DEFAULT_ONLY_TITLES, }, @@ -164,7 +168,7 @@ function everyFlagCombination(stackProfile: RunFlags["stackProfile"]): RunFlags[ return bools.flatMap((includeQuarantine) => bools.flatMap((includeInsertAll) => bools.flatMap((includeSuperAdmin) => - bools.map((includeEnterpriseTakeover) => ({ includeQuarantine, includeInsertAll, includeSuperAdmin, includeEnterpriseTakeover, stackProfile })), + bools.map((includeEnterpriseTakeover) => ({ includeQuarantine, includeInsertAll, includeSuperAdmin, includeNodeServiceSidecars: false, includeEnterpriseTakeover, stackProfile })), ), ), ); @@ -229,11 +233,12 @@ test.describe("run selection: grep and grepInvert from the opt-in flags and the }); test("excludedTags lists each opt-in tag unless its own flag is set, and the enterprise tags on the default stack", () => { - expect(excludedTags(flagsOf())).toEqual([TAGS.QUARANTINE, TAGS.INSERT_ALL, TAGS.SUPERADMIN, TAGS.ENTERPRISE, TAGS.ENTERPRISE_TAKEOVER, TAGS.SIGNUP_DISABLED]); - expect(excludedTags(flagsOf({ includeQuarantine: true }))).toEqual([TAGS.INSERT_ALL, TAGS.SUPERADMIN, TAGS.ENTERPRISE, TAGS.ENTERPRISE_TAKEOVER, TAGS.SIGNUP_DISABLED]); - expect(excludedTags(flagsOf({ includeInsertAll: true }))).toEqual([TAGS.QUARANTINE, TAGS.SUPERADMIN, TAGS.ENTERPRISE, TAGS.ENTERPRISE_TAKEOVER, TAGS.SIGNUP_DISABLED]); - expect(excludedTags(flagsOf({ includeSuperAdmin: true }))).toEqual([TAGS.QUARANTINE, TAGS.INSERT_ALL, TAGS.ENTERPRISE, TAGS.ENTERPRISE_TAKEOVER, TAGS.SIGNUP_DISABLED]); + expect(excludedTags(flagsOf())).toEqual([TAGS.QUARANTINE, TAGS.INSERT_ALL, TAGS.SUPERADMIN, TAGS.NODE_SERVICE_SIDECAR, TAGS.ENTERPRISE, TAGS.ENTERPRISE_TAKEOVER, TAGS.SIGNUP_DISABLED]); + expect(excludedTags(flagsOf({ includeQuarantine: true }))).toEqual([TAGS.INSERT_ALL, TAGS.SUPERADMIN, TAGS.NODE_SERVICE_SIDECAR, TAGS.ENTERPRISE, TAGS.ENTERPRISE_TAKEOVER, TAGS.SIGNUP_DISABLED]); + expect(excludedTags(flagsOf({ includeInsertAll: true }))).toEqual([TAGS.QUARANTINE, TAGS.SUPERADMIN, TAGS.NODE_SERVICE_SIDECAR, TAGS.ENTERPRISE, TAGS.ENTERPRISE_TAKEOVER, TAGS.SIGNUP_DISABLED]); + expect(excludedTags(flagsOf({ includeSuperAdmin: true }))).toEqual([TAGS.QUARANTINE, TAGS.INSERT_ALL, TAGS.NODE_SERVICE_SIDECAR, TAGS.ENTERPRISE, TAGS.ENTERPRISE_TAKEOVER, TAGS.SIGNUP_DISABLED]); expect(excludedTags(flagsOf({ includeQuarantine: true, includeInsertAll: true, includeSuperAdmin: true, includeEnterpriseTakeover: true }))).toEqual([ + TAGS.NODE_SERVICE_SIDECAR, TAGS.ENTERPRISE, TAGS.ENTERPRISE_TAKEOVER, TAGS.SIGNUP_DISABLED, @@ -275,6 +280,7 @@ test.describe("run selection: grep and grepInvert from the opt-in flags and the [RUN_FLAGS.INCLUDE_INSERT_ALL]: "", [RUN_FLAGS.INCLUDE_SUPERADMIN]: "", [RUN_FLAGS.INCLUDE_ENTERPRISE_TAKEOVER]: "", + [RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS]: "", [STACK_PROFILE_ENV]: "", }), "the empty strings run-in-docker.sh passes when the variables are unset", @@ -283,6 +289,7 @@ test.describe("run selection: grep and grepInvert from the opt-in flags and the expect(runFlagsFromEnv({ [RUN_FLAGS.INCLUDE_INSERT_ALL]: "1" }), "insert-all only").toEqual({ ...off, includeInsertAll: true }); expect(runFlagsFromEnv({ [RUN_FLAGS.INCLUDE_SUPERADMIN]: "1" }), "super admin only").toEqual({ ...off, includeSuperAdmin: true }); expect(runFlagsFromEnv({ [RUN_FLAGS.INCLUDE_ENTERPRISE_TAKEOVER]: "1" }), "takeover only").toEqual({ ...off, includeEnterpriseTakeover: true }); + expect(runFlagsFromEnv({ [RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS]: "1" }), "node-service sidecars only").toEqual({ ...off, includeNodeServiceSidecars: true }); expect(runFlagsFromEnv({ [STACK_PROFILE_ENV]: "enterprise" }), "enterprise profile").toEqual({ ...off, stackProfile: ENTERPRISE_STACK }); expect(runFlagsFromEnv({ [STACK_PROFILE_ENV]: "default" }), "default profile named").toEqual(off); }); @@ -521,3 +528,123 @@ test.describe("run selection: the super admin tests are opt-in", () => { expect(untaggedSuperAdminTests(`test("a", async ({ page }) => {});\ntest(SYNTHETIC, async ({ superAdmin }) => {});`).map((entry) => entry.slice(0, 7)), "the report names the line of the untagged one").toEqual(["line 2:"]); }); }); + +/** Every combination of the five flags of the default stack. */ +function everyFlagCombinationWithSidecars(): RunFlags[] { + return everyFlagCombination(DEFAULT_STACK).flatMap((flags) => [false, true].map((includeNodeServiceSidecars) => ({ ...flags, includeNodeServiceSidecars }))); +} + +test.describe("run selection: the node-service sidecar tests are opt-in", () => { + test("the default selection leaves out the sidecar tag and keeps the plain node-service tests", () => { + expect(excludedTags(flagsOf()), "excluded by default").toContain(TAGS.NODE_SERVICE_SIDECAR); + expect(excludedTags(flagsOf()), "@node-service itself is a selection tag, never excluded").not.toContain(TAGS.NODE_SERVICE); + expect(keptTitles(flagsOf()), "the default run keeps no sidecar test").not.toContain(TITLE_SIDECAR); + const plainNodeServiceTitle = `a plain node-service test ${TAGS.NODE_SERVICE}`; + expect(grepInvertFor(flagsOf())?.test(plainNodeServiceTitle), "a test with only @node-service is not excluded").toBe(false); + expect(grepInvertFor(flagsOf())?.test(TITLE_SIDECAR), "the sidecar title is excluded by the inversion").toBe(true); + }); + + test("the flag includes the sidecar tests, and only the flag does", () => { + expect(excludedTags(flagsOf({ includeNodeServiceSidecars: true })), "excluded with the flag").not.toContain(TAGS.NODE_SERVICE_SIDECAR); + expect(keptTitles(flagsOf({ includeNodeServiceSidecars: true })), "the flag keeps the sidecar test").toContain(TITLE_SIDECAR); + for (const flags of everyFlagCombinationWithSidecars()) { + expect(keptTitles(flags).includes(TITLE_SIDECAR), `the sidecar test under ${JSON.stringify(flags)}`).toBe(flags.includeNodeServiceSidecars); + } + }); + + test("the flag changes nothing else on the default stack, and the other stacks never run a sidecar test", () => { + for (const flags of everyFlagCombination(DEFAULT_STACK)) { + const without = keptTitles({ ...flags, includeNodeServiceSidecars: false }); + const withFlag = keptTitles({ ...flags, includeNodeServiceSidecars: true }); + expect(withFlag, `titles kept with the flag, under ${JSON.stringify(flags)}`).toEqual([...without, TITLE_SIDECAR].sort((a, b) => ALL_TITLES.indexOf(a) - ALL_TITLES.indexOf(b))); + } + for (const stack of [ENTERPRISE_STACK, SIGNUP_DISABLED_STACK]) { + for (const flags of everyFlagCombination(stack)) { + expect(keptTitles({ ...flags, includeNodeServiceSidecars: true }), `the sidecar test on ${stack} under ${JSON.stringify(flags)}`).not.toContain(TITLE_SIDECAR); + } + } + }); +}); + +/** The name of the helper whose use makes a spec need the Firebird sidecar, and the tag every test of such a spec must wear. */ +const SIDECAR_HELPER = "firebirdConnection"; +const SIDECAR_TAG_KEY = "NODE_SERVICE_SIDECAR"; + +/** True when the expression, or any expression inside it, is `TAGS.NODE_SERVICE_SIDECAR` or the string `"@node-service-sidecar"`. Comments are no nodes. */ +function mentionsSidecarTag(node: ts.Node): boolean { + if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === TAGS_OBJECT_NAME && node.name.text === SIDECAR_TAG_KEY) return true; + if ((ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) && node.text === TAGS.NODE_SERVICE_SIDECAR) return true; + return ts.forEachChild(node, mentionsSidecarTag) ?? false; +} + +/** Whether a details argument tags the test: an object literal with a `tag` property that mentions the tag (a variable is not followed: it counts as untagged). */ +function detailsTagWithSidecar(details: ts.Expression): boolean { + return ( + ts.isObjectLiteralExpression(details) && + details.properties.some( + (property) => ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) && property.name.text === "tag" && mentionsSidecarTag(property.initializer), + ) + ); +} + +/** + * The tests of a spec source that does not wear `TAGS.NODE_SERVICE_SIDECAR`, when the source uses `firebirdConnection` (a spec that needs the + * sidecar: untagged, its tests would run in the default run, where the sidecar is not started). A source that does not use the helper + * reports nothing. A tag on an enclosing `test.describe*(title, details, body)` counts for every test inside. Each result is `line `. + * Limits: the same as `untaggedSuperAdminTests` (a `test` passed through a parameter is not recognised, a tag through a variable is not followed). + */ +function untaggedSidecarTests(source: string, fileName = "synthetic.spec.ts"): string[] { + const file = ts.createSourceFile(fileName, source, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS); + if (!source.includes(`${SIDECAR_HELPER}(`)) return []; + const untagged: string[] = []; + const testNames = localTestNames(file); + const visit = (node: ts.Node, tagged: boolean): void => { + let childrenTagged = tagged; + if (ts.isCallExpression(node)) { + const chain = callChain(node.expression); + if (chain !== undefined && testNames.has(chain[0] as string)) { + const form = chain[1]; + const args = [...node.arguments]; + const fn = args.filter((arg): arg is ts.ArrowFunction | ts.FunctionExpression => ts.isArrowFunction(arg) || ts.isFunctionExpression(arg)).at(-1); + const isDescribe = form === "describe" && chain[chain.length - 1] !== "configure"; + const isTest = chain.length === 1 || (chain.length === 2 && form !== undefined && TEST_FORMS.has(form)); + const ownTag = args.slice(1).filter((arg) => arg !== fn).some(detailsTagWithSidecar); + if (isDescribe) { + childrenTagged = tagged || ownTag; + } else if (isTest && fn && !(tagged || ownTag)) { + untagged.push(`line ${file.getLineAndCharacterOfPosition(node.getStart(file)).line + 1}`); + } + } + } + ts.forEachChild(node, (child) => visit(child, childrenTagged)); + }; + visit(file, false); + return untagged; +} + +test.describe("run selection: every test that needs the Firebird sidecar carries the opt-in tag", () => { + test("every spec that uses firebirdConnection tags all its tests with TAGS.NODE_SERVICE_SIDECAR, and the Firebird spec does use it", () => { + const untagged: string[] = []; + const users: string[] = []; + for (const file of specFilesUnder(join(__dirname, ".."))) { + const source = readFileSync(file, "utf8"); + if (file.includes(`${join("tests", "foundation")}`)) continue; + if (source.includes(`${SIDECAR_HELPER}(`)) users.push(file); + untagged.push(...untaggedSidecarTests(source, file).map((entry) => `${file}: ${entry}`)); + } + + expect(users.map((file) => file.split("tests/")[1]), "the specs that use the helper (a positive control that the guard looks at the Firebird spec)").toEqual(["datasource/plugin-firebird.spec.ts"]); + expect(untagged, "tests of a Firebird spec without TAGS.NODE_SERVICE_SIDECAR (they would run, and fail, in the default run)").toEqual([]); + }); + + test("the guard accepts a describe tag and a test tag, and reports an untagged test, a tag in a comment or a title, and a tag through a variable", () => { + const use = `const c = ${SIDECAR_HELPER}();\n`; + expect(untaggedSidecarTests(`${use}test.describe("g", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { test("a", async () => {}); });`), "describe tag").toEqual([]); + expect(untaggedSidecarTests(`${use}test("a", { tag: TAGS.NODE_SERVICE_SIDECAR }, async () => {});`), "test tag").toEqual([]); + expect(untaggedSidecarTests(`${use}test("a", async () => {});`), "untagged").toEqual(["line 2"]); + expect(untaggedSidecarTests(`${use}test.describe("g", { tag: [TAGS.NODE_SERVICE] }, () => { test("a", async () => {}); });`), "only the selection tag").toEqual(["line 2"]); + expect(untaggedSidecarTests(`${use}// TAGS.NODE_SERVICE_SIDECAR\ntest("uses @node-service-sidecar in its title", async () => {});`), "comment and title").toEqual(["line 3"]); + expect(untaggedSidecarTests(`${use}const D = { tag: [TAGS.NODE_SERVICE_SIDECAR] };\ntest("a", D, async () => {});`), "a variable is not followed").toEqual(["line 3"]); + expect(untaggedSidecarTests(`test("a", async () => {});`), "a spec that does not use the helper is not asked").toEqual([]); + }); +}); From b40740abf57f8541f80078d12b54d58917d989b4 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 21:34:06 +0100 Subject: [PATCH 15/20] test: add an opt-in libSQL server sidecar and Turso scenarios against it With E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 the run script now also starts a pinned libSQL server (sqld) next to the Firebird one, authenticated with throw-away JWTs, waits until it answers a real query, makes it reachable from the app container and the test runner, and removes it on exit even when the run fails. Without the flag nothing extra is started and the tests are neither listed nor run. Adds scenarios that run the Turso plugin against the real server: column and row mapping, raw results, INSERT answers, real server errors, a wrong, a foreign-signed and a read-only token, the published view after a click, a trailing-slash URL, and reachability from the runner. Blob cells being dropped and integers above 2^53 being rounded are characterised and annotated as defect candidates; real server errors still print as [object Object], the defect already annotated for the echo scenarios. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 12 +- e2e/README.md | 36 +- e2e/scripts/run-in-docker.sh | 64 ++- e2e/src/constants.ts | 27 +- e2e/src/datasource/libsql.ts | 66 +++ .../datasource/plugin-turso-libsql.spec.ts | 464 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 93 +++- e2e/tests/foundation/run-selection.spec.ts | 21 +- 8 files changed, 750 insertions(+), 33 deletions(-) create mode 100644 e2e/src/datasource/libsql.ts create mode 100644 e2e/tests/datasource/plugin-turso-libsql.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index 37352ca13d..39fb48cacd 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,8 +129,8 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `tests/datasource/plugin-supabase-storage.spec.ts`, D11; `tests/datasource/plugin-firebird.spec.ts`, D12, which also wears the opt-in tag of the next bullet; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. -- `@node-service-sidecar`: a node-service data source test that needs a sidecar of its own because the plugin does not speak HTTP (today Firebird, `tests/datasource/plugin-firebird.spec.ts`, D12; `TAGS.NODE_SERVICE_SIDECAR`). Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of the default run (neither listed nor run, and `run-in-docker.sh` starts no such container), in only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` (default stack only). A spec that calls `firebirdConnection()` must tag every test with it (a guard in `foundation/run-selection.spec.ts` parses the spec: write `{ tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }` on the describe or the test, not through a variable). Never put the tag text in a test title: the default `grepInvert` matches titles too and would drop the test. The helper that reads a sidecar's host variable throws when it is unset, so a test selected without its sidecar fails loudly. Later sidecars add their container under the same flag. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `tests/datasource/plugin-supabase-storage.spec.ts`, D11; `tests/datasource/plugin-firebird.spec.ts`, D12, and `tests/datasource/plugin-turso-libsql.spec.ts`, D13, which also wear the opt-in tag of the next bullet; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service-sidecar`: a node-service data source test that needs a sidecar of its own, because the plugin does not speak HTTP (Firebird, `tests/datasource/plugin-firebird.spec.ts`, D12) or because a real server adds what canned echo answers cannot (a libSQL server for the Turso plugin, `tests/datasource/plugin-turso-libsql.spec.ts`, D13); `TAGS.NODE_SERVICE_SIDECAR`. Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of the default run (neither listed nor run, and `run-in-docker.sh` starts no such container), in only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` (default stack only). A spec that calls `firebirdConnection()` or `libsqlConnection()` must tag every test with it (a guard in `foundation/run-selection.spec.ts` parses the spec: write `{ tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }` on the describe or the test, not through a variable). Never put the tag text in a test title: the default `grepInvert` matches titles too and would drop the test. The helper that reads a sidecar's host variable throws when it is unset, so a test selected without its sidecar fails loudly. Both sidecars start together under the one flag; later sidecars add their container under it too. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). @@ -171,9 +171,9 @@ MUST NOT: `test-results`, `playwright-report`), and do not run `playwright test` directly while a stack of this checkout runs. - Edit anything in `e2e/evidence/` (git-ignored, local). Do not cite it as if it were in git. - Reach a real external host, switch the guard off, or add a route that allows another origin. Only `@npm` tests need - the app container to reach the npm registry. The places the backend may be pointed at are the run's own echo sidecar (`echo` fixture, `src/security/echo.ts`) and, only in a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, the opt-in node-service sidecars: today the Firebird sidecar (`firebirdConnection()`, `src/datasource/firebird.ts`). Later opt-in sidecars add their names to this sentence. Never give a data source or a registry entry any other URL, and never rely on a placeholder host failing to resolve: every connection of a sidecar test goes to the sidecar. + the app container to reach the npm registry. The places the backend may be pointed at are the run's own echo sidecar (`echo` fixture, `src/security/echo.ts`) and, only in a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, the opt-in node-service sidecars: the Firebird sidecar (`firebirdConnection()`, `src/datasource/firebird.ts`) and the libSQL server sidecar (`libsqlConnection()`, `src/datasource/libsql.ts`). Later opt-in sidecars add their names to this sentence. Never give a data source or a registry entry any other URL, and never rely on a placeholder host failing to resolve: every connection of a sidecar test goes to the sidecar. - Import `test` from `@playwright/test` in a spec that opens a page or uses the stack: the network guard exists only in the `test` of `src/fixtures.ts` (accepted exception for stack-free unit specs below). -- Commit secrets. The PostgreSQL password in `src/constants.ts` is the throw-away one of the sidecar. The Firebird password in `src/constants.ts` is likewise the throw-away one of its own sidecar. +- Commit secrets. The PostgreSQL password in `src/constants.ts` is the throw-away one of the sidecar. The Firebird password in `src/constants.ts` is likewise the throw-away one of its own sidecar, and so are the libSQL tokens (`LIBSQL`): signed with a key pair generated once, whose private half was thrown away. - Let the super admin's password (`E2E_SUPERUSER_PASSWORD`, new every run, set by `run-in-docker.sh`) reach a command line, log, trace, report, test title, annotation or error message; keep `set -x` off in the script. Never give the password to a matcher as the expected or received value (`expect(text).not.toContain(password)` prints it when it fails): assert `text.includes(password)` is `false`. The sign-in lives in an automatic worker fixture (`superAdminState`) because a request context created inside a test lands in its trace; do not sign the super admin in from a test or a helper, and create no request context in a helper. Every test that uses the `superAdmin` fixture carries `TAGS.SUPERADMIN` (a guard in `foundation/run-selection.spec.ts` checks it by parsing the spec with the TypeScript compiler: write the tag as `TAGS.SUPERADMIN` in the test's or its describe's details, a mention in a comment or title does not count). The super admin is ONE account shared by all workers: never switch its workspace or change its password. It hangs once the stack holds more than about 420 workspaces (README, security section): the SEC-R16 tests therefore carry `@superadmin` and run only on request (`E2E_INCLUDE_SUPERADMIN=1`); keep such runs short. - Duplicate a helper that exists: @@ -194,6 +194,7 @@ MUST NOT: | media | `PNG_RED`, `PNG_BLUE`, `WAV`, `WEBM`, `MP4`, `PDF`, `PDF_RAW_B64` | `src/media.ts` | | security actors, quarantine, answers, tokens | `Actor`, `adminOfApiUser`, `joinWorkspace`, `makeDeveloper`, `makeAdmin`, `grantApp`, `seedPrivateApp`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `securityTestDetails`, `securityCandidateDetails`, `expectAnswer`, `expectDeniedAs`, `forgeApiKeyToken`, `forgeUnsignedToken`, `withRandomSignature`, `tokenIsSignedWith`, `superAdminCredentials`, `SUPER_ADMIN_ENV`, `enterpriseAdmin` (ENTERPRISE stack: an actor the super admin makes admin of the one workspace), `echoTargetPath`, `echoReadPrefix`, `echoBaseUrl`, `echoUrlByIp` (an echo target URL with its host replaced by the echo's IP address, `E2E_ECHO_IP`: for a plugin that derives a host name from its endpoint, e.g. an S3 bucket call; never address a bucket of the `e2e-echo` alias), `recordsContain` (requests the SERVER makes, read back from the HTTP echo sidecar: the `echo` fixture gives a test its own target `url` and `received()`; a denial must follow a positive control that the echo does receive from that path; compare a secret with `recordsContain(...)` as a boolean, never as a matcher's value) (the `actor`, `superAdmin` and `echo` fixtures are in `src/fixtures.ts`; the raw-answer helper `apiRaw` and the other security API helpers are in `src/api/client.ts`) | `src/security/actors.ts`, `scene.ts`, `quarantine.ts`, `assertions.ts`, `tokens.ts`, `super-admin.ts`, `enterprise.ts`, `echo.ts` | | Firebird sidecar connection (opt-in sidecar: throws `FirebirdSidecarMissingError` when `E2E_FIREBIRD_HOST` is unset), the rows of `fixtures/firebird/init.sql` | `firebirdConnection`, `FirebirdSidecarMissingError`, `FIREBIRD_ITEMS` | `src/datasource/firebird.ts` | +| libSQL sidecar connection (opt-in sidecar: throws `LibsqlSidecarMissingError` when `E2E_LIBSQL_HOST` is unset) and a direct pipeline call to it from the test process (the control that shows the server's own answer) | `libsqlConnection`, `libsqlDirect`, `LibsqlSidecarMissingError`, `LIBSQL_PIPELINE_PATH` | `src/datasource/libsql.ts` | | pages | `EditorPage`, `AppViewPage`, `PropertyPanel`, `QueryPanel`, `TableView`, `ExtensionsPanel`, `AppListPage`, `AuthPage`, `LoginPage`, `UserMenu`, `SettingPage`, `DatasourcePage` | `src/pages/` | Accepted exception to the `test` import rule: stack-free unit specs that open no browser page (no `page`, no app) may @@ -270,6 +271,7 @@ E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --grep @quarantine E2E_INCLUDE_INSERT_ALL=1 e2e/scripts/run-in-docker.sh --grep @insert-all --workers=4 # S1 gate, once E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin # SEC-R16a, R16b (R16c, R16d also need E2E_INCLUDE_QUARANTINE=1) E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-firebird.spec.ts # D12 gate: starts the Firebird sidecar (image pull, a few seconds) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-turso-libsql.spec.ts # D13 gate: starts both sidecars (Firebird and libSQL) E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # only the tests that need a sidecar e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/modules/module-editor-host.spec.ts # M3 gate E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/security/enterprise.spec.ts # ENTERPRISE stack gate (its own stack; never at the same time as another run) @@ -284,7 +286,7 @@ Directory `e2e/` (no stack; `--reporter=list` is required so no report files are LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_INCLUDE_QUARANTINE=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_INCLUDE_SUPERADMIN=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # adds the D12 tests +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # adds the D12 and D13 tests E2E_INCLUDE_INSERT_ALL=1 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_SUPERADMIN=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_STACK_PROFILE=enterprise LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # the SEC-E tests only ``` diff --git a/e2e/README.md b/e2e/README.md index eb3a75c3b7..d1d2e3a0b6 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; Firebird (node-firebird over TCP, D12) runs against a Firebird sidecar of its own that only a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` starts, and a default run neither starts it nor lists or runs those tests; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; Firebird (node-firebird over TCP, D12) runs against a Firebird sidecar of its own that only a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` starts, and a default run neither starts it nor lists or runs those tests, and Turso also runs against a real libSQL server (sqld, D13) the same way, where the `libsql://` to `https://` rewrite of the URL is not covered because the sidecar speaks plain HTTP; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -43,6 +43,12 @@ lifecycle (insert, save, publish, load) is covered by S1 when `@insert-all` runs - **Image:** `firebirdsql/firebird:3.0.12`, pinned by tag and digest (`sha256:e45c9bc4fdacaaddc1980a05b7bb8b297f09fe019eadefb059006efe4dafe875`; `FIREBIRD_IMAGE` overrides it), data from `fixtures/firebird/init.sql` (`FB_ITEMS`, 3 read-only rows; `FB_NOTES`, writes scoped by owner), throw-away user and password in `FIREBIRD` of `src/constants.ts` and in the script. Why this one, measured with node-firebird 1.1.9 (the version node-service installs) from the runner: 3.0.12, 4.0.5 and 5.0.4 all refuse the attach with the image's defaults (3.0.12 and 5.0.4: "Incompatible wire encryption levels requested on client and server", WireCrypt `Required`; 4.0.5: "Error occurred during login"). 4.0.5 and 5.0.4 attached with `FIREBIRD_CONF_AuthServer=Srp,Legacy_Auth` plus `FIREBIRD_CONF_WireCrypt=Disabled` (one attempt each). 3.0.12 attached with `FIREBIRD_CONF_WireCrypt=Enabled` or `FIREBIRD_USE_LEGACY_AUTH=true`, but with its default Srp login 12 of 100 attaches failed with "Your user name and password are not defined" (node-firebird's client-side Srp; also seen through the app: 4 of 14 queries of one probe), while with `FIREBIRD_USE_LEGACY_AUTH=true` 100 of 100 attached. The sidecar therefore runs 3.0.12 with `FIREBIRD_USE_LEGACY_AUTH=true` (Legacy_Auth first, WireCrypt `Enabled`). Limit of that choice: Legacy_Auth compares only the first eight characters of a password (measured: a wrong password that shares them attached), so the wrong password of D12b differs within them; the sidecar is not evidence about the Srp login of Firebird 3, 4 or 5, which node-firebird 1.1.9 fails at random. - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar` (or name the spec file). - **Cost, measured here:** image 156 MB (`docker image inspect`), a cold pull of the pinned digest took 3 s (a fast link and a warm registry mirror: expect more elsewhere), the container accepted the readiness SELECT within about 3 s of starting (the script logged `Firebird sidecar ready after 0s`: the wait ran after the PostgreSQL wait of 2 s), and a gate of 110 tests ran in about 23 s. Runs without the flag pay nothing. +- **libSQL sidecar (opt-in):** the Turso plugin of node-service posts Hrana pipelines to `/v2/pipeline` over HTTP, so the echo can stand in for it (D5, canned answers); a real server adds what canned answers cannot: the real column types and cells, real SQL errors, real authentication (D13, `tests/datasource/plugin-turso-libsql.spec.ts`). It is OPT-IN under the same flag and tag as the Firebird sidecar and both start together: + - **A default run** starts no libSQL container, pulls no libSQL image, passes no `E2E_LIBSQL_HOST` to the runner, and neither lists nor runs the D13 tests. **A run with the flag** starts the sidecar right after the Firebird one, waits (at most `STARTUP_TIMEOUT`, 300 s, polled every 2 s) until one real `select 1` pipeline with the read-write token, posted from the echo container to `http://e2e-libsql:8080/v2/pipeline` over the run network, answers 200 with the integer 1, gives the app container and the runner `--add-host e2e-libsql:` (added to the Firebird entry, not replacing it), passes `E2E_LIBSQL_HOST=e2e-libsql` to the runner, and removes the container in the cleanup trap however the run ends. The data source URL is `http://e2e-libsql:8080` (`libsqlConnection()` throws a named error when the host variable is unset). + - **Image:** `ghcr.io/tursodatabase/libsql-server:v0.24.33`, sqld 0.24.33, pinned by tag and digest (`sha256:f8ca0134cdded747793888e48591aece07647d9d598d3ac229aabfa93159ca88`; `LIBSQL_IMAGE` overrides it). It is the libSQL project's own server image. Its `latest` tag, pulled at the same time, was another build that also reports sqld 0.24.33 (digest `sha256:6dd3eb276d9d3604e4a48ac4a999a2e267814732d57d7e94c04ba71482333a67`), so the pin uses the version tag. The image declares `/var/lib/sqld` a volume, so the script mounts a tmpfs there: the database is in memory and no anonymous volume outlives the run. + - **Auth setup:** sqld started with `SQLD_AUTH_JWT_KEY` accepts only a JWT signed with the matching Ed25519 key (a plain `--http-auth` would want Basic credentials, but the plugin sends `Authorization: Bearer `). A key pair was generated once and its private half thrown away; `LIBSQL` in `src/constants.ts` and `LIBSQL_JWT_PUBLIC_KEY` / `LIBSQL_TOKEN` in the script hold the public key and tokens signed with it, without an expiry: a read-write token (claim `a: "rw"`), a read-only one (`a: "ro"`, the server answers 403 to a write) and a "foreign" one signed by a second throw-away pair (the server answers 401). A foundation test verifies the three signatures against the public key. Without a token, with a malformed one or with the foreign one the server answers 401. + - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-turso-libsql.spec.ts` (both sidecars start; `--grep @node-service-sidecar` runs D12 as well). + - **Cost, measured here:** the image is 153 MB (`docker image inspect`, uncompressed) and a cold pull of the pinned digest took 9 s (a fast link: expect more elsewhere); the container started with the Firebird one and answered the readiness call within about a second (the script logged `libSQL sidecar ready after 0s`, the wait running after the PostgreSQL, echo and Firebird waits), so the two sidecars together add no waiting of their own beyond the slower one; a gate of 110 tests (`--repeat-each=10 --workers=4`) ran in about 27 s. Runs without the flag pay nothing. A readiness failure is bounded: with a copy of the script whose key did not match the readiness token and `STARTUP_TIMEOUT=6`, the run stopped after about 11 s with `the libSQL sidecar did not become ready within 6s`, the server's log tail, and the containers and network removed. - **HTTP echo sidecar** (`scripts/echo-server.js`, started by `run-in-docker.sh` on the already pinned runner image, so no extra image or download; network alias `e2e-echo`, port 8080; the runner gets `E2E_ECHO_URL` and the sidecar's IP address on the run network as `E2E_ECHO_IP`): the target of the requests the SERVER makes inside the app container (node-service's npm registry proxy, the n8n plugin). It records `{ method, path, headers, body }` of every request in @@ -132,7 +138,7 @@ e2e/scripts/run-in-docker.sh -g "sign-up through the UI" # one test b e2e/scripts/run-in-docker.sh --grep @smoke # by tag: @smoke @core @slow @npm E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --grep @quarantine E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin # SEC-R16a, SEC-R16b (R16c, R16d also need E2E_INCLUDE_QUARANTINE=1) -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # D12, the Firebird sidecar tests (starts the sidecar) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # D12 and D13, the Firebird and libSQL sidecar tests (starts both sidecars) E2E_INCLUDE_INSERT_ALL=1 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh # everything on the default stack (not the @enterprise tests) E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh tests/security/enterprise.spec.ts # the ENTERPRISE stack, SEC-E01 to E04, E06a, E06b, E07a, E07b E2E_STACK_PROFILE=signup-disabled e2e/scripts/run-in-docker.sh tests/auth/signup-disabled.spec.ts # the stack with e-mail sign-up switched off, LC-AU20 to AU24 @@ -187,7 +193,9 @@ data; its tests are untagged. | `PLAYWRIGHT_IMAGE` | run-in-docker.sh | runner image; version must equal `@playwright/test` in `package-lock.json` (1.64.0) | | `POSTGRES_IMAGE` | run-in-docker.sh | PostgreSQL sidecar image | | `FIREBIRD_IMAGE` | run-in-docker.sh | Firebird sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | -| `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | script and config | non-empty, default stack only (any other profile stops the script): start the Firebird sidecar and include the `@node-service-sidecar` tests (D12) | +| `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | script and config | non-empty, default stack only (any other profile stops the script): start the Firebird and libSQL sidecars and include the `@node-service-sidecar` tests (D12, D13) | +| `LIBSQL_IMAGE` | run-in-docker.sh | libSQL server (sqld) sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | +| `E2E_LIBSQL_HOST` | set by run-in-docker.sh | the libSQL sidecar's network alias, only in a run with the flag; `libsqlConnection()` reads it | | `E2E_FIREBIRD_HOST` | set by run-in-docker.sh | the Firebird sidecar's network alias, only in a run with the flag; `firebirdConnection()` reads it | | `E2E_INCLUDE_QUARANTINE`, `E2E_INCLUDE_INSERT_ALL`, `E2E_INCLUDE_SUPERADMIN` | script and config | non-empty: include that opt-in group | | `E2E_STACK_PROFILE` | run-in-docker.sh, config | `default` (the default), `signup-disabled` (the app container gets `LOWCODER_EMAIL_SIGNUP_ENABLED=false` and the run keeps only the `@signup-disabled` tests; `E2E_INCLUDE_QUARANTINE` is the only flag that applies) or `enterprise`: the app container gets `LOWCODER_WORKSPACE_MODE=ENTERPRISE` and the run keeps only the `@enterprise` tests (`grep`); another value stops the run. On the enterprise profile `E2E_INCLUDE_QUARANTINE` opens nothing extra (no enterprise test is quarantined any more), `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` change nothing (the stack has one workspace, so the D-47 limit does not arise). A `--grep` of the command line narrows the profile's selection further; it does not replace it (measured with Playwright 1.64: enterprise profile with `--grep SEC-R01b` lists 0 tests, with `--grep SEC-E02` lists 1, with the default profile `--grep SEC-E02` lists 0) | @@ -268,15 +276,16 @@ Test titles carry these ids. - D10 the DynamoDB and S3 plugins of node-service (AWS SDK v3) against the echo sidecar: a DynamoDB call is a signed JSON POST to `/ddb/` (`x-amz-target`, credential scope with the access key and region, the secret never sent), GetItem, PutItem and Query wrap the request's values and unwrap the answer's typed attributes, a service error fails the query with its message, the published view after a click; the S3 connection test lists the buckets (API and the form's Test Connection button), a refused test answers `code` 500 with the service's text (HTTP 200), a listBuckets query answers the names, every call that takes a bucket (listObjects with and without a presigned URL, readFile, uploadData, deleteFile) is path-style `/s3//` on the echo's IP address, a service error fails the query, a bucket call without a bucket sends nothing (readFile, uploadData and deleteFile show the SDK's text, NSD-8 candidate) (`@node-service`; the signed request's shape and the answer's path into the app, not the vendor service). - D11 the Supabase Storage plugin of node-service (`supabase-js`, project URL `/sb`) against the echo sidecar: every operation (listBuckets, listObjects, readFile, uploadData, deleteFile, createSignedUrl) sends its Storage API request below `/sb/storage/v1` with the key in `apikey` and `authorization` and nowhere else, a trailing slash of the project URL changes nothing, a storage error fails the query with `{"size":0,"timeout":0}` and not the API's message (NSD-9 candidate), the signed-URL validity is an epoch time in milliseconds (NSD-10 candidate), the `search` field of listObjects is not sent (NSD-11 candidate), only listObjects refuses an empty bucket (NSD-12 candidate), the published view after a click (`@node-service`; the request shape and the answer's path into the app, not Supabase). - D12 the Firebird plugin of node-service against the opt-in Firebird sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): the connection test attaches, a wrong password and a missing database file fail it with the server's text, a named parameter answers the lower-cased row, every column type of the seeded table, parameters bound in SQL order, not object order, an unknown parameter is refused with its name, an INSERT is read back by its own owner, a SQL error is the failed query's message, the lower-case option, a failing query leaves its attachment open (NSD-13 candidate), and the runner reaches the sidecar over TCP. +- D13 the Turso plugin of node-service against the opt-in libSQL server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): create, insert and select answer typed rows (integer, real, a lower-case `boolean`, `datetime`, NULL), `includeRaw` answers the server's own result set, a write answers no values and its raw result counts the change, a blob cell is dropped from the row (NSD-14 candidate), an integer beyond 2^53 is rounded (NSD-15 candidate), a real SQL error (syntax, unknown column, constraint, two statements) fails the query with `[object Object]` (NSD-1 candidate, the defect of D5d against a real server), a token of another key or a malformed one is a 401, a read-only token reads and its write is a 403, the published view after a click, a trailing slash after the URL is a 404, and the runner reaches the sidecar. The `libsql://` rewrite is not covered. - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue -Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 827-test suite after the opt-in sidecar mechanism and the Firebird scenarios (D12) landed, `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (no variable set): 44 failed, 783 passed. It started no Firebird container (the containers seen once a second during the run were the app, the echo, PostgreSQL and the runner) and ran no D12 test (they are not in the listing). The baseline from a clean worktree of the previous commit (816 tests, same command and image): 44 failed, 772 passed. The failing sets differ by two tests, each intermittent by the evidence at hand: `SEC-R09d` failed in the baseline and not in the current run, and `logic/triggers.spec.ts` "an automatic query with periodic runs repeatedly, a manual one does not (page clock)" failed in the current run and not in the baseline (it passed 10 of 10 in a `--repeat-each=10 --workers=4` run of its own afterwards; one run each, so neither is classified further). The 44 failures of the current run are 24 `@security`, 17 `@lifecycle` and 3 others (`components/npm-components.spec.ts` calendar, `@npm`; `apps/card-menu.spec.ts` export and import, `@core`; the periodic trigger above); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag and by the baseline, not analysed one by one). No node-service scenario failed. The D12 evidence is a separate gate, `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-firebird.spec.ts`: 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e`.): -default **827 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **841 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **832 in 114**; with both of those **846 in 115**; -with `E2E_INCLUDE_INSERT_ALL=1` **939 in 115**; with all three opt-in variables **958 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **838 in 115** (the 11 D12 tests of the Firebird sidecar, which no other variable lists), and **969 in 117** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: +Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 833-test suite after the libSQL sidecar scenarios (D13) landed, `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (no variable set): 43 failed, 790 passed. It started no libSQL and no Firebird container (the containers seen every 0.3 s during the run were the app, the echo, PostgreSQL and the runner) and ran no D12 or D13 test (they are not in the listing). The baseline from a clean worktree of the previous commit (827 tests, same command and image): 43 failed, 784 passed. The failing sets are identical (compared by test name): 24 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`; `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag, not analysed one by one). Neither `SEC-R09d` nor the periodic trigger test of `logic/triggers.spec.ts` failed in either of these two runs (both failed once in earlier runs, so they are still treated as intermittent). The six extra passes are the six new unit tests of `foundation/node-plugins.spec.ts`. No node-service scenario failed. The D12 and D13 evidence is a separate gate each, `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 `: for `tests/datasource/plugin-firebird.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D12 landed), for `tests/datasource/plugin-turso-libsql.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (both sidecars start).): +default **833 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **847 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **838 in 114**; with both of those **852 in 115**; +with `E2E_INCLUDE_INSERT_ALL=1` **945 in 115**; with all three opt-in variables **964 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **855 in 116** (the 11 D12 tests of the Firebird sidecar and the 11 D13 tests of the libSQL sidecar, which no other variable lists), and **986 in 118** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 122 in 10 files (the 31 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **133 in 11 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests); `@node-service-sidecar` 0 (**11 in 1 file** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 128 in 10 files (the 37 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **150 in 12 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests and the 11 D13 tests); `@node-service-sidecar` 0 (**22 in 2 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests, and D13a to D13k, the libSQL sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -325,7 +334,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | editor/js-query.spec.ts | a JS query written in the editor runs | @core | 1 | | editor/drop-size.spec.ts | a component dropped right after ready has width above 0 (D-5) | @quarantine | 1 | -### datasource (101 default, 112 with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`) +### datasource (101 default, 123 with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`) | File | Proves | Tags | Tests | |---|---|---|---| @@ -342,6 +351,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/plugin-aws-sdk.spec.ts | D10: DynamoDB and S3 against the echo sidecar (endpoints `/ddb` and `/s3`; bucket calls on the echo's IP address). Measured on 3.0.0-e2e and 3.0.1-e2e (the SDK version printed in its user agent is 3.668.0 on 3.0.0-e2e; the tests match the shape, not the version): the SDK keeps the endpoint's path, DynamoDB posts to `/ddb/`, S3 without a bucket gets `/s3/?x-id=ListBuckets`, and with a bucket on an IP-address endpoint it is path-style (`/s3//`, `Host` the IP address). Every request a D10 test makes is asserted completely: method, path and query, body, the whole header set (per-request values by shape: date, invocation id, user agents, signature), the credential scope (access key, date, region, service) and the signed-header list, and every D10 test that sends a request also asserts that the secret key is in no header, path or body of the echo's records (with a control that the access key is: it travels in the credential scope). The rows of D10q that send nothing assert that the echo holds no record, after which a control call with a bucket is asserted completely. The presigned URL of D10l is asserted by its stable query parameters and by shape, not by value. D10a DynamoDB ListTables (region `eu-central-1` in the scope, body `{TableName: "", Limit: 10}`, answer without `$metadata`), D10b GetItem wraps the key and unwraps a string, a number, a string set and a boolean, D10c PutItem wraps a number, a string and a boolean, D10d Query keeps the expression and unwraps the items, D10e a 400 `ResourceNotFoundException` fails the query (`Requested resource not found`, one request), D10f the published view after a click, D10g the connection test (`code` 1, `success`, `data` true; one `GET /s3/?x-id=ListBuckets`), D10h a 403 test answers HTTP 200 with `code` 500, `success` false and `Failed to connect data source: Access Denied.`, and the same body succeeds once the endpoint answers 200, D10i the form's Test Connection button shows that text, then `Connection Successful`, D10j listBuckets answers `[{name}]`, D10k listObjects is path-style on the IP with `delimiter`, `max-keys` and `prefix` and answers name, size, time, file URL, D10l `returnSignedUrl` adds a presigned URL (`X-Amz-Expires=300`, signed header `host`, no extra request), D10m readFile as text and base64, D10n uploadData of text and of base64 without a content type (`application/octet-stream`), D10o deleteFile, D10p a 403 and a 404 fail the query with the service's text, D10q a bucket call without a bucket sends nothing: listObjects says `Bucket is required`, readFile, uploadData and deleteFile say `Empty value provided for input HTTP label: Bucket.` (NSD-8 candidate), after a control that a call with a bucket reaches the echo. Not covered: a real DynamoDB or S3 service, the SDK's retry of a 5xx answer | @node-service | 19 | | datasource/plugin-supabase-storage.spec.ts | D11: the Supabase Storage plugin against the echo sidecar (project URL `/sb`; the Storage API is `/sb/storage/v1/...`). Measured on 3.0.0-e2e and 3.0.1-e2e (same requests and answers; supabase-js 2.45.4 in `x-client-info`, matched by shape): the client keeps the project URL's path with or without a trailing slash and derives no host name; every request carries `apikey: `, `authorization: Bearer `, the `node-fetch` user agent, `accept-encoding: gzip,deflate` and `connection: close`. Every request a D11 test makes is asserted completely (method, path and query, body, the whole header set), and every test that sends one also asserts that the key is in no header besides those two, no path or body, and no answer of the query (the whole query answer; in D11q the view's whole `q.data` as text); control: it is in those two. D11a listBuckets `GET /bucket` and the buckets as the API answered, D11b the project URL with and without a trailing slash reach the same path, D11c listObjects `POST /object/list/` with `{limit: 10, offset: 0, sortBy: {column: name, order: asc}, prefix}` and the public URL of each file in the answer, D11d limit, offset and sort order of the query, D11e the `search` field is not sent (NSD-11 candidate), D11f `returnSignedUrl` adds `POST /object/sign/` with `{expiresIn, paths}` and the signed URL in the answer, D11g readFile as text and base64 (`GET /object//`, answer `{data, type}`), D11h readFile with a transform goes to `/render/image/authenticated//?width=10`, D11i uploadData of text `POST /object//` with the text, its content type, `cache-control: max-age=3600` and `x-upsert: false`, D11j base64 without a content type sends an empty `content-type` header (observation), D11k uploadData with `returnSignedUrl` uploads then signs, D11l deleteFile `DELETE /object/` with `{prefixes: [name]}`, D11m createSignedUrl sends `expiresIn` as an integer above 1e12, an epoch time in milliseconds computed once (the second query, asserted completely too, sends the same number; the bounds allow one hour of clock skew and a plugin load up to six hours old; NSD-10 candidate, also asserted in D11f and D11k), D11n a 400, a 404 and a 401 answer fail the query with `{"size":0,"timeout":0}` instead of the answer's message, each followed by a control that the same query succeeds once the API answers 200 (NSD-9 candidate), D11o the signing and the listing fail the same way, each followed by a control that both succeed once the API answers 200 on their paths, D11p an empty bucket: listObjects says `Bucket is required` and sends nothing, readFile, uploadData, deleteFile and createSignedUrl send requests with an empty bucket segment (NSD-12 candidate), D11q the published view shows the bucket name only after the click (echo empty before, one request after). Not covered: a real Supabase project; the connection test (none is wired up for this plugin) | @node-service | 21 | | datasource/plugin-firebird.spec.ts | D12: the Firebird plugin against the opt-in Firebird sidecar (Firebird 3.0.12, `fixtures/firebird/init.sql`; host, port, database path and login of the sidecar written over the recorded form body). Measured on 3.0.0-e2e and 3.0.1-e2e. D12a the connection test answers `code` 1, `success` true, `data` true; D12b a wrong password answers `code` 500 with `Failed to connect data source: Your user name and password are not defined. Ask your database\nadministrator to set up a Firebird login\n.` and a missing database file with the server's `I/O error for file ...` (the right fields attach first); D12c `SELECT ID, NAME FROM FB_ITEMS WHERE ID = :id` with `{"id": 2}` answers `[{id: 2, name: "beta"}]`; D12d the three seeded rows with `price` as a number and a NULL as `null`; D12e parameters bind in the order the names appear in the SQL, not the key order of the parameter object (`CAST(:first AS INTEGER) - CAST(:second AS INTEGER)` with 10 and 3 answers 7 whichever order the object lists them); D12f an unknown name fails with `Named parameter "missing" not found in Query Parameters object.` (the same SQL with the name present runs); D12g an INSERT answers `{}` and is read back by the test's own owner (the owner has no row before); D12h a syntax error and an unknown table answer the server's text; D12i `lowercaseKeys: false` answers upper-case keys; D12j a query that fails after the attach leaves its attachment open on the server, a succeeding one does not: two failing runs of a statement that tags its attachment with a per-test context variable leave exactly two tagged attachments in `MON$CONTEXT_VARIABLES`, and a succeeding tagged run does not add a third (NSD-13 candidate, `defect` annotation); D12k the runner connects to the sidecar's port 3050, and a closed port of the same host is refused. Limits: `role`, `blobAsText` and Firebird 4 and 5 are not covered; the sidecar authenticates with Legacy_Auth (see the architecture bullet) | @node-service @node-service-sidecar (opt-in) | 11 | +| datasource/plugin-turso-libsql.spec.ts | D13: the Turso plugin against the opt-in libSQL sidecar (sqld 0.24.33 with a JWT key; the data source URL is `http://e2e-libsql:8080`, the recorded `turso` form body with the sidecar's URL and token written over it; each test makes its own table `e2e_t_`). Measured on 3.0.0-e2e and 3.0.1-e2e. D13a CREATE, two INSERTs and a SELECT: a CREATE and an INSERT answer `[]`, the empty table answers `[]` before the inserts, then `integer` is a number, `real` 2 stays 2, a `boolean` column written in lower case is `true`/`false`, a `datetime` text is the ISO text of a `Date` (`2024-01-02T03:04:05.000Z`), NULL is `null`; D13b `includeRaw` answers `values` and the server's `raw` (columns with their declared types, cells such as `{type:"integer", value:"7"}`, the counters; the timing is only checked to be a number); D13c an INSERT answers `[]` with and without `includeRaw`, its raw result has `affected_row_count` 1 and `last_insert_rowid` `"2"` (a string) for the second row; D13d a blob cell is missing from the row (`[{id: 1}]`) while `includeRaw` shows the server sent `{type:"blob", base64:"AP8Q"}` (NSD-14 candidate); D13e `SELECT 9007199254740993` answers 9007199254740992 while the raw cell is the exact string (NSD-15 candidate); D13f `SELEC 1`, an unknown column, a duplicate key and `SELECT 1; SELECT 2` are errors of the server with codes `SQL_PARSE_ERROR`, `SQL_INPUT_ERROR`, `SQLITE_CONSTRAINT` and `SQL_MANY_STATEMENTS` (read by direct calls), and every one of them reaches the app as `Cannot parse result, received error: [object Object]` (NSD-1 candidate; a valid query of the same app succeeds first); D13g a token signed by another key and a string that is no JWT fail with `Failed to execute query. Endpoint returned 401: Unauthorized.` (the sidecar's own token reads the row first; direct calls show the server's `The JWT is invalid` and, without a header, `Expected authorization header but none given`); D13h a read-only token reads, its INSERT fails with `Endpoint returned 403: Forbidden.` and writes nothing (the read-write token then inserts the same row); D13i the published view shows a row after a click; D13j a URL with a trailing slash fails with `Endpoint returned 404: Not Found.` (the plugin builds `//v2/pipeline`; the same URL without it works); D13k the runner reaches the sidecar over HTTP and TCP, a closed port of the same host is refused. Limits: the `libsql://` to `https://` rewrite, a stream with a baton, and Turso's cloud features are not covered | @node-service @node-service-sidecar (opt-in) | 11 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -486,14 +496,14 @@ first makes sure some admin exists (accepting both answers), so none depends on SEC-R09d (D-38) left the quarantine: the check took the workspace of the first id of a `HashSet`; each id is now decided in its own workspace (Java unit and MongoDB integration tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)). Accounting of the earlier 3.0.0 run `E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --workers=4 --reporter=list --grep "@quarantine" tests/security` (measured before the `@superadmin` tag existed and before the reassessment, so it listed 44 tests, 19 of which have since left the quarantine): 44 listed, 43 failed, 1 passed (SEC-R09d); the two quarantined tests of `foundation/security-helpers.spec.ts` are outside that folder. -### foundation (306 default, 309 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) +### foundation (312 default, 315 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) | File | Proves | Tags | Tests | |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization`, and the Firebird sidecar helpers: `firebirdConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the firebird recordings (form fields with the sidecar's values, one query, no session value), `fixtures/firebird/init.sql` equals `FIREBIRD_ITEMS`, the script's Firebird constants equal `FIREBIRD`, and the run script starts, waits for and passes the sidecar only inside `if node_service_sidecars_enabled` | @node-service | 31 | -| foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources), `@node-service-sidecar` (excluded by default, included by `E2E_INCLUDE_NODE_SERVICE_SIDECARS`, independent of the other flags, never selected on the enterprise and signup-disabled stacks), and the guard that every test of a spec that calls `firebirdConnection` carries `@node-service-sidecar` (same parsing; synthetic sources) | none | 32 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization`, and the Firebird sidecar helpers: `firebirdConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the firebird recordings (form fields with the sidecar's values, one query, no session value), `fixtures/firebird/init.sql` equals `FIREBIRD_ITEMS`, the script's Firebird constants equal `FIREBIRD`, and the run script starts, waits for and passes the sidecar only inside `if node_service_sidecars_enabled`; and the libSQL sidecar helpers: `libsqlConnection` (reads the host variable, builds the plain-HTTP URL, throws a named error when it is unset or empty), the script's libSQL values equal `LIBSQL` (alias, port, public key, token, an image pinned by tag and digest, the tmpfs data directory), the three tokens are JWTs with the claims they are named for and only the two sidecar ones verify under the sidecar's key (the foreign one is well-formed and does not), the script starts and waits for the libSQL sidecar only under the flag and appends its `--add-host` and host variable to the Firebird ones, and `libsqlDirect` against a local server (the pipeline body, the bearer header or none, a JSON or a text body) | @node-service | 37 | +| foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources), `@node-service-sidecar` (excluded by default, included by `E2E_INCLUDE_NODE_SERVICE_SIDECARS`, independent of the other flags, never selected on the enterprise and signup-disabled stacks), and the guard that every test of a spec that calls `firebirdConnection` or `libsqlConnection` carries `@node-service-sidecar` (same parsing; synthetic sources) | none | 32 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | | foundation/module-host.spec.ts | module created through the API works in a host; republish rules | none | 2 | @@ -532,7 +542,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | CD-7 | `setIn` with a bad path or on a scalar fails silently (query ends as success) | `logic/temporary-state.spec.ts` asserts today's behaviour, annotation `{type:"defect", description:"CD-7"}`, default run | | CD-8 | `transfer` list titles are in the wrong order: confirmed by code (`titles={[targetTitle, sourceTitle]}`, 2026-11-22 reading) | conditional `defect` annotation in `components/choices.spec.ts` (the annotation still says candidate) | | CD-9 | an icon switched from a name to an image URL keeps the old icon: confirmed (failed 3 of 3 on 3.0.1-e2e; code: the old icon is cached under the new URL and `undefined === undefined` keeps it) | `components/displays.spec.ts`, `@quarantine`, `defect` annotation (still named candidate there) | -| NSD-1 candidate | the Turso plugin prints a pipeline `error` result as `${result.error}`, an object: a failed statement reaches the app as `Cannot parse result, received error: [object Object]` and the server's own message is lost; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-turso-slack.spec.ts` D5d asserts today's message (characterisation, default run), annotation `{type:"defect", description:"NSD-1 candidate"}`; it changes when the plugin prints the message | +| NSD-1 candidate | the Turso plugin prints a pipeline `error` result as `${result.error}`, an object: a failed statement reaches the app as `Cannot parse result, received error: [object Object]` and the server's own message is lost; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-turso-slack.spec.ts` D5d asserts today's message (characterisation, default run), annotation `{type:"defect", description:"NSD-1 candidate"}`; it changes when the plugin prints the message. Against the real libSQL sidecar the same text is printed for a syntax error, an unknown column, a constraint violation and a two-statement string, each of which the server answers with its own message and code (`datasource/plugin-turso-libsql.spec.ts` D13f, same annotation) | | NSD-3 candidate | the DuckDB plugin answers rows keyed by the column position, not the column name (`SELECT 42 AS answer` arrives as `{"0": 42}`): `getRows()` answers arrays and `serializeBigInts` copies `Object.entries(row)`; measured on 3.0.0-e2e and 3.0.1-e2e. An app cannot read `row.answer`. The id is provisional until the owner assigns one | `datasource/plugin-duckdb.spec.ts` D4a to D4c assert today's keys (characterisation, default run), annotation `{type:"defect", description:"NSD-3 candidate"}`; they change when the plugin keys rows by name | | NSD-2 candidate | the Shopify plugin reads the query's headers and passes `{}` on, and its data source has only `endpoint`: it cannot send Shopify's access token (`X-Shopify-Access-Token`); measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-graphql.spec.ts` D6d asserts today's behaviour after a control that the request did reach the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-2 candidate"}`; it changes when the query's headers are forwarded | | NSD-4 candidate | the generic Open API plugin returns the body of an error status answer as the query result (`runOpenApi` catch, `e.response.body`): a canned 404 `{"message":"e2e-missing"}` is reported as `success: true`, `queryCode: "OK"`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi.spec.ts` D7d asserts today's behaviour after a control that the request reached the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-4 candidate"}`; it changes when an error status fails the query. `datasource/plugin-openapi-wrappers-apps.spec.ts` D9i shows the same for APITemplate (wrappers share `runOpenApi`) | @@ -545,6 +555,8 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-11 candidate | the `search` field of the Supabase Storage listObjects query is never sent: the request body is `{limit, offset, sortBy, prefix}` whatever the field holds; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11e asserts today's body after a positive control that the query's prefix travels (characterisation, default run), annotation `{type:"defect", description:"NSD-11 candidate"}`; it changes when the search text is sent | | NSD-12 candidate | the Supabase Storage plugin checks the bucket itself only for listObjects (`Bucket is required`); readFile, uploadData, deleteFile and createSignedUrl with an empty bucket send a request whose path has an empty bucket segment (`GET /object//x.txt`, `POST /object//x.txt`, `DELETE /object/`, `POST /object/sign//x.txt`), and the queries succeed against a server that answers; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11p asserts today's requests next to listObjects refusing the same empty bucket and sending nothing (characterisation, default run), annotation `{type:"defect", description:"NSD-12 candidate"}`; it changes when the four operations check the bucket like listObjects | | NSD-13 candidate | the Firebird plugin never detaches a connection when its query fails after the attach (`firebirdsql/run.ts`: `detachAsync()` comes after the awaited query, and the unknown-parameter check also runs after the attach), so the attachment stays open on the server; a succeeding query detaches. Measured on 3.0.0-e2e and 3.0.1-e2e against the Firebird sidecar: after two failing runs of a statement that tags its attachment (`RDB$SET_CONTEXT`, then a division by zero) `MON$CONTEXT_VARIABLES` holds exactly 2 attachments with the tag, and a succeeding tagged run leaves it at 2. The id is provisional until the owner assigns one | `datasource/plugin-firebird.spec.ts` D12j, `defect` annotation `NSD-13 candidate`; passes today, expect it to fail once the plugin detaches in `finally` | +| NSD-14 candidate | the Turso plugin drops a `blob` cell: the server answers it as `{type:"blob", base64}` with no `value`, `parseValue` returns `undefined` for it, and the key is missing from the row (`SELECT id, data` answers `[{id: 1}]`). Measured on 3.0.0-e2e and 3.0.1-e2e against the libSQL sidecar. The id is provisional until the owner assigns one | `datasource/plugin-turso-libsql.spec.ts` D13d, `defect` annotation `NSD-14 candidate`; passes today, expect it to fail once the plugin returns the bytes | +| NSD-15 candidate | the Turso plugin parses an `integer` cell (which the server sends as a string, exact) with `Number.parseInt`, so an integer above 2^53 is rounded: `SELECT 9007199254740993` answers 9007199254740992 while `includeRaw` shows the exact string. Measured on 3.0.0-e2e and 3.0.1-e2e against the libSQL sidecar. The id is provisional until the owner assigns one | `datasource/plugin-turso-libsql.spec.ts` D13e, `defect` annotation `NSD-15 candidate`; passes today, expect it to fail once the plugin keeps large integers exact | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/scripts/run-in-docker.sh b/e2e/scripts/run-in-docker.sh index 93d09115a5..b31cc59a06 100755 --- a/e2e/scripts/run-in-docker.sh +++ b/e2e/scripts/run-in-docker.sh @@ -24,7 +24,7 @@ ## E2E_INCLUDE_SUPERADMIN set to 1 to also run the @superadmin tests (SEC-R16a to SEC-R16d, the instance super admin; ## independent of the other flags). Run: E2E_INCLUDE_SUPERADMIN=1 $0 --grep @superadmin ## E2E_INCLUDE_NODE_SERVICE_SIDECARS set to 1 to also start the sidecars of the node-service data sources whose protocol is not HTTP -## (today a Firebird server, FIREBIRD_IMAGE below) and run their @node-service-sidecar tests; independent of the +## (today a Firebird server, FIREBIRD_IMAGE below, and a libSQL server, LIBSQL_IMAGE below) and run their @node-service-sidecar tests; independent of the ## other flags, default stack only (any other profile is an error). Without it the run starts none of them, ## neither lists nor runs those tests, and pulls no extra image. ## Run only these: E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 $0 --grep @node-service-sidecar @@ -42,6 +42,7 @@ ## E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_ENTERPRISE_TAKEOVER=1 E2E_STACK_PROFILE=enterprise $0 ## POSTGRES_IMAGE PostgreSQL sidecar for the data source tests (pinned by digest) ## FIREBIRD_IMAGE Firebird sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS +## LIBSQL_IMAGE libSQL server (sqld) sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS ## E2E_HOST_PORT also publish the app on 127.0.0.1: to look at it in a browser while the run lasts ## ## Set by the script for each run (a value of the caller is overwritten; the password is new every run, never printed, @@ -77,6 +78,14 @@ ## the image's own isql answers over TCP, and `cleanup` removes the container however the run ends. Its credentials are throw-away constants ## that must equal FIREBIRD in e2e/src/constants.ts. Without the flag nothing of this runs: no container, no image pull, no variable for the runner. ## +## Only with E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 it also starts a libSQL server sidecar (LIBSQL_IMAGE) under the alias e2e-libsql, port 8080: the target of +## the Turso data source of node-service (a real Hrana-over-HTTP server in place of the echo's canned answers). It starts after the Firebird sidecar and +## is reached exactly like it: `--add-host e2e-libsql:` for the app container and the runner, and the alias as E2E_LIBSQL_HOST for the runner. +## sqld accepts only a JWT signed by a throw-away key: the script gives it the public half (LIBSQL_JWT_PUBLIC_KEY) and uses the read-write token +## (LIBSQL_TOKEN) for its readiness call, one real `select 1` pipeline posted to the sidecar from the echo container over the run network. Both +## must equal LIBSQL in e2e/src/constants.ts. The database lives in a tmpfs (the image declares /var/lib/sqld a volume, which `docker rm -f` would +## leave behind), and `cleanup` removes the container however the run ends. Without the flag nothing of this runs. +## ## Not covered: Firefox and WebKit (only Chromium runs), the multi-container compose setup, databases other than ## PostgreSQL. ## @@ -109,6 +118,18 @@ readonly FIREBIRD_ROOT_PASSWORD="e2e-firebird-root-password" readonly FIREBIRD_USE_LEGACY_AUTH="true" readonly FIREBIRD_ALIAS="e2e-firebird" readonly FIREBIRD_PORT=3050 +# libSQL server (sqld) sidecar of the @node-service-sidecar tests, started only with E2E_INCLUDE_NODE_SERVICE_SIDECARS. The image is sqld 0.24.33 by tag and +# digest. It is told to accept only a JWT (SQLD_AUTH_JWT_KEY: the URL-safe base64 of a PUBLIC Ed25519 key); the matching private key was thrown away after +# signing the tokens of LIBSQL in e2e/src/constants.ts, so the values below are throw-away, the container dies with the run. LIBSQL_PORT is the image's +# own HTTP port. The values below must equal LIBSQL in e2e/src/constants.ts (the foundation tests check it, and that the token verifies under the key). +readonly DEFAULT_LIBSQL_IMAGE="ghcr.io/tursodatabase/libsql-server:v0.24.33@sha256:f8ca0134cdded747793888e48591aece07647d9d598d3ac229aabfa93159ca88" +readonly LIBSQL_IMAGE="${LIBSQL_IMAGE:-$DEFAULT_LIBSQL_IMAGE}" +readonly LIBSQL_ALIAS="e2e-libsql" +readonly LIBSQL_PORT=8080 +readonly LIBSQL_JWT_PUBLIC_KEY="GC25tiEOubxlGdpbkc60UOXqUQeepEUWZmAbEKjt1rQ" +readonly LIBSQL_TOKEN="eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJhIjoicncifQ.tlvnzqEfO2pnCYHReSfLIQ3dHk393fsOH5hLtLo4ZkJWJV6b9q9Zf56QbS5spbT2G9XuzYQaVsZqO4jUVSsPAw" +# The image's data directory, mounted as a tmpfs so that no anonymous volume outlives the run +readonly LIBSQL_DATA_DIR="/var/lib/sqld" # The instance super admin of the throw-away stack; the domain equals TEST_EMAIL_DOMAIN in e2e/src/constants.ts; the suite # reads the name from E2E_SUPERUSER_USERNAME (SUPER_ADMIN_ENV). The password is generated per run (generate_superuser_password). readonly SUPERUSER_USERNAME="e2e-superadmin@example.test" @@ -142,6 +163,7 @@ readonly POSTGRES_CONTAINER="${NAME_PREFIX}-pg" readonly RUNNER_CONTAINER="${NAME_PREFIX}-runner" readonly ECHO_CONTAINER="${NAME_PREFIX}-echo" readonly FIREBIRD_CONTAINER="${NAME_PREFIX}-fb" +readonly LIBSQL_CONTAINER="${NAME_PREFIX}-libsql" # The alias and port the app container and the runner use; E2E_ECHO_URL below is built from them (the suite reads it by ECHO_ENV in e2e/src/constants.ts) readonly ECHO_ALIAS="e2e-echo" readonly ECHO_PORT=8080 @@ -151,7 +173,7 @@ readonly ECHO_HEALTH_PATH="/__e2e/health" readonly ECHO_SCRIPT="$SCRIPT_DIR/echo-server.js" # Set by start_echo: the sidecar's IP on the run network (used for --add-host of the app and the runner) ECHO_IP="" -# Set by start_firebird (only with E2E_INCLUDE_NODE_SERVICE_SIDECARS): the extra `--add-host` and `-e` arguments of the app and the runner. Empty otherwise. +# Set by start_firebird and start_libsql (only with E2E_INCLUDE_NODE_SERVICE_SIDECARS): the extra `--add-host` and `-e` arguments of the app and the runner. Empty otherwise. SIDECAR_ADD_HOST=() SIDECAR_RUNNER_ENV=() @@ -165,7 +187,7 @@ fail() { } cleanup() { - docker rm -f "$RUNNER_CONTAINER" "$APP_CONTAINER" "$POSTGRES_CONTAINER" "$ECHO_CONTAINER" "$FIREBIRD_CONTAINER" > /dev/null 2>&1 || true + docker rm -f "$RUNNER_CONTAINER" "$APP_CONTAINER" "$POSTGRES_CONTAINER" "$ECHO_CONTAINER" "$FIREBIRD_CONTAINER" "$LIBSQL_CONTAINER" > /dev/null 2>&1 || true docker network rm "$NETWORK" > /dev/null 2>&1 || true } trap cleanup EXIT @@ -325,6 +347,36 @@ wait_for_firebird() { log "Firebird sidecar ready after ${waited}s" } +# sqld needs no init script: the tests make their own tables. The sidecar is started after the echo (its container is the one that probes it). +start_libsql() { + log "Starting $LIBSQL_IMAGE as $LIBSQL_CONTAINER (alias $LIBSQL_ALIAS, port $LIBSQL_PORT)" + docker run -d --name "$LIBSQL_CONTAINER" --network "$NETWORK" --network-alias "$LIBSQL_ALIAS" \ + --tmpfs "$LIBSQL_DATA_DIR" -e SQLD_AUTH_JWT_KEY="$LIBSQL_JWT_PUBLIC_KEY" \ + "$LIBSQL_IMAGE" > /dev/null + local libsql_ip + libsql_ip="$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$LIBSQL_CONTAINER")" + [ -n "$libsql_ip" ] || fail "no IP address for $LIBSQL_CONTAINER on $NETWORK" + SIDECAR_ADD_HOST+=(--add-host "${LIBSQL_ALIAS}:${libsql_ip}") + SIDECAR_RUNNER_ENV+=(-e "E2E_LIBSQL_HOST=${LIBSQL_ALIAS}") + log "libSQL sidecar is $LIBSQL_ALIAS = $libsql_ip" +} + +# A real Hrana pipeline with the read-write token, posted to the sidecar's alias over the run network from the echo container (the image has no +# curl and no shell tools of use): ready when it answers 200 with the integer 1 for `select 1`. +wait_for_libsql() { + local waited=0 + local probe="fetch(process.env.LIBSQL_PROBE_URL + '/v2/pipeline', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + process.env.LIBSQL_PROBE_TOKEN }, body: JSON.stringify({ requests: [{ type: 'execute', stmt: { sql: 'select 1' } }, { type: 'close' }] }) }).then((r) => r.text().then((t) => process.exit(r.ok && t.includes('\"value\":\"1\"') ? 0 : 1)), () => process.exit(1))" + until docker exec -e LIBSQL_PROBE_URL="http://${LIBSQL_ALIAS}:${LIBSQL_PORT}" -e LIBSQL_PROBE_TOKEN="$LIBSQL_TOKEN" "$ECHO_CONTAINER" node -e "$probe" > /dev/null 2>&1; do + if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then + docker logs --tail "$LOG_TAIL_LINES" "$LIBSQL_CONTAINER" >&2 || true + fail "the libSQL sidecar did not become ready within ${STARTUP_TIMEOUT}s" + fi + sleep "$POLL_INTERVAL" + waited=$((waited + POLL_INTERVAL)) + done + log "libSQL sidecar ready after ${waited}s" +} + wait_for_app() { local waited=0 log "Waiting for $READY_PATH (at most ${STARTUP_TIMEOUT}s)" @@ -385,11 +437,17 @@ start_echo if node_service_sidecars_enabled; then start_firebird fi +if node_service_sidecars_enabled; then + start_libsql +fi start_app wait_for_postgres wait_for_echo if node_service_sidecars_enabled; then wait_for_firebird fi +if node_service_sidecars_enabled; then + wait_for_libsql +fi wait_for_app run_tests "$@" diff --git a/e2e/src/constants.ts b/e2e/src/constants.ts index bc281a74eb..696370c309 100644 --- a/e2e/src/constants.ts +++ b/e2e/src/constants.ts @@ -220,8 +220,9 @@ export const TAGS = { */ NODE_SERVICE: "@node-service", /** - * The node-service data source tests that need a sidecar of their own because the plugin's protocol is not HTTP (today the - * Firebird tests, `tests/datasource/plugin-firebird.spec.ts`). Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of + * The node-service data source tests that need a sidecar of their own: the plugin's protocol is not HTTP (the Firebird tests, + * `tests/datasource/plugin-firebird.spec.ts`) or the test wants a real server instead of canned answers (the libSQL server tests, + * `tests/datasource/plugin-turso-libsql.spec.ts`). Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of * the default run (neither listed nor run, and the run script starts no such sidecar), in only with * `E2E_INCLUDE_NODE_SERVICE_SIDECARS` (see src/run-selection.ts and scripts/run-in-docker.sh). */ @@ -236,7 +237,7 @@ export const RUN_FLAGS = { /** Enterprise profile only: run SEC-E05 (`@enterprise-takeover`) and nothing else. */ INCLUDE_ENTERPRISE_TAKEOVER: "E2E_INCLUDE_ENTERPRISE_TAKEOVER", /** - * Default stack only: also start the sidecars of the node-service data sources whose protocol is not HTTP (Firebird) and run + * Default stack only: also start the sidecars of the node-service data sources (Firebird, a libSQL server) and run * their `@node-service-sidecar` tests. Without it the run starts none of them. */ INCLUDE_NODE_SERVICE_SIDECARS: "E2E_INCLUDE_NODE_SERVICE_SIDECARS", @@ -307,6 +308,26 @@ export const FIREBIRD = { PASSWORD: "e2e-firebird-password", } as const; +/** + * The libSQL server (sqld) sidecar that scripts/run-in-docker.sh starts on the run's network ONLY when `E2E_INCLUDE_NODE_SERVICE_SIDECARS` is + * set. The run script passes the host name (the sidecar's network alias); the rest is fixed there and must equal the `LIBSQL_*` values of the + * script. The sidecar accepts only a JWT signed by the private half of a key pair that was generated once and thrown away: `JWT_PUBLIC_KEY` + * is the public half (what the script gives sqld), and the three tokens are signed JWTs without an expiry, made with the private half + * (`READ_WRITE_TOKEN`, claim `a: "rw"`; `READ_ONLY_TOKEN`, claim `a: "ro"`) or with the private half of a second throw-away pair that the + * sidecar does not know (`FOREIGN_TOKEN`). Nothing here is a real secret: the container is removed when the run ends and holds no other data. + */ +export const LIBSQL = { + HOST_ENV: "E2E_LIBSQL_HOST", + PORT: 8080, + JWT_PUBLIC_KEY: "GC25tiEOubxlGdpbkc60UOXqUQeepEUWZmAbEKjt1rQ", + READ_WRITE_TOKEN: + "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJhIjoicncifQ.tlvnzqEfO2pnCYHReSfLIQ3dHk393fsOH5hLtLo4ZkJWJV6b9q9Zf56QbS5spbT2G9XuzYQaVsZqO4jUVSsPAw", + READ_ONLY_TOKEN: + "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJhIjoicm8ifQ.6pik3ukdCu1vxNNnUPe-ZuVrX4jgTqcJSnPU2SQOIKtVtwVbtZpzFWD8yKG4afdInqfsirG4PfeGizOeno7QDQ", + FOREIGN_TOKEN: + "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJhIjoicncifQ.QtYpcj3lGU5Rtry83fcTaI-e_WwmcvSDEFrysDlxiHGMfb_GNaJTzOvuSgas_Hivmf4D68Azw-lK7Te4vuIABg", +} as const; + export const SEEDED_ITEM_NAMES = ["alpha", "beta"] as const; /** Component type, panel search text, drop position and generated name of the button the editor tests drop. */ diff --git a/e2e/src/datasource/libsql.ts b/e2e/src/datasource/libsql.ts new file mode 100644 index 0000000000..059a241ee9 --- /dev/null +++ b/e2e/src/datasource/libsql.ts @@ -0,0 +1,66 @@ +import { LIBSQL, RUN_FLAGS } from "../constants"; + +/** Where a Turso data source connects: the libSQL sidecar of the run, as the app container reaches it (by the sidecar's network alias, over plain HTTP so the plugin's `libsql://` rewrite does not apply). */ +export interface LibsqlConnection { + /** `http://:`, no trailing slash: the plugin appends `/v2/pipeline`. */ + url: string; + /** A JWT the sidecar accepts for reads and writes. */ + token: string; +} + +/** The sidecar's host variable is not set: the run did not start the libSQL sidecar. */ +export class LibsqlSidecarMissingError extends Error { + constructor() { + super( + `${LIBSQL.HOST_ENV} is not set: the libSQL sidecar was not started. Run the suite through e2e/scripts/run-in-docker.sh with ${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}=1.`, + ); + this.name = "LibsqlSidecarMissingError"; + } +} + +/** + * The connection to the run's libSQL sidecar from the environment. Throws `LibsqlSidecarMissingError` when the run script did not set the + * host variable (it does so only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`), so a test that was selected without its sidecar fails loudly + * instead of passing vacuously or connecting to a name that happens to resolve elsewhere. Reads only `env`. + */ +export function libsqlConnection(env: NodeJS.ProcessEnv = process.env): LibsqlConnection { + const host = env[LIBSQL.HOST_ENV]; + if (!host) throw new LibsqlSidecarMissingError(); + return { url: `http://${host}:${LIBSQL.PORT}`, token: LIBSQL.READ_WRITE_TOKEN }; +} + +/** The route of the Hrana-over-HTTP pipeline, the one the Turso plugin posts to. */ +export const LIBSQL_PIPELINE_PATH = "/v2/pipeline"; + +/** How long a direct call to the sidecar may take before it is abandoned: a local server answers in milliseconds. */ +const DIRECT_CALL_TIMEOUT_MS = 10_000; + +/** The answer of a direct pipeline call: the status line and the body parsed as JSON (or the text when it is not JSON). */ +export interface LibsqlDirectAnswer { + status: number; + statusText: string; + body: unknown; +} + +/** + * One `execute` of `sql` (then `close`) posted to the sidecar from the TEST process, with `token` as the bearer token or with no + * `Authorization` header when `token` is `undefined`. This is what the plugin sends, minus the plugin: it is the control that shows what the + * server itself answers (a real error with its code, a 401 body), which the plugin's own answer to the app then hides or changes. The + * runner reaches the sidecar by the same alias the app container does. + */ +export async function libsqlDirect(connection: Pick, sql: string, token?: string): Promise { + const response = await fetch(`${connection.url}${LIBSQL_PIPELINE_PATH}`, { + method: "POST", + headers: { "Content-Type": "application/json", ...(token === undefined ? {} : { Authorization: `Bearer ${token}` }) }, + body: JSON.stringify({ requests: [{ type: "execute", stmt: { sql } }, { type: "close" }] }), + signal: AbortSignal.timeout(DIRECT_CALL_TIMEOUT_MS), + }); + const text = await response.text(); + let body: unknown = text; + try { + body = JSON.parse(text); + } catch { + // not JSON: the text itself is the body + } + return { status: response.status, statusText: response.statusText, body }; +} diff --git a/e2e/tests/datasource/plugin-turso-libsql.spec.ts b/e2e/tests/datasource/plugin-turso-libsql.spec.ts new file mode 100644 index 0000000000..c460986ab8 --- /dev/null +++ b/e2e/tests/datasource/plugin-turso-libsql.spec.ts @@ -0,0 +1,464 @@ +import { randomBytes } from "node:crypto"; +import { connect } from "node:net"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, LIBSQL, TAGS } from "../../src/constants"; +import { appDsl, button, nodePluginQuery, stackItems } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { boundText, boundTextTestId, openSeededView } from "../../src/components/scenario"; +import { libsqlConnection, libsqlDirect, type LibsqlConnection } from "../../src/datasource/libsql"; +import { expect, test } from "../../src/fixtures"; + +/** + * D13: the Turso plugin of node-service (`server/node-service/src/plugins/turso/index.ts`, the plugin id `turso`) run against a REAL libSQL + * server, sqld, the sidecar of the run (`scripts/run-in-docker.sh` starts it only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`; image and + * authentication in the README, "libSQL sidecar"). D5 runs the same plugin against the echo's canned answers; here the answers are the + * server's own. Every connection of these tests goes to the sidecar: the data source URL is `http://:8080` from `E2E_LIBSQL_HOST` + * (plain HTTP, so the plugin's `libsql://` to `https://` rewrite does not apply), never a placeholder. Each test makes its own table, named + * by a per-test marker, so parallel tests share nothing; the server keeps every table until the run ends. + * + * "Direct" calls (`libsqlDirect`) post the same pipeline from the test process to the sidecar. They are the controls that show what the + * server itself answers, next to what the plugin makes of it for the app. + * + * Measured on the images `3.0.0-e2e` and `3.0.1-e2e` against sqld 0.24.33: + * - A cell is `{type, value}`: `integer` carries its value as a STRING, `float` as a number, `text` as text, `null` has no value, a `blob` + * carries `base64` and no `value`. The column's `decltype` is the declared type as written in the CREATE TABLE (its case is kept), + * `null` for an expression. + * - The plugin makes an `integer` a number (a `boolean` column, written in lower case, a boolean), a `float` a number, a `datetime` or `date` + * column's text a `Date` (an ISO string in the answer), a `null` `null`. A blob cell becomes a value of `undefined`, so the key is + * missing from the row (NSD-14 candidate). An integer beyond 2^53 is parsed with `parseInt` and loses its low digits (NSD-15 candidate). + * - A SQL error is answered by the server with HTTP 200 and `results[0] = { type: "error", error: { message, code } }`; the plugin prints it + * as `[object Object]` (NSD-1 candidate, the defect D5d shows against a canned answer). + * - A bad token is HTTP 401 `Unauthorized`; a read-only token that writes is HTTP 403 `Forbidden`; both fail the query with the plugin's + * `Endpoint returned : .` + * + * Not covered: the `libsql://` to `https://` rewrite of the URL (the sidecar speaks plain HTTP and the rewritten URL is https, so it cannot + * be exercised here); Turso's cloud features (branches, groups, per-database tokens); a stream with a baton (the plugin always closes). + */ +/** Candidate defect: an `error` result of the pipeline is printed as `${result.error}` (an object): the server's own message never reaches the app. */ +const ERROR_TEXT_DEFECT = { type: "defect", description: "NSD-1 candidate" } as const; +/** Candidate defect: the cell of a `blob` has `base64` and no `value`, so the plugin answers the column as `undefined`: the key is missing from the row. */ +const BLOB_DEFECT = { type: "defect", description: "NSD-14 candidate" } as const; +/** Candidate defect: an `integer` cell is parsed with `Number.parseInt`, so an integer the JavaScript number cannot hold exactly is rounded. */ +const BIG_INTEGER_DEFECT = { type: "defect", description: "NSD-15 candidate" } as const; + +/** What the plugin prints for an `error` result (measured): the error object is printed as `[object Object]`. */ +const MEASURED_ERROR_TEXT = "Cannot parse result, received error: [object Object]"; + +const HTTP_OK = 200; +const HTTP_UNAUTHORIZED = 401; +const HTTP_FORBIDDEN = 403; +const HTTP_NOT_FOUND = 404; +const QUERY_CODE_OK = "OK"; +const QUERY_CODE_FAILED = "FAILED"; +const MARKER_BYTES = 4; +const QUERY_ID = "q1"; +const QUERY_NAME = "q"; + +/** The plugin's text for a non-OK pipeline answer (`Failed to execute query. Endpoint returned : .`). */ +function endpointReturned(status: number, statusText: string): string { + return `Failed to execute query. Endpoint returned ${status}: ${statusText}.`; +} + +/** A token that is no JWT at all, for a data source whose token field holds anything. */ +const MALFORMED_TOKEN = "e2e-not-a-jwt"; + +/** The server's own answers to what these tests send (sqld 0.24.33): the `error` object of a failed statement, and the body of a refused request. */ +const SERVER_ERROR_CODES = { + PARSE: "SQL_PARSE_ERROR", + INPUT: "SQL_INPUT_ERROR", + CONSTRAINT: "SQLITE_CONSTRAINT", + MANY_STATEMENTS: "SQL_MANY_STATEMENTS", +} as const; +const SERVER_UNAUTHORIZED_BODY = { error: "Unauthorized: `The JWT is invalid`" }; +const SERVER_NO_HEADER_BODY = { error: "Unauthorized: `Expected authorization header but none given`" }; +const SERVER_READ_ONLY_BODY = { error: "Authorization forbidden: Current session doesn't not have Write permission to namespace default" }; + +/** A port of the sidecar's host where nothing listens: the control that a refused connection is seen as one. */ +const CLOSED_PORT = 8081; +const CONNECT_TIMEOUT_MS = 5000; + +/** The largest integer a JavaScript number holds exactly, plus one: the server stores it exactly, the plugin rounds it down to the even neighbour below. */ +const BEYOND_SAFE = "9007199254740993"; +const BEYOND_SAFE_AS_PARSED = 9007199254740992; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +/** A table name of this test only (an SQL identifier: letters, digits and underscores). */ +function uniqueTable(): string { + return `e2e_t_${uniqueMarker()}`; +} + +/** One saved query: the SQL, and whether the form's "Include raw" switch is on. */ +interface TursoQuery { + queryString: string; + includeRaw?: boolean; +} + +/** The data source fields of the sidecar over the recorded form body; `overrides` change the URL or the token. */ +function sidecarConfig(overrides: Partial = {}): LibsqlConnection { + return { ...libsqlConnection(), ...overrides }; +} + +async function tursoDatasource(page: Page, apiUser: RegisteredUser, overrides: Partial = {}): Promise { + return createNodePluginDatasource(page.request, { orgId: apiUser.orgId, recorded: recordedPluginDatasource("turso"), config: { ...sidecarConfig(overrides) } }); +} + +function savedQueries(datasourceId: string, queries: Record): ReturnType[] { + return Object.entries(queries).map(([id, query]) => + nodePluginQuery({ id, name: id, datasourceId, recorded: recordedPluginQuery("turso"), action: { queryString: query.queryString, includeRaw: query.includeRaw ?? false } }), + ); +} + +/** A saved app with one manual Turso query per entry of `queries` on one data source (not published: the draft runs with `viewMode: false`). */ +async function tursoApp(page: Page, apiUser: RegisteredUser, queries: Record, overrides: Partial = {}): Promise { + const datasourceId = await tursoDatasource(page, apiUser, overrides); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: "e2e-turso-libsql", dsl: appDsl([], { queries: savedQueries(datasourceId, queries) }) }); + return appId; +} + +async function runDraft(page: Page, appId: string, queryId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +function expectSucceeded(answer: RawAnswer): void { + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); +} + +function expectFailed(answer: RawAnswer, message: string): void { + expectRan(answer); + expect( + { success: envelopeOf(answer).success, queryCode: envelopeOf(answer).queryCode, message: envelopeOf(answer).message, data: envelopeOf(answer).data }, + "the query failed with the measured message", + ).toEqual({ success: false, queryCode: QUERY_CODE_FAILED, message, data: null }); +} + +/** The first result of a direct pipeline answer, which must be the HTTP 200 answer of the server. */ +function firstResultOf(answer: { status: number; body: unknown }): unknown { + expect(answer.status, "the direct call was answered with 200").toBe(HTTP_OK); + return (answer.body as { results: unknown[] }).results[0]; +} + +/** Runs setup SQL straight on the sidecar (test-owned tables only) and checks that the server accepted it. */ +async function setUpDirect(sql: string): Promise { + const answer = await libsqlDirect(libsqlConnection(), sql, libsqlConnection().token); + expect((firstResultOf(answer) as { type: string }).type, `the server executed: ${sql}`).toBe("ok"); +} + +/** How a TCP connection to `host:port` ended: `connected`, or the error code Node reports (`ECONNREFUSED`, ...). */ +async function tcpOutcome(host: string, port: number): Promise { + return new Promise((resolve) => { + const socket = connect({ host, port }); + socket.setTimeout(CONNECT_TIMEOUT_MS, () => { + socket.destroy(); + resolve("timeout"); + }); + socket.once("connect", () => { + socket.destroy(); + resolve("connected"); + }); + socket.once("error", (error: NodeJS.ErrnoException) => resolve(error.code ?? error.message)); + }); +} + +/** The rows of the seeded table of the type round trip, as the plugin answers them (a `datetime` text is a `Date`, here its ISO text). */ +const TYPED_ROWS = [ + { id: 1, name: "alpha", price: 1.5, active: true, born: "2024-01-02T03:04:05.000Z", note: null }, + { id: 2, name: "beta", price: 2, active: false, born: null, note: "second" }, +] as const; + +test.describe("Turso data source against a real libSQL server", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { + test("D13a: create, insert and select answer typed rows, in the order the SQL sorts them", async ({ page, apiUser }) => { + const table = uniqueTable(); + const appId = await tursoApp(page, apiUser, { + create: { queryString: `CREATE TABLE ${table} (id INTEGER PRIMARY KEY, name TEXT, price REAL, active boolean, born datetime, note TEXT)` }, + insertAlpha: { queryString: `INSERT INTO ${table} VALUES (1, 'alpha', 1.5, 1, '2024-01-02T03:04:05Z', NULL)` }, + insertBeta: { queryString: `INSERT INTO ${table} VALUES (2, 'beta', 2, 0, NULL, 'second')` }, + select: { queryString: `SELECT id, name, price, active, born, note FROM ${table} ORDER BY id` }, + }); + + const created = await runDraft(page, appId, "create"); + const empty = await runDraft(page, appId, "select"); + const alpha = await runDraft(page, appId, "insertAlpha"); + const beta = await runDraft(page, appId, "insertBeta"); + const rows = await runDraft(page, appId, "select"); + + expectSucceeded(created); + expect(envelopeOf(created).data, "a CREATE TABLE answers no rows").toEqual([]); + expectSucceeded(empty); + expect(envelopeOf(empty).data, "before the inserts the new table is empty").toEqual([]); + expectSucceeded(alpha); + expect(envelopeOf(alpha).data, "an INSERT answers no rows").toEqual([]); + expectSucceeded(beta); + expectSucceeded(rows); + // integer -> number, real -> number (2 stays 2), a lower-case `boolean` column -> boolean, `datetime` text -> Date (ISO text), NULL -> null + expect(envelopeOf(rows).data, "the two rows with every column mapped").toEqual(TYPED_ROWS); + }); + + test("D13b: includeRaw answers the values and the server's own result set", async ({ page, apiUser }) => { + const table = uniqueTable(); + await setUpDirect(`CREATE TABLE ${table} (id INTEGER PRIMARY KEY, name TEXT)`); + await setUpDirect(`INSERT INTO ${table} VALUES (7, 'raw')`); + const appId = await tursoApp(page, apiUser, { raw: { queryString: `SELECT id, name FROM ${table}`, includeRaw: true } }); + + const answer = await runDraft(page, appId, "raw"); + + expectSucceeded(answer); + const data = envelopeOf(answer).data as { values: unknown; raw: Record }; + expect(Object.keys(data).sort(), "both keys are present").toEqual(["raw", "values"]); + expect(data.values, "the values").toEqual([{ id: 7, name: "raw" }]); + // the cells are the server's: an integer's value is a STRING, the declared types are kept + expect(data.raw.cols, "the columns with their declared types").toEqual([ + { name: "id", decltype: "INTEGER" }, + { name: "name", decltype: "TEXT" }, + ]); + expect(data.raw.rows, "the cells as the server sends them").toEqual([[{ type: "integer", value: "7" }, { type: "text", value: "raw" }]]); + expect(Object.keys(data.raw).sort(), "the result set's fields").toEqual( + ["affected_row_count", "cols", "last_insert_rowid", "query_duration_ms", "replication_index", "rows", "rows_read", "rows_written"], + ); + expect(data.raw.affected_row_count, "a SELECT changes no row").toBe(0); + expect(typeof data.raw.query_duration_ms, "the server's own timing").toBe("number"); + }); + + test("D13c: a write answers no values, and its raw result counts the change and names the new row id", async ({ page, apiUser }) => { + const table = uniqueTable(); + await setUpDirect(`CREATE TABLE ${table} (id INTEGER PRIMARY KEY, name TEXT)`); + const appId = await tursoApp(page, apiUser, { + plain: { queryString: `INSERT INTO ${table} (name) VALUES ('first')` }, + raw: { queryString: `INSERT INTO ${table} (name) VALUES ('second')`, includeRaw: true }, + count: { queryString: `SELECT COUNT(*) AS n FROM ${table}` }, + }); + + const plain = await runDraft(page, appId, "plain"); + const raw = await runDraft(page, appId, "raw"); + const count = await runDraft(page, appId, "count"); + + expectSucceeded(plain); + expect(envelopeOf(plain).data, "an INSERT without includeRaw answers an empty list").toEqual([]); + expectSucceeded(raw); + const data = envelopeOf(raw).data as { values: unknown; raw: Record }; + expect(data.values, "an INSERT answers no values with includeRaw either").toEqual([]); + // the second insert took the next id: `last_insert_rowid` is a string like every 64-bit integer of the protocol + expect({ affected: data.raw.affected_row_count, lastId: data.raw.last_insert_rowid, rows: data.raw.rows, cols: data.raw.cols }, "the write's counters").toEqual({ + affected: 1, + lastId: "2", + rows: [], + cols: [], + }); + expectSucceeded(count); + expect(envelopeOf(count).data, "both inserts reached the table (a COUNT is an expression: no declared type, still a number)").toEqual([{ n: 2 }]); + }); + + test("D13d: a blob cell is dropped from the row", { annotation: BLOB_DEFECT }, async ({ page, apiUser }) => { + const table = uniqueTable(); + await setUpDirect(`CREATE TABLE ${table} (id INTEGER PRIMARY KEY, data BLOB)`); + await setUpDirect(`INSERT INTO ${table} VALUES (1, x'00ff10')`); + const appId = await tursoApp(page, apiUser, { + values: { queryString: `SELECT id, data FROM ${table}` }, + raw: { queryString: `SELECT id, data FROM ${table}`, includeRaw: true }, + }); + + const values = await runDraft(page, appId, "values"); + const raw = await runDraft(page, appId, "raw"); + + expectSucceeded(raw); + // positive control: the server did send the blob (base64 of the bytes 00 ff 10), and the plugin read its other cell + const rawData = envelopeOf(raw).data as { raw: { rows: unknown } }; + expect(rawData.raw.rows, "the server's cells").toEqual([[{ type: "integer", value: "1" }, { type: "blob", base64: "AP8Q" }]]); + expectSucceeded(values); + // NSD-14 candidate: the blob has no `value`, so the column is `undefined` and the key is missing + expect(envelopeOf(values).data, "the row holds the id and not the blob").toEqual([{ id: 1 }]); + }); + + test("D13e: an integer beyond 2^53 is rounded by the plugin and exact in the server's result", { annotation: BIG_INTEGER_DEFECT }, async ({ page, apiUser }) => { + const appId = await tursoApp(page, apiUser, { + values: { queryString: `SELECT ${BEYOND_SAFE} AS big` }, + raw: { queryString: `SELECT ${BEYOND_SAFE} AS big`, includeRaw: true }, + }); + + const values = await runDraft(page, appId, "values"); + const raw = await runDraft(page, appId, "raw"); + + expectSucceeded(raw); + const rawData = envelopeOf(raw).data as { raw: { rows: unknown } }; + expect(rawData.raw.rows, "positive control: the server holds the exact integer, as a string").toEqual([[{ type: "integer", value: BEYOND_SAFE }]]); + expectSucceeded(values); + // NSD-15 candidate: 9007199254740993 is not a JavaScript number; parseInt rounds it + expect(envelopeOf(values).data, "the plugin's number").toEqual([{ big: BEYOND_SAFE_AS_PARSED }]); + }); + + test("D13f: a SQL error of the server fails the query with [object Object]", { annotation: ERROR_TEXT_DEFECT }, async ({ page, apiUser }) => { + const table = uniqueTable(); + const sidecar = libsqlConnection(); + const appId = await tursoApp(page, apiUser, { + create: { queryString: `CREATE TABLE ${table} (id INTEGER PRIMARY KEY)` }, + insert: { queryString: `INSERT INTO ${table} VALUES (1)` }, + syntax: { queryString: "SELEC 1" }, + column: { queryString: `SELECT nope FROM ${table}` }, + duplicate: { queryString: `INSERT INTO ${table} VALUES (1)` }, + many: { queryString: "SELECT 1; SELECT 2" }, + control: { queryString: `SELECT id FROM ${table}` }, + }); + expectSucceeded(await runDraft(page, appId, "create")); + expectSucceeded(await runDraft(page, appId, "insert")); + + // what the server itself says for each statement: a real message and a code (the controls that the error exists and is specific) + const serverErrors: Record = {}; + for (const [name, sql] of Object.entries({ syntax: "SELEC 1", column: `SELECT nope FROM ${table}`, duplicate: `INSERT INTO ${table} VALUES (1)`, many: "SELECT 1; SELECT 2" })) { + serverErrors[name] = firstResultOf(await libsqlDirect(sidecar, sql, sidecar.token)); + } + expect(serverErrors, "the server's own errors").toEqual({ + syntax: { type: "error", error: { message: "SQL string could not be parsed: syntax error around L1:6: `SELEC`", code: SERVER_ERROR_CODES.PARSE } }, + column: { type: "error", error: { message: "SQL input error: no such column: nope (at offset 7)", code: SERVER_ERROR_CODES.INPUT } }, + duplicate: { type: "error", error: { message: `SQLite error: UNIQUE constraint failed: ${table}.id`, code: SERVER_ERROR_CODES.CONSTRAINT } }, + many: { type: "error", error: { message: "SQL string contains more than one statement", code: SERVER_ERROR_CODES.MANY_STATEMENTS } }, + }); + + expectSucceeded(await runDraft(page, appId, "control")); + // NSD-1 candidate: whatever the server said, the app gets the same text + for (const name of ["syntax", "column", "duplicate", "many"]) { + expectFailed(await runDraft(page, appId, name), MEASURED_ERROR_TEXT); + } + }); + + test("D13g: a token the server does not accept fails the query with the status, and the right token on the same query succeeds", async ({ page, apiUser }) => { + const table = uniqueTable(); + await setUpDirect(`CREATE TABLE ${table} (id INTEGER PRIMARY KEY)`); + await setUpDirect(`INSERT INTO ${table} VALUES (1)`); + const queries = { read: { queryString: `SELECT id FROM ${table}` } }; + const rightApp = await tursoApp(page, apiUser, queries); + const foreignApp = await tursoApp(page, apiUser, queries, { token: LIBSQL.FOREIGN_TOKEN }); + const malformedApp = await tursoApp(page, apiUser, queries, { token: MALFORMED_TOKEN }); + const sidecar = libsqlConnection(); + + const right = await runDraft(page, rightApp, "read"); + const foreign = await runDraft(page, foreignApp, "read"); + const malformed = await runDraft(page, malformedApp, "read"); + + expectSucceeded(right); + expect(envelopeOf(right).data, "positive control: the sidecar's own token reads the row").toEqual([{ id: 1 }]); + expectFailed(foreign, endpointReturned(HTTP_UNAUTHORIZED, "Unauthorized")); + expectFailed(malformed, endpointReturned(HTTP_UNAUTHORIZED, "Unauthorized")); + // the server's reason, from direct calls: a JWT it cannot verify (signed by another key, or no JWT) and no header at all + const direct = [ + await libsqlDirect(sidecar, `SELECT id FROM ${table}`, LIBSQL.FOREIGN_TOKEN), + await libsqlDirect(sidecar, `SELECT id FROM ${table}`, MALFORMED_TOKEN), + await libsqlDirect(sidecar, `SELECT id FROM ${table}`), + ]; + expect( + direct.map((answer) => ({ status: answer.status, body: answer.body })), + "the server's answers to the three refused calls", + ).toEqual([ + { status: HTTP_UNAUTHORIZED, body: SERVER_UNAUTHORIZED_BODY }, + { status: HTTP_UNAUTHORIZED, body: SERVER_UNAUTHORIZED_BODY }, + { status: HTTP_UNAUTHORIZED, body: SERVER_NO_HEADER_BODY }, + ]); + }); + + test("D13h: a read-only token reads and cannot write: 403 fails the query and no row is written", async ({ page, apiUser }) => { + const table = uniqueTable(); + await setUpDirect(`CREATE TABLE ${table} (id INTEGER PRIMARY KEY)`); + await setUpDirect(`INSERT INTO ${table} VALUES (1)`); + const queries = { + read: { queryString: `SELECT id FROM ${table} ORDER BY id` }, + write: { queryString: `INSERT INTO ${table} VALUES (2)` }, + }; + const readOnlyApp = await tursoApp(page, apiUser, queries, { token: LIBSQL.READ_ONLY_TOKEN }); + const readWriteApp = await tursoApp(page, apiUser, queries); + + const read = await runDraft(page, readOnlyApp, "read"); + const refused = await runDraft(page, readOnlyApp, "write"); + const stillOne = await runDraft(page, readWriteApp, "read"); + + expectSucceeded(read); + expect(envelopeOf(read).data, "the read-only token reads").toEqual([{ id: 1 }]); + expectFailed(refused, endpointReturned(HTTP_FORBIDDEN, "Forbidden")); + expectSucceeded(stillOne); + expect(envelopeOf(stillOne).data, "the refused INSERT wrote nothing").toEqual([{ id: 1 }]); + // positive control: the read-write token's INSERT of the same row works, so the refusal was about the token + expectSucceeded(await runDraft(page, readWriteApp, "write")); + expect(envelopeOf(await runDraft(page, readWriteApp, "read")).data, "the read-write token writes").toEqual([{ id: 1 }, { id: 2 }]); + const sidecar = libsqlConnection(); + expect(await libsqlDirect(sidecar, `INSERT INTO ${table} VALUES (3)`, LIBSQL.READ_ONLY_TOKEN), "the server's own answer to the read-only write").toMatchObject({ + status: HTTP_FORBIDDEN, + body: SERVER_READ_ONLY_BODY, + }); + }); + + test("D13i: the published view shows a row of the server after a click", async ({ page, apiUser }) => { + const table = uniqueTable(); + const rowName = `row-${uniqueMarker()}`; + await setUpDirect(`CREATE TABLE ${table} (id INTEGER PRIMARY KEY, name TEXT)`); + await setUpDirect(`INSERT INTO ${table} VALUES (1, '${rowName}')`); + const datasourceId = await tursoDatasource(page, apiUser); + // before the first run `q.data` is not a list + const expression = `{{${QUERY_NAME}.data ? ${QUERY_NAME}.data[0].name : ""}}`; + const view = await openSeededView( + page, + apiUser.orgId, + "e2e-turso-libsql-view", + stackItems([ + button({ id: "b1", name: "button1", text: "Run", testId: "e2e-turso-libsql-run", onClickQuery: QUERY_NAME }), + boundText({ id: "t1", name: "label", expression }), + // `success` also reads `true` before the first run (measured, D5e), so only the state after the click proves anything + boundText({ id: "t2", name: "succeeded", expression: `{{String(${QUERY_NAME}.success)}}` }), + ]), + { queries: [nodePluginQuery({ id: QUERY_ID, name: QUERY_NAME, datasourceId, recorded: recordedPluginQuery("turso"), action: { queryString: `SELECT name FROM ${table}` } })] }, + ); + + await expect(view.byTestId(boundTextTestId("label")), "before the click the text is empty").toHaveText(""); + await view.buttonByTestId("e2e-turso-libsql-run").click(); + await expect(view.byTestId(boundTextTestId("succeeded")), "after the click the query succeeded").toHaveText("true"); + await expect(view.byTestId(boundTextTestId("label")), "after the click the text shows the server's row").toHaveText(rowName); + }); + + test("D13j: a trailing slash after the URL is a 404 of the server, the same URL without it works", async ({ page, apiUser }) => { + const sidecar = libsqlConnection(); + const queries = { select: { queryString: "SELECT 1 AS one" } }; + const plainApp = await tursoApp(page, apiUser, queries); + const slashApp = await tursoApp(page, apiUser, queries, { url: `${sidecar.url}/` }); + + const plain = await runDraft(page, plainApp, "select"); + const slash = await runDraft(page, slashApp, "select"); + + expectSucceeded(plain); + expect(envelopeOf(plain).data, "positive control: the URL without the slash").toEqual([{ one: 1 }]); + // the plugin appends `/v2/pipeline` to the text it was given: `http://host:8080//v2/pipeline` is a path the server does not have + expectFailed(slash, endpointReturned(HTTP_NOT_FOUND, "Not Found")); + expect((await libsqlDirect({ url: `${sidecar.url}/` }, "SELECT 1", sidecar.token)).status, "the server's own status for the doubled slash").toBe(HTTP_NOT_FOUND); + }); + + test("D13k: the runner reaches the sidecar over HTTP and TCP, and a closed port of the same host is refused", async () => { + const sidecar = libsqlConnection(); + const host = new URL(sidecar.url).hostname; + + const answer = await libsqlDirect(sidecar, "SELECT 1 AS one", sidecar.token); + + expect(firstResultOf(answer), "the server's answer to SELECT 1").toMatchObject({ + type: "ok", + response: { type: "execute", result: { cols: [{ name: "one", decltype: null }], rows: [[{ type: "integer", value: "1" }]] } }, + }); + expect(await tcpOutcome(host, LIBSQL.PORT), "the sidecar's HTTP port").toBe("connected"); + expect(await tcpOutcome(host, CLOSED_PORT), "positive control: a port nothing listens on is refused").toBe("ECONNREFUSED"); + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index 9beeb47fbd..b5ffcd1e49 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -1,10 +1,11 @@ +import { createPublicKey, verify } from "node:crypto"; import { readFileSync } from "node:fs"; import { createServer, type IncomingMessage, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import { join } from "node:path"; import { expect, test } from "@playwright/test"; import { createNodePluginDatasource, LowcoderApiError, nodePluginDatasourceBody, pluginDynamicConfigRaw, testDatasourceRaw } from "../../src/api/client"; -import { API_OK, API_PATHS, FIREBIRD, orgDatasourceTypesPath, RUN_FLAGS, TAGS } from "../../src/constants"; +import { API_OK, API_PATHS, FIREBIRD, LIBSQL, orgDatasourceTypesPath, RUN_FLAGS, TAGS } from "../../src/constants"; import { nodePluginQuery } from "../../src/dsl/builders"; import { parsePluginRecording, @@ -16,6 +17,7 @@ import { type RecordedPluginQuery, } from "../../src/dsl/recorded"; import { FIREBIRD_ITEMS, firebirdConnection, FirebirdSidecarMissingError } from "../../src/datasource/firebird"; +import { LIBSQL_PIPELINE_PATH, libsqlConnection, libsqlDirect, LibsqlSidecarMissingError } from "../../src/datasource/libsql"; import { NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL, NODE_PLUGIN_IDS, @@ -585,6 +587,8 @@ test.describe("node-service data source request helpers", { tag: [TAGS.NODE_SERV /** The alias the run script gives the Firebird sidecar, the host of the recorded form body. */ const FIREBIRD_ALIAS = "e2e-firebird"; +/** The alias the run script gives the libSQL sidecar. */ +const LIBSQL_ALIAS = "e2e-libsql"; /** The text of `scripts/run-in-docker.sh` and of `fixtures/firebird/init.sql`. */ const RUN_SCRIPT = readFileSync(join(__dirname, "..", "..", "scripts", "run-in-docker.sh"), "utf8"); @@ -688,4 +692,91 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = expect(RUN_SCRIPT, "the cleanup trap removes the container").toMatch(/docker rm -f [^\n]*"\$FIREBIRD_CONTAINER"/); expect(RUN_SCRIPT, "another stack profile with the flag is refused").toContain("E2E_INCLUDE_NODE_SERVICE_SIDECARS needs E2E_STACK_PROFILE=$DEFAULT_PROFILE"); }); + + test("libsqlConnection reads the host from the environment and builds a plain-HTTP URL with the read-write token", () => { + expect(libsqlConnection({ [LIBSQL.HOST_ENV]: LIBSQL_ALIAS })).toEqual({ url: `http://${LIBSQL_ALIAS}:${LIBSQL.PORT}`, token: LIBSQL.READ_WRITE_TOKEN }); + }); + + test("libsqlConnection throws a named error that names the variable and the flag when the host is unset or empty", () => { + for (const env of [{}, { [LIBSQL.HOST_ENV]: "" }]) { + expect(() => libsqlConnection(env), `env ${JSON.stringify(env)}`).toThrow(LibsqlSidecarMissingError); + expect(() => libsqlConnection(env)).toThrow(LIBSQL.HOST_ENV); + expect(() => libsqlConnection(env)).toThrow(`${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}=1`); + } + }); + + test("the run script's libSQL values equal LIBSQL in the constants", () => { + expect(scriptConstant("LIBSQL_ALIAS"), "alias").toBe(LIBSQL_ALIAS); + expect(Number(RUN_SCRIPT.match(/^readonly LIBSQL_PORT=(\d+)$/m)?.[1]), "port").toBe(LIBSQL.PORT); + expect(scriptConstant("LIBSQL_JWT_PUBLIC_KEY"), "the public key sqld is given").toBe(LIBSQL.JWT_PUBLIC_KEY); + expect(scriptConstant("LIBSQL_TOKEN"), "the token of the readiness call is the read-write one").toBe(LIBSQL.READ_WRITE_TOKEN); + expect(scriptConstant("DEFAULT_LIBSQL_IMAGE"), "the image is pinned by tag and digest").toMatch(/^ghcr\.io\/tursodatabase\/libsql-server:v\d+\.\d+\.\d+@sha256:[0-9a-f]{64}$/); + expect(scriptConstant("LIBSQL_DATA_DIR"), "the data directory the image declares a volume").toBe("/var/lib/sqld"); + expect(RUN_SCRIPT, "the data directory is a tmpfs, so no anonymous volume outlives the run").toContain('--tmpfs "$LIBSQL_DATA_DIR"'); + }); + + test("the three tokens are JWTs of the claims they are named for, and only the two sidecar tokens verify under the sidecar's key", () => { + const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: LIBSQL.JWT_PUBLIC_KEY }, format: "jwk" }); + const check = (token: string): { signed: boolean; claims: unknown } => { + const [header, payload, signature] = token.split(".") as [string, string, string]; + return { + signed: verify(null, Buffer.from(`${header}.${payload}`), key, Buffer.from(signature, "base64url")), + claims: JSON.parse(Buffer.from(payload, "base64url").toString("utf8")), + }; + }; + expect(check(LIBSQL.READ_WRITE_TOKEN), "read-write token").toEqual({ signed: true, claims: { a: "rw" } }); + expect(check(LIBSQL.READ_ONLY_TOKEN), "read-only token").toEqual({ signed: true, claims: { a: "ro" } }); + expect(check(LIBSQL.FOREIGN_TOKEN), "a token of another key: well-formed, same claims, not signed by the sidecar's key").toEqual({ signed: false, claims: { a: "rw" } }); + }); + + test("the run script starts, waits for and passes the libSQL sidecar only under the flag, next to the Firebird one", () => { + const lines = RUN_SCRIPT.split("\n"); + for (const fn of ["start_libsql", "wait_for_libsql"]) { + const calls = lines.map((line, index) => ({ line, index })).filter(({ line }) => line.trim() === fn); + expect(calls, `${fn} is called exactly once`).toHaveLength(1); + const call = calls[0] as { index: number }; + expect(lines[call.index - 1]?.trim(), `${fn} is the first line of an if node_service_sidecars_enabled block`).toBe("if node_service_sidecars_enabled; then"); + expect(lines[call.index + 1]?.trim(), `${fn} is the only line of that block`).toBe("fi"); + } + const startBody = /start_libsql\(\) \{[\s\S]*?\n\}/.exec(RUN_SCRIPT)?.[0] ?? ""; + // `+=`, so that the Firebird entries set before stay: both sidecars are passed to the app container and the runner + expect(startBody, "start_libsql appends the runner's host variable").toContain(`SIDECAR_RUNNER_ENV+=(-e "${LIBSQL.HOST_ENV}=`); + expect(startBody, "start_libsql appends the --add-host entry").toContain("SIDECAR_ADD_HOST+=(--add-host"); + const codeLines = lines.filter((line) => !line.trim().startsWith("#")).join("\n"); + expect(codeLines.match(new RegExp(LIBSQL.HOST_ENV, "g")), "the host variable is named once in the script's code, in start_libsql").toHaveLength(1); + expect(RUN_SCRIPT, "the cleanup trap removes the container").toMatch(/docker rm -f [^\n]*"\$LIBSQL_CONTAINER"/); + expect(RUN_SCRIPT, "the app container and the runner both get the add-host entries").toMatch(/--add-host "\$\{ECHO_ALIAS\}:\$\{ECHO_IP\}" "\$\{SIDECAR_ADD_HOST\[@\]\}"[\s\S]*--add-host "\$\{ECHO_ALIAS\}:\$\{ECHO_IP\}" "\$\{SIDECAR_ADD_HOST\[@\]\}"/); + }); + + test("libsqlDirect posts one execute and one close with the bearer token, sends no header without a token, and parses a JSON or a text body", async () => { + const received: { method?: string; url?: string; authorization?: string; body: unknown }[] = []; + const server: Server = createServer((request: IncomingMessage, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + received.push({ method: request.method, url: request.url, authorization: request.headers.authorization, body: JSON.parse(Buffer.concat(chunks).toString("utf8")) }); + if (request.headers.authorization === undefined) { + response.writeHead(401, "Unauthorized").end("plain text, not JSON"); + } else { + response.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify({ results: [] })); + } + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + try { + const withToken = await libsqlDirect({ url }, "SELECT 1", "tok"); + const withoutToken = await libsqlDirect({ url }, "SELECT 2"); + + expect(withToken, "a JSON body is parsed").toEqual({ status: 200, statusText: "OK", body: { results: [] } }); + expect(withoutToken, "a body that is not JSON stays text").toEqual({ status: 401, statusText: "Unauthorized", body: "plain text, not JSON" }); + expect(received.map(({ method, url: path, authorization }) => ({ method, path, authorization })), "method, path and header of both calls").toEqual([ + { method: "POST", path: LIBSQL_PIPELINE_PATH, authorization: "Bearer tok" }, + { method: "POST", path: LIBSQL_PIPELINE_PATH, authorization: undefined }, + ]); + expect(received[0]?.body, "the pipeline the plugin sends").toEqual({ requests: [{ type: "execute", stmt: { sql: "SELECT 1" } }, { type: "close" }] }); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }); }); diff --git a/e2e/tests/foundation/run-selection.spec.ts b/e2e/tests/foundation/run-selection.spec.ts index 6e07609f94..44cf749f56 100644 --- a/e2e/tests/foundation/run-selection.spec.ts +++ b/e2e/tests/foundation/run-selection.spec.ts @@ -566,8 +566,9 @@ test.describe("run selection: the node-service sidecar tests are opt-in", () => }); }); -/** The name of the helper whose use makes a spec need the Firebird sidecar, and the tag every test of such a spec must wear. */ -const SIDECAR_HELPER = "firebirdConnection"; +/** The names of the helpers whose use makes a spec need a sidecar (Firebird, libSQL), and the tag every test of such a spec must wear. */ +const SIDECAR_HELPERS = ["firebirdConnection", "libsqlConnection"] as const; +const SIDECAR_HELPER = SIDECAR_HELPERS[0]; const SIDECAR_TAG_KEY = "NODE_SERVICE_SIDECAR"; /** True when the expression, or any expression inside it, is `TAGS.NODE_SERVICE_SIDECAR` or the string `"@node-service-sidecar"`. Comments are no nodes. */ @@ -588,14 +589,14 @@ function detailsTagWithSidecar(details: ts.Expression): boolean { } /** - * The tests of a spec source that does not wear `TAGS.NODE_SERVICE_SIDECAR`, when the source uses `firebirdConnection` (a spec that needs the + * The tests of a spec source that does not wear `TAGS.NODE_SERVICE_SIDECAR`, when the source uses a sidecar helper (`firebirdConnection` or `libsqlConnection`; a spec that needs the * sidecar: untagged, its tests would run in the default run, where the sidecar is not started). A source that does not use the helper * reports nothing. A tag on an enclosing `test.describe*(title, details, body)` counts for every test inside. Each result is `line `. * Limits: the same as `untaggedSuperAdminTests` (a `test` passed through a parameter is not recognised, a tag through a variable is not followed). */ function untaggedSidecarTests(source: string, fileName = "synthetic.spec.ts"): string[] { const file = ts.createSourceFile(fileName, source, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS); - if (!source.includes(`${SIDECAR_HELPER}(`)) return []; + if (!SIDECAR_HELPERS.some((helper) => source.includes(`${helper}(`))) return []; const untagged: string[] = []; const testNames = localTestNames(file); const visit = (node: ts.Node, tagged: boolean): void => { @@ -622,19 +623,19 @@ function untaggedSidecarTests(source: string, fileName = "synthetic.spec.ts"): s return untagged; } -test.describe("run selection: every test that needs the Firebird sidecar carries the opt-in tag", () => { - test("every spec that uses firebirdConnection tags all its tests with TAGS.NODE_SERVICE_SIDECAR, and the Firebird spec does use it", () => { +test.describe("run selection: every test that needs a sidecar carries the opt-in tag", () => { + test("every spec that uses a sidecar helper tags all its tests with TAGS.NODE_SERVICE_SIDECAR, and the Firebird and libSQL specs do use one", () => { const untagged: string[] = []; const users: string[] = []; for (const file of specFilesUnder(join(__dirname, ".."))) { const source = readFileSync(file, "utf8"); if (file.includes(`${join("tests", "foundation")}`)) continue; - if (source.includes(`${SIDECAR_HELPER}(`)) users.push(file); + if (SIDECAR_HELPERS.some((helper) => source.includes(`${helper}(`))) users.push(file); untagged.push(...untaggedSidecarTests(source, file).map((entry) => `${file}: ${entry}`)); } - expect(users.map((file) => file.split("tests/")[1]), "the specs that use the helper (a positive control that the guard looks at the Firebird spec)").toEqual(["datasource/plugin-firebird.spec.ts"]); - expect(untagged, "tests of a Firebird spec without TAGS.NODE_SERVICE_SIDECAR (they would run, and fail, in the default run)").toEqual([]); + expect(users.map((file) => file.split("tests/")[1]), "the specs that use the helper (a positive control that the guard looks at the Firebird and the libSQL spec)").toEqual(["datasource/plugin-firebird.spec.ts", "datasource/plugin-turso-libsql.spec.ts"]); + expect(untagged, "tests of a sidecar spec without TAGS.NODE_SERVICE_SIDECAR (they would run, and fail, in the default run)").toEqual([]); }); test("the guard accepts a describe tag and a test tag, and reports an untagged test, a tag in a comment or a title, and a tag through a variable", () => { @@ -646,5 +647,7 @@ test.describe("run selection: every test that needs the Firebird sidecar carries expect(untaggedSidecarTests(`${use}// TAGS.NODE_SERVICE_SIDECAR\ntest("uses @node-service-sidecar in its title", async () => {});`), "comment and title").toEqual(["line 3"]); expect(untaggedSidecarTests(`${use}const D = { tag: [TAGS.NODE_SERVICE_SIDECAR] };\ntest("a", D, async () => {});`), "a variable is not followed").toEqual(["line 3"]); expect(untaggedSidecarTests(`test("a", async () => {});`), "a spec that does not use the helper is not asked").toEqual([]); + expect(untaggedSidecarTests(`const c = libsqlConnection();\ntest("a", async () => {});`), "the libSQL helper is asked too").toEqual(["line 2"]); + expect(untaggedSidecarTests(`const c = libsqlConnection();\ntest.describe("g", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { test("a", async () => {}); });`), "and accepts its describe tag").toEqual([]); }); }); From 6472758727374e86ada5279a7294095da624964b Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Tue, 24 Nov 2026 22:57:27 +0100 Subject: [PATCH 16/20] test: add an opt-in CouchDB server sidecar and CouchDB scenarios against it With E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 the run script now also starts a pinned Apache CouchDB server next to the Firebird and libSQL ones, creates its system databases through the real API, waits until they are listed, makes it reachable from the app container and the test runner, and removes it on exit even when the run fails. Without the flag nothing extra is started and the tests are neither listed nor run. The readiness probes of all three sidecars now have a time limit per request, so a stalled request cannot outlast the startup timeout. The CouchDB probe accepts only the documented status codes. Adds scenarios that run the CouchDB plugin against the real server: database create, list, info and delete, document revisions, conflicts, missing databases and documents, a wrong password, the conditional-read header, query parameters reaching the server, the published view after a click, reachability from the runner and account lockout. HTTP error answers that carry a body are reported as success; this is characterised and annotated as a defect candidate, as is a required header that makes a matching ETag fail. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 12 +- e2e/README.md | 42 +- .../plugins/couchdb/couchdbDeleteQuery.json | 15 + .../couchdb/couchdbDocDeleteQuery.json | 19 + .../couchdb/couchdbDocGetAllQuery.json | 42 ++ .../plugins/couchdb/couchdbDocGetQuery.json | 29 + .../plugins/couchdb/couchdbDocPutQuery.json | 21 + .../dsl/plugins/couchdb/couchdbGetQuery.json | 15 + .../dsl/plugins/couchdb/couchdbPutQuery.json | 18 + e2e/scripts/run-in-docker.sh | 104 ++- e2e/src/constants.ts | 22 +- e2e/src/datasource/couchdb.ts | 93 +++ e2e/src/run-selection.ts | 2 +- e2e/tests/datasource/plugin-couchdb.spec.ts | 706 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 190 ++++- e2e/tests/foundation/run-selection.spec.ts | 16 +- 16 files changed, 1309 insertions(+), 37 deletions(-) create mode 100644 e2e/fixtures/dsl/plugins/couchdb/couchdbDeleteQuery.json create mode 100644 e2e/fixtures/dsl/plugins/couchdb/couchdbDocDeleteQuery.json create mode 100644 e2e/fixtures/dsl/plugins/couchdb/couchdbDocGetAllQuery.json create mode 100644 e2e/fixtures/dsl/plugins/couchdb/couchdbDocGetQuery.json create mode 100644 e2e/fixtures/dsl/plugins/couchdb/couchdbDocPutQuery.json create mode 100644 e2e/fixtures/dsl/plugins/couchdb/couchdbGetQuery.json create mode 100644 e2e/fixtures/dsl/plugins/couchdb/couchdbPutQuery.json create mode 100644 e2e/src/datasource/couchdb.ts create mode 100644 e2e/tests/datasource/plugin-couchdb.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index 39fb48cacd..00b8107517 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,8 +129,8 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `tests/datasource/plugin-supabase-storage.spec.ts`, D11; `tests/datasource/plugin-firebird.spec.ts`, D12, and `tests/datasource/plugin-turso-libsql.spec.ts`, D13, which also wear the opt-in tag of the next bullet; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. -- `@node-service-sidecar`: a node-service data source test that needs a sidecar of its own, because the plugin does not speak HTTP (Firebird, `tests/datasource/plugin-firebird.spec.ts`, D12) or because a real server adds what canned echo answers cannot (a libSQL server for the Turso plugin, `tests/datasource/plugin-turso-libsql.spec.ts`, D13); `TAGS.NODE_SERVICE_SIDECAR`. Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of the default run (neither listed nor run, and `run-in-docker.sh` starts no such container), in only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` (default stack only). A spec that calls `firebirdConnection()` or `libsqlConnection()` must tag every test with it (a guard in `foundation/run-selection.spec.ts` parses the spec: write `{ tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }` on the describe or the test, not through a variable). Never put the tag text in a test title: the default `grepInvert` matches titles too and would drop the test. The helper that reads a sidecar's host variable throws when it is unset, so a test selected without its sidecar fails loudly. Both sidecars start together under the one flag; later sidecars add their container under it too. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `tests/datasource/plugin-supabase-storage.spec.ts`, D11; `tests/datasource/plugin-firebird.spec.ts`, D12, `tests/datasource/plugin-turso-libsql.spec.ts`, D13, and `tests/datasource/plugin-couchdb.spec.ts`, D14, which also wear the opt-in tag of the next bullet; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service-sidecar`: a node-service data source test that needs a real server of its own to be pointed at: either the echo cannot serve the plugin's protocol (Firebird, a wire protocol, `tests/datasource/plugin-firebird.spec.ts`, D12) or the echo's canned answers say nothing about the real server's behaviour (a libSQL server for the Turso plugin, `tests/datasource/plugin-turso-libsql.spec.ts`, D13, and a CouchDB server for the CouchDB plugin, `tests/datasource/plugin-couchdb.spec.ts`, D14); `TAGS.NODE_SERVICE_SIDECAR`. Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of the default run (neither listed nor run, and `run-in-docker.sh` starts no such container), in only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` (default stack only). A spec that calls `firebirdConnection()`, `libsqlConnection()` or `couchdbConnection()` must tag every test with it (a guard in `foundation/run-selection.spec.ts` parses the spec: write `{ tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }` on the describe or the test, not through a variable). Never put the tag text in a test title: the default `grepInvert` matches titles too and would drop the test. The helper that reads a sidecar's host variable throws when it is unset, so a test selected without its sidecar fails loudly. All three sidecars start together under the one flag; later sidecars add their container under it too. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). @@ -171,9 +171,9 @@ MUST NOT: `test-results`, `playwright-report`), and do not run `playwright test` directly while a stack of this checkout runs. - Edit anything in `e2e/evidence/` (git-ignored, local). Do not cite it as if it were in git. - Reach a real external host, switch the guard off, or add a route that allows another origin. Only `@npm` tests need - the app container to reach the npm registry. The places the backend may be pointed at are the run's own echo sidecar (`echo` fixture, `src/security/echo.ts`) and, only in a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, the opt-in node-service sidecars: the Firebird sidecar (`firebirdConnection()`, `src/datasource/firebird.ts`) and the libSQL server sidecar (`libsqlConnection()`, `src/datasource/libsql.ts`). Later opt-in sidecars add their names to this sentence. Never give a data source or a registry entry any other URL, and never rely on a placeholder host failing to resolve: every connection of a sidecar test goes to the sidecar. + the app container to reach the npm registry. The places the backend may be pointed at are the run's own echo sidecar (`echo` fixture, `src/security/echo.ts`) and, only in a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, the opt-in node-service sidecars: the Firebird sidecar (`firebirdConnection()`, `src/datasource/firebird.ts`), the libSQL server sidecar (`libsqlConnection()`, `src/datasource/libsql.ts`) and the CouchDB sidecar (`couchdbConnection()`, `src/datasource/couchdb.ts`). Later opt-in sidecars add their names to this sentence. Never give a data source or a registry entry any other URL, and never rely on a placeholder host failing to resolve: every connection of a sidecar test goes to the sidecar. - Import `test` from `@playwright/test` in a spec that opens a page or uses the stack: the network guard exists only in the `test` of `src/fixtures.ts` (accepted exception for stack-free unit specs below). -- Commit secrets. The PostgreSQL password in `src/constants.ts` is the throw-away one of the sidecar. The Firebird password in `src/constants.ts` is likewise the throw-away one of its own sidecar, and so are the libSQL tokens (`LIBSQL`): signed with a key pair generated once, whose private half was thrown away. +- Commit secrets. The PostgreSQL password in `src/constants.ts` is the throw-away one of the sidecar. The Firebird password in `src/constants.ts` is likewise the throw-away one of its own sidecar, and so are the libSQL tokens (`LIBSQL`): signed with a key pair generated once, whose private half was thrown away, and the CouchDB admin of its sidecar (`COUCHDB`). - Let the super admin's password (`E2E_SUPERUSER_PASSWORD`, new every run, set by `run-in-docker.sh`) reach a command line, log, trace, report, test title, annotation or error message; keep `set -x` off in the script. Never give the password to a matcher as the expected or received value (`expect(text).not.toContain(password)` prints it when it fails): assert `text.includes(password)` is `false`. The sign-in lives in an automatic worker fixture (`superAdminState`) because a request context created inside a test lands in its trace; do not sign the super admin in from a test or a helper, and create no request context in a helper. Every test that uses the `superAdmin` fixture carries `TAGS.SUPERADMIN` (a guard in `foundation/run-selection.spec.ts` checks it by parsing the spec with the TypeScript compiler: write the tag as `TAGS.SUPERADMIN` in the test's or its describe's details, a mention in a comment or title does not count). The super admin is ONE account shared by all workers: never switch its workspace or change its password. It hangs once the stack holds more than about 420 workspaces (README, security section): the SEC-R16 tests therefore carry `@superadmin` and run only on request (`E2E_INCLUDE_SUPERADMIN=1`); keep such runs short. - Duplicate a helper that exists: @@ -195,6 +195,7 @@ MUST NOT: | security actors, quarantine, answers, tokens | `Actor`, `adminOfApiUser`, `joinWorkspace`, `makeDeveloper`, `makeAdmin`, `grantApp`, `seedPrivateApp`, `sceneOf`, `memberOf`, `roleOf`, `permissionIdOf`, `securityTestDetails`, `securityCandidateDetails`, `expectAnswer`, `expectDeniedAs`, `forgeApiKeyToken`, `forgeUnsignedToken`, `withRandomSignature`, `tokenIsSignedWith`, `superAdminCredentials`, `SUPER_ADMIN_ENV`, `enterpriseAdmin` (ENTERPRISE stack: an actor the super admin makes admin of the one workspace), `echoTargetPath`, `echoReadPrefix`, `echoBaseUrl`, `echoUrlByIp` (an echo target URL with its host replaced by the echo's IP address, `E2E_ECHO_IP`: for a plugin that derives a host name from its endpoint, e.g. an S3 bucket call; never address a bucket of the `e2e-echo` alias), `recordsContain` (requests the SERVER makes, read back from the HTTP echo sidecar: the `echo` fixture gives a test its own target `url` and `received()`; a denial must follow a positive control that the echo does receive from that path; compare a secret with `recordsContain(...)` as a boolean, never as a matcher's value) (the `actor`, `superAdmin` and `echo` fixtures are in `src/fixtures.ts`; the raw-answer helper `apiRaw` and the other security API helpers are in `src/api/client.ts`) | `src/security/actors.ts`, `scene.ts`, `quarantine.ts`, `assertions.ts`, `tokens.ts`, `super-admin.ts`, `enterprise.ts`, `echo.ts` | | Firebird sidecar connection (opt-in sidecar: throws `FirebirdSidecarMissingError` when `E2E_FIREBIRD_HOST` is unset), the rows of `fixtures/firebird/init.sql` | `firebirdConnection`, `FirebirdSidecarMissingError`, `FIREBIRD_ITEMS` | `src/datasource/firebird.ts` | | libSQL sidecar connection (opt-in sidecar: throws `LibsqlSidecarMissingError` when `E2E_LIBSQL_HOST` is unset) and a direct pipeline call to it from the test process (the control that shows the server's own answer) | `libsqlConnection`, `libsqlDirect`, `LibsqlSidecarMissingError`, `LIBSQL_PIPELINE_PATH` | `src/datasource/libsql.ts` | +| CouchDB sidecar connection (opt-in sidecar: throws `CouchdbSidecarMissingError` when `E2E_COUCHDB_HOST` is unset) and a direct HTTP call to it from the test process, plain or as the sidecar's admin (the control that shows the server's own status and body, and the way a test makes and removes its own database) | `couchdbConnection`, `couchdbDirect`, `couchdbAdmin`, `CouchdbSidecarMissingError` | `src/datasource/couchdb.ts` | | pages | `EditorPage`, `AppViewPage`, `PropertyPanel`, `QueryPanel`, `TableView`, `ExtensionsPanel`, `AppListPage`, `AuthPage`, `LoginPage`, `UserMenu`, `SettingPage`, `DatasourcePage` | `src/pages/` | Accepted exception to the `test` import rule: stack-free unit specs that open no browser page (no `page`, no app) may @@ -272,6 +273,7 @@ E2E_INCLUDE_INSERT_ALL=1 e2e/scripts/run-in-docker.sh --grep @insert-all --worke E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin # SEC-R16a, R16b (R16c, R16d also need E2E_INCLUDE_QUARANTINE=1) E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-firebird.spec.ts # D12 gate: starts the Firebird sidecar (image pull, a few seconds) E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-turso-libsql.spec.ts # D13 gate: starts both sidecars (Firebird and libSQL) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-couchdb.spec.ts # D14 gate: starts all three sidecars (Firebird, libSQL and CouchDB) E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # only the tests that need a sidecar e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/modules/module-editor-host.spec.ts # M3 gate E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/security/enterprise.spec.ts # ENTERPRISE stack gate (its own stack; never at the same time as another run) @@ -286,7 +288,7 @@ Directory `e2e/` (no stack; `--reporter=list` is required so no report files are LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_INCLUDE_QUARANTINE=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_INCLUDE_SUPERADMIN=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # adds the D12 and D13 tests +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # adds the D12, D13 and D14 tests E2E_INCLUDE_INSERT_ALL=1 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_SUPERADMIN=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_STACK_PROFILE=enterprise LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # the SEC-E tests only ``` diff --git a/e2e/README.md b/e2e/README.md index d1d2e3a0b6..93b802a7ca 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; Firebird (node-firebird over TCP, D12) runs against a Firebird sidecar of its own that only a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` starts, and a default run neither starts it nor lists or runs those tests, and Turso also runs against a real libSQL server (sqld, D13) the same way, where the `libsql://` to `https://` rewrite of the URL is not covered because the sidecar speaks plain HTTP; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; Firebird (node-firebird over TCP, D12) runs against a Firebird sidecar of its own that only a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` starts, and a default run neither starts it nor lists or runs those tests, and Turso also runs against a real libSQL server (sqld, D13) the same way, where the `libsql://` to `https://` rewrite of the URL is not covered because the sidecar speaks plain HTTP, and CouchDB also runs against a real Apache CouchDB server (D14) the same way, where the JWT credential and cookie sessions are not covered because the image's default configuration has no JWT authentication handler and the plugin sends the `Authorization` header only; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -43,12 +43,19 @@ lifecycle (insert, save, publish, load) is covered by S1 when `@insert-all` runs - **Image:** `firebirdsql/firebird:3.0.12`, pinned by tag and digest (`sha256:e45c9bc4fdacaaddc1980a05b7bb8b297f09fe019eadefb059006efe4dafe875`; `FIREBIRD_IMAGE` overrides it), data from `fixtures/firebird/init.sql` (`FB_ITEMS`, 3 read-only rows; `FB_NOTES`, writes scoped by owner), throw-away user and password in `FIREBIRD` of `src/constants.ts` and in the script. Why this one, measured with node-firebird 1.1.9 (the version node-service installs) from the runner: 3.0.12, 4.0.5 and 5.0.4 all refuse the attach with the image's defaults (3.0.12 and 5.0.4: "Incompatible wire encryption levels requested on client and server", WireCrypt `Required`; 4.0.5: "Error occurred during login"). 4.0.5 and 5.0.4 attached with `FIREBIRD_CONF_AuthServer=Srp,Legacy_Auth` plus `FIREBIRD_CONF_WireCrypt=Disabled` (one attempt each). 3.0.12 attached with `FIREBIRD_CONF_WireCrypt=Enabled` or `FIREBIRD_USE_LEGACY_AUTH=true`, but with its default Srp login 12 of 100 attaches failed with "Your user name and password are not defined" (node-firebird's client-side Srp; also seen through the app: 4 of 14 queries of one probe), while with `FIREBIRD_USE_LEGACY_AUTH=true` 100 of 100 attached. The sidecar therefore runs 3.0.12 with `FIREBIRD_USE_LEGACY_AUTH=true` (Legacy_Auth first, WireCrypt `Enabled`). Limit of that choice: Legacy_Auth compares only the first eight characters of a password (measured: a wrong password that shares them attached), so the wrong password of D12b differs within them; the sidecar is not evidence about the Srp login of Firebird 3, 4 or 5, which node-firebird 1.1.9 fails at random. - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar` (or name the spec file). - **Cost, measured here:** image 156 MB (`docker image inspect`), a cold pull of the pinned digest took 3 s (a fast link and a warm registry mirror: expect more elsewhere), the container accepted the readiness SELECT within about 3 s of starting (the script logged `Firebird sidecar ready after 0s`: the wait ran after the PostgreSQL wait of 2 s), and a gate of 110 tests ran in about 23 s. Runs without the flag pay nothing. -- **libSQL sidecar (opt-in):** the Turso plugin of node-service posts Hrana pipelines to `/v2/pipeline` over HTTP, so the echo can stand in for it (D5, canned answers); a real server adds what canned answers cannot: the real column types and cells, real SQL errors, real authentication (D13, `tests/datasource/plugin-turso-libsql.spec.ts`). It is OPT-IN under the same flag and tag as the Firebird sidecar and both start together: +- **libSQL sidecar (opt-in):** the Turso plugin of node-service posts Hrana pipelines to `/v2/pipeline` over HTTP, so the echo can stand in for it (D5, canned answers); a real server adds what canned answers cannot: the real column types and cells, real SQL errors, real authentication (D13, `tests/datasource/plugin-turso-libsql.spec.ts`). It is OPT-IN under the same flag and tag as the Firebird sidecar and the sidecars start together: - **A default run** starts no libSQL container, pulls no libSQL image, passes no `E2E_LIBSQL_HOST` to the runner, and neither lists nor runs the D13 tests. **A run with the flag** starts the sidecar right after the Firebird one, waits (at most `STARTUP_TIMEOUT`, 300 s, polled every 2 s) until one real `select 1` pipeline with the read-write token, posted from the echo container to `http://e2e-libsql:8080/v2/pipeline` over the run network, answers 200 with the integer 1, gives the app container and the runner `--add-host e2e-libsql:` (added to the Firebird entry, not replacing it), passes `E2E_LIBSQL_HOST=e2e-libsql` to the runner, and removes the container in the cleanup trap however the run ends. The data source URL is `http://e2e-libsql:8080` (`libsqlConnection()` throws a named error when the host variable is unset). - **Image:** `ghcr.io/tursodatabase/libsql-server:v0.24.33`, sqld 0.24.33, pinned by tag and digest (`sha256:f8ca0134cdded747793888e48591aece07647d9d598d3ac229aabfa93159ca88`; `LIBSQL_IMAGE` overrides it). It is the libSQL project's own server image. Its `latest` tag, pulled at the same time, was another build that also reports sqld 0.24.33 (digest `sha256:6dd3eb276d9d3604e4a48ac4a999a2e267814732d57d7e94c04ba71482333a67`), so the pin uses the version tag. The image declares `/var/lib/sqld` a volume, so the script mounts a tmpfs there: the database is in memory and no anonymous volume outlives the run. - **Auth setup:** sqld started with `SQLD_AUTH_JWT_KEY` accepts only a JWT signed with the matching Ed25519 key (a plain `--http-auth` would want Basic credentials, but the plugin sends `Authorization: Bearer `). A key pair was generated once and its private half thrown away; `LIBSQL` in `src/constants.ts` and `LIBSQL_JWT_PUBLIC_KEY` / `LIBSQL_TOKEN` in the script hold the public key and tokens signed with it, without an expiry: a read-write token (claim `a: "rw"`), a read-only one (`a: "ro"`, the server answers 403 to a write) and a "foreign" one signed by a second throw-away pair (the server answers 401). A foundation test verifies the three signatures against the public key. Without a token, with a malformed one or with the foreign one the server answers 401. - - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-turso-libsql.spec.ts` (both sidecars start; `--grep @node-service-sidecar` runs D12 as well). + - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-turso-libsql.spec.ts` (every sidecar starts; `--grep @node-service-sidecar` runs D12 and D14 as well). - **Cost, measured here:** the image is 153 MB (`docker image inspect`, uncompressed) and a cold pull of the pinned digest took 9 s (a fast link: expect more elsewhere); the container started with the Firebird one and answered the readiness call within about a second (the script logged `libSQL sidecar ready after 0s`, the wait running after the PostgreSQL, echo and Firebird waits), so the two sidecars together add no waiting of their own beyond the slower one; a gate of 110 tests (`--repeat-each=10 --workers=4`) ran in about 27 s. Runs without the flag pay nothing. A readiness failure is bounded: with a copy of the script whose key did not match the readiness token and `STARTUP_TIMEOUT=6`, the run stopped after about 11 s with `the libSQL sidecar did not become ready within 6s`, the server's log tail, and the containers and network removed. +- **CouchDB sidecar (opt-in):** the CouchDB plugin of node-service is an OpenAPI wrapper that sends HTTP, so the echo can stand in for it (D8a to D8i, canned answers); a real server adds what canned answers cannot: the server's own status codes and error bodies, stored documents and revisions, key ranges, real authentication and its lockout (D14, `tests/datasource/plugin-couchdb.spec.ts`). It is OPT-IN under the same flag and tag as the other sidecars and all three start together: + - **A default run** starts no CouchDB container, pulls no CouchDB image, passes no `E2E_COUCHDB_HOST` to the runner, and neither lists nor runs the D14 tests (`--list --grep @node-service-sidecar` shows 0). Measured: the containers a default run created (`docker events`) were the app, the echo, PostgreSQL and the runner. **A run with the flag** starts the sidecar right after the libSQL one, waits (at most `STARTUP_TIMEOUT`, 300 s, polled every 2 s; every readiness request has a 2 s connect and a 5 s total limit, so a stalled request ends the attempt and the deadline is checked again) until the server answers `_up`, creates the system databases (a `PUT` counts only on 201 or 412) and lists them, gives the app container and the runner `--add-host e2e-couchdb:` (appended to the entries of the other sidecars), passes `E2E_COUCHDB_HOST=e2e-couchdb` to the runner, and removes the container in the cleanup trap however the run ends. The data source URL is `http://e2e-couchdb:5984` (`couchdbConnection()` throws a named error when the host variable is unset). Reached from both sides: the plugin's requests come from the app container, and D14i and the direct calls come from the runner. + - **Image:** `couchdb:3.5.1`, Apache CouchDB 3.5.1 (the official image; the plugin bundles the 3.1.1 API document), pinned by tag and digest (`sha256:ccea1e8035bf7afd68336e24056a1ca9c1c46d7abe42da686322c0ac7218e5c2`; `COUCHDB_IMAGE` overrides it). The image declares `/opt/couchdb/data` a volume, so the script mounts a tmpfs there: the data is in memory and this sidecar leaves no anonymous volume (measured: `docker inspect` of the running container shows `Mounts` empty and the tmpfs; a default run left one dangling volume, PostgreSQL's, and a run with the flag two, PostgreSQL's and Firebird's, so the CouchDB sidecar adds none). + - **Admin setup:** the image makes one server admin from `COUCHDB_USER` and `COUCHDB_PASSWORD` (`COUCHDB` in `src/constants.ts` and the script: `e2eadmin` and a throw-away password, never a real secret). A fresh single node has no system databases (`_all_dbs` answers `[]`), so the readiness step creates `_users`, `_replicator` and `_global_changes` with `PUT` through the real HTTP API (201, or 412 when they exist) and is ready when `_all_dbs` lists all three; it runs inside the container (the image has curl), is idempotent, and is repeated until it succeeds. The tests make their own databases (`e2e_couch_`) and remove them. + - **Lockout (measured, CouchDB 3.5.1):** after five failed logins of a real account the server answers 403 `Account is temporarily locked due to multiple authentication failures` to that account, from that client address, even with the right password (the message says "temporarily"; how long it lasts was not measured). A test that sends a wrong password therefore does it as a second admin it makes for the purpose (D14e, D14j) and never as the sidecar's admin, which every other test uses; failures for a name that does not exist are not counted. A freshly made config admin cannot log in until the server has hashed its password (a moment after the `PUT`), so the helper waits for the hash before the first login. + - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-couchdb.spec.ts` (all three sidecars start; `--grep @node-service-sidecar` runs D12 and D13 as well). + - **Cost, measured here:** the image is 276 MB (`docker image inspect`, uncompressed); CouchDB answered the readiness probe on its first try, about a second after it started (the script logged `CouchDB sidecar ready after 0s`: the wait runs after the PostgreSQL, echo, Firebird and libSQL waits, and the server's log shows it started in about half a second), so all three sidecars together added no waiting of their own beyond the slowest. A cold pull of the pinned digest took 6.4 s (a fast link: expect more elsewhere). A readiness failure is bounded: with a copy of the script whose readiness probe used a wrong password and `STARTUP_TIMEOUT=6`, the run stopped after 12 s with `the CouchDB sidecar did not become ready within 6s`, the server's log tail, and the containers and network removed. A test that fails still ends with every container and the network removed (measured with a deliberately failing test under the flag: seven containers created, none left, no network left). - **HTTP echo sidecar** (`scripts/echo-server.js`, started by `run-in-docker.sh` on the already pinned runner image, so no extra image or download; network alias `e2e-echo`, port 8080; the runner gets `E2E_ECHO_URL` and the sidecar's IP address on the run network as `E2E_ECHO_IP`): the target of the requests the SERVER makes inside the app container (node-service's npm registry proxy, the n8n plugin). It records `{ method, path, headers, body }` of every request in @@ -138,7 +145,7 @@ e2e/scripts/run-in-docker.sh -g "sign-up through the UI" # one test b e2e/scripts/run-in-docker.sh --grep @smoke # by tag: @smoke @core @slow @npm E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --grep @quarantine E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin # SEC-R16a, SEC-R16b (R16c, R16d also need E2E_INCLUDE_QUARANTINE=1) -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # D12 and D13, the Firebird and libSQL sidecar tests (starts both sidecars) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # D12, D13 and D14, the Firebird, libSQL and CouchDB sidecar tests (starts all three sidecars) E2E_INCLUDE_INSERT_ALL=1 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh # everything on the default stack (not the @enterprise tests) E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh tests/security/enterprise.spec.ts # the ENTERPRISE stack, SEC-E01 to E04, E06a, E06b, E07a, E07b E2E_STACK_PROFILE=signup-disabled e2e/scripts/run-in-docker.sh tests/auth/signup-disabled.spec.ts # the stack with e-mail sign-up switched off, LC-AU20 to AU24 @@ -193,9 +200,11 @@ data; its tests are untagged. | `PLAYWRIGHT_IMAGE` | run-in-docker.sh | runner image; version must equal `@playwright/test` in `package-lock.json` (1.64.0) | | `POSTGRES_IMAGE` | run-in-docker.sh | PostgreSQL sidecar image | | `FIREBIRD_IMAGE` | run-in-docker.sh | Firebird sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | -| `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | script and config | non-empty, default stack only (any other profile stops the script): start the Firebird and libSQL sidecars and include the `@node-service-sidecar` tests (D12, D13) | +| `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | script and config | non-empty, default stack only (any other profile stops the script): start the Firebird, libSQL and CouchDB sidecars and include the `@node-service-sidecar` tests (D12, D13, D14) | | `LIBSQL_IMAGE` | run-in-docker.sh | libSQL server (sqld) sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | | `E2E_LIBSQL_HOST` | set by run-in-docker.sh | the libSQL sidecar's network alias, only in a run with the flag; `libsqlConnection()` reads it | +| `COUCHDB_IMAGE` | run-in-docker.sh | CouchDB sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | +| `E2E_COUCHDB_HOST` | set by run-in-docker.sh | the CouchDB sidecar's network alias, only in a run with the flag; `couchdbConnection()` reads it | | `E2E_FIREBIRD_HOST` | set by run-in-docker.sh | the Firebird sidecar's network alias, only in a run with the flag; `firebirdConnection()` reads it | | `E2E_INCLUDE_QUARANTINE`, `E2E_INCLUDE_INSERT_ALL`, `E2E_INCLUDE_SUPERADMIN` | script and config | non-empty: include that opt-in group | | `E2E_STACK_PROFILE` | run-in-docker.sh, config | `default` (the default), `signup-disabled` (the app container gets `LOWCODER_EMAIL_SIGNUP_ENABLED=false` and the run keeps only the `@signup-disabled` tests; `E2E_INCLUDE_QUARANTINE` is the only flag that applies) or `enterprise`: the app container gets `LOWCODER_WORKSPACE_MODE=ENTERPRISE` and the run keeps only the `@enterprise` tests (`grep`); another value stops the run. On the enterprise profile `E2E_INCLUDE_QUARANTINE` opens nothing extra (no enterprise test is quarantined any more), `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` change nothing (the stack has one workspace, so the D-47 limit does not arise). A `--grep` of the command line narrows the profile's selection further; it does not replace it (measured with Playwright 1.64: enterprise profile with `--grep SEC-R01b` lists 0 tests, with `--grep SEC-E02` lists 1, with the default profile `--grep SEC-E02` lists 0) | @@ -229,7 +238,7 @@ e2e/ fixtures/firebird/init.sql Firebird sidecar data (opt-in sidecar): FB_ITEMS, FB_NOTES fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb`, `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate), `firebird` (the form's body with the sidecar's own host, port, database path and throw-away login, because the host cannot be a placeholder, and the editor's saved query; recorded in a session on a stack with the sidecar), `supabase` (the form's body, and one query recording per action: `supabaseQuery.json` is listBuckets, the others are `supabaseQuery.json`: ListObjects, ReadFile, UploadData, DeleteFile, CreateSignedUrl), `dynamodb` and `s3` (the form's body, and one query recording per action because the saved query differs by action: `Query.json` is the editor's default action, the others are `Query.json`, loaded by `recordedPluginQuery(id, "")`: `dynamodb` Query, ListTables, GetItem, PutItem; `s3` listBuckets, ListObjects, ReadFile, UploadData, DeleteFile) + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb` (the form's body with placeholders, `couchdbQuery.json` is the editor's saved `allDBs`, and one query recording per further operation of the CouchDB sidecar tests, `couchdbQuery.json`: Put, Get, Delete, DocPut, DocGet, DocDelete, DocGetAll; recorded in a session on a stack with the sidecar, the data source typed with the sidecar's own host and login, operation picked in the editor's Resource and Operation lists; the field values of every recording are the editor's empty defaults, so no host or login survives), `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate), `firebird` (the form's body with the sidecar's own host, port, database path and throw-away login, because the host cannot be a placeholder, and the editor's saved query; recorded in a session on a stack with the sidecar), `supabase` (the form's body, and one query recording per action: `supabaseQuery.json` is listBuckets, the others are `supabaseQuery.json`: ListObjects, ReadFile, UploadData, DeleteFile, CreateSignedUrl), `dynamodb` and `s3` (the form's body, and one query recording per action because the saved query differs by action: `Query.json` is the editor's default action, the others are `Query.json`, loaded by `recordedPluginQuery(id, "")`: `dynamodb` Query, ListTables, GetItem, PutItem; `s3` listBuckets, ListObjects, ReadFile, UploadData, DeleteFile) src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -277,15 +286,16 @@ Test titles carry these ids. - D11 the Supabase Storage plugin of node-service (`supabase-js`, project URL `/sb`) against the echo sidecar: every operation (listBuckets, listObjects, readFile, uploadData, deleteFile, createSignedUrl) sends its Storage API request below `/sb/storage/v1` with the key in `apikey` and `authorization` and nowhere else, a trailing slash of the project URL changes nothing, a storage error fails the query with `{"size":0,"timeout":0}` and not the API's message (NSD-9 candidate), the signed-URL validity is an epoch time in milliseconds (NSD-10 candidate), the `search` field of listObjects is not sent (NSD-11 candidate), only listObjects refuses an empty bucket (NSD-12 candidate), the published view after a click (`@node-service`; the request shape and the answer's path into the app, not Supabase). - D12 the Firebird plugin of node-service against the opt-in Firebird sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): the connection test attaches, a wrong password and a missing database file fail it with the server's text, a named parameter answers the lower-cased row, every column type of the seeded table, parameters bound in SQL order, not object order, an unknown parameter is refused with its name, an INSERT is read back by its own owner, a SQL error is the failed query's message, the lower-case option, a failing query leaves its attachment open (NSD-13 candidate), and the runner reaches the sidecar over TCP. - D13 the Turso plugin of node-service against the opt-in libSQL server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): create, insert and select answer typed rows (integer, real, a lower-case `boolean`, `datetime`, NULL), `includeRaw` answers the server's own result set, a write answers no values and its raw result counts the change, a blob cell is dropped from the row (NSD-14 candidate), an integer beyond 2^53 is rounded (NSD-15 candidate), a real SQL error (syntax, unknown column, constraint, two statements) fails the query with `[object Object]` (NSD-1 candidate, the defect of D5d against a real server), a token of another key or a malformed one is a 401, a read-only token reads and its write is a 403, the published view after a click, a trailing slash after the URL is a 404, and the runner reaches the sidecar. The `libsql://` rewrite is not covered. +- D14 the CouchDB plugin of node-service against the opt-in CouchDB server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): a database is created, listed (by a key range), described and deleted, and the server agrees at each step; a document is created, read, updated by its revision, read at its old revision, listed and deleted; a stale revision (as a query parameter or as `If-Match`) answers a conflict body and changes nothing (NSD-4 candidate); a missing database or document and an existing database answer their error bodies (NSD-4 candidate); a wrong password answers an unauthorized body and writes nothing (NSD-4 candidate); five wrong passwords lock the account for the client address and even the right password then gets the lockout's 403 body (NSD-4 candidate); `docGet` cannot run without `If-None-Match` and a matching ETag fails with `status: 304` (NSD-16 candidate); the listing options (`startkey`, `endkey`, `descending`, `skip`, `limit`) reach the server; the published view shows a document after a click; and the runner reaches the sidecar. The JWT credential and cookie sessions are not covered. - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue -Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 833-test suite after the libSQL sidecar scenarios (D13) landed, `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (no variable set): 43 failed, 790 passed. It started no libSQL and no Firebird container (the containers seen every 0.3 s during the run were the app, the echo, PostgreSQL and the runner) and ran no D12 or D13 test (they are not in the listing). The baseline from a clean worktree of the previous commit (827 tests, same command and image): 43 failed, 784 passed. The failing sets are identical (compared by test name): 24 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`; `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag, not analysed one by one). Neither `SEC-R09d` nor the periodic trigger test of `logic/triggers.spec.ts` failed in either of these two runs (both failed once in earlier runs, so they are still treated as intermittent). The six extra passes are the six new unit tests of `foundation/node-plugins.spec.ts`. No node-service scenario failed. The D12 and D13 evidence is a separate gate each, `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 `: for `tests/datasource/plugin-firebird.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D12 landed), for `tests/datasource/plugin-turso-libsql.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (both sidecars start).): -default **833 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **847 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **838 in 114**; with both of those **852 in 115**; -with `E2E_INCLUDE_INSERT_ALL=1` **945 in 115**; with all three opt-in variables **964 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **855 in 116** (the 11 D12 tests of the Firebird sidecar and the 11 D13 tests of the libSQL sidecar, which no other variable lists), and **986 in 118** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: +Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 839-test suite (before the last unit test, the readiness-limit one, was added; the suite lists 840 now) after the CouchDB sidecar scenarios (D14) landed, `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (no variable set): 44 failed, 795 passed. It started no Firebird, libSQL or CouchDB container (the script logged only the PostgreSQL, echo and app starts; a separate default run measured with `docker events` created the app, the echo, PostgreSQL and the runner) and ran no D12, D13 or D14 test (they are not in the listing). The baseline from a clean worktree of the previous commit (833 tests, same command and image): 44 failed, 789 passed. The failing sets are identical (compared by test name): 25 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`; `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag, not analysed one by one). `SEC-R09d` is one of the 25 in both runs (the earlier full run, 43 failed, did not fail it: it is intermittent); the periodic trigger test of `logic/triggers.spec.ts` failed in neither. The six extra passes are the six new unit tests of `foundation/node-plugins.spec.ts`. No node-service scenario failed. The D12, D13 and D14 evidence is a separate gate each, `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 `: for `tests/datasource/plugin-firebird.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D12 landed), for `tests/datasource/plugin-turso-libsql.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D13 landed), for `tests/datasource/plugin-couchdb.spec.ts` 100 passed on `3.0.0-e2e` and 100 passed on `3.0.1-e2e`, and after the readiness probes got their time limits 110 passed for the Firebird spec and 110 for the libSQL spec on `3.0.0-e2e` (all three sidecars start; the app was ready 15 s after the first container started with the flag against 14 s without it). With the flag, `--grep @node-service-sidecar` ran all 32 sidecar tests (D12, D13, D14) in one run: 32 passed. These Docker results were measured by hand on one machine; no result files are committed, so re-run the commands named here to reproduce them.): +default **840 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **854 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **845 in 114**; with both of those **859 in 115**; +with `E2E_INCLUDE_INSERT_ALL=1` **952 in 115**; with all three opt-in variables **971 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **872 in 117** (the 11 D12 tests of the Firebird sidecar, the 11 D13 tests of the libSQL sidecar and the 10 D14 tests of the CouchDB sidecar, which no other variable lists), and **1003 in 119** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 128 in 10 files (the 37 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **150 in 12 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests and the 11 D13 tests); `@node-service-sidecar` 0 (**22 in 2 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests, and D13a to D13k, the libSQL sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 135 in 10 files (the 44 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **167 in 13 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests, the 11 D13 tests and the 10 D14 tests); `@node-service-sidecar` 0 (**32 in 3 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests, D13a to D13k, the libSQL sidecar tests, and D14a to D14j, the CouchDB sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -334,7 +344,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | editor/js-query.spec.ts | a JS query written in the editor runs | @core | 1 | | editor/drop-size.spec.ts | a component dropped right after ready has width above 0 (D-5) | @quarantine | 1 | -### datasource (101 default, 123 with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`) +### datasource (101 default, 133 with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`) | File | Proves | Tags | Tests | |---|---|---|---| @@ -352,6 +362,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/plugin-supabase-storage.spec.ts | D11: the Supabase Storage plugin against the echo sidecar (project URL `/sb`; the Storage API is `/sb/storage/v1/...`). Measured on 3.0.0-e2e and 3.0.1-e2e (same requests and answers; supabase-js 2.45.4 in `x-client-info`, matched by shape): the client keeps the project URL's path with or without a trailing slash and derives no host name; every request carries `apikey: `, `authorization: Bearer `, the `node-fetch` user agent, `accept-encoding: gzip,deflate` and `connection: close`. Every request a D11 test makes is asserted completely (method, path and query, body, the whole header set), and every test that sends one also asserts that the key is in no header besides those two, no path or body, and no answer of the query (the whole query answer; in D11q the view's whole `q.data` as text); control: it is in those two. D11a listBuckets `GET /bucket` and the buckets as the API answered, D11b the project URL with and without a trailing slash reach the same path, D11c listObjects `POST /object/list/` with `{limit: 10, offset: 0, sortBy: {column: name, order: asc}, prefix}` and the public URL of each file in the answer, D11d limit, offset and sort order of the query, D11e the `search` field is not sent (NSD-11 candidate), D11f `returnSignedUrl` adds `POST /object/sign/` with `{expiresIn, paths}` and the signed URL in the answer, D11g readFile as text and base64 (`GET /object//`, answer `{data, type}`), D11h readFile with a transform goes to `/render/image/authenticated//?width=10`, D11i uploadData of text `POST /object//` with the text, its content type, `cache-control: max-age=3600` and `x-upsert: false`, D11j base64 without a content type sends an empty `content-type` header (observation), D11k uploadData with `returnSignedUrl` uploads then signs, D11l deleteFile `DELETE /object/` with `{prefixes: [name]}`, D11m createSignedUrl sends `expiresIn` as an integer above 1e12, an epoch time in milliseconds computed once (the second query, asserted completely too, sends the same number; the bounds allow one hour of clock skew and a plugin load up to six hours old; NSD-10 candidate, also asserted in D11f and D11k), D11n a 400, a 404 and a 401 answer fail the query with `{"size":0,"timeout":0}` instead of the answer's message, each followed by a control that the same query succeeds once the API answers 200 (NSD-9 candidate), D11o the signing and the listing fail the same way, each followed by a control that both succeed once the API answers 200 on their paths, D11p an empty bucket: listObjects says `Bucket is required` and sends nothing, readFile, uploadData, deleteFile and createSignedUrl send requests with an empty bucket segment (NSD-12 candidate), D11q the published view shows the bucket name only after the click (echo empty before, one request after). Not covered: a real Supabase project; the connection test (none is wired up for this plugin) | @node-service | 21 | | datasource/plugin-firebird.spec.ts | D12: the Firebird plugin against the opt-in Firebird sidecar (Firebird 3.0.12, `fixtures/firebird/init.sql`; host, port, database path and login of the sidecar written over the recorded form body). Measured on 3.0.0-e2e and 3.0.1-e2e. D12a the connection test answers `code` 1, `success` true, `data` true; D12b a wrong password answers `code` 500 with `Failed to connect data source: Your user name and password are not defined. Ask your database\nadministrator to set up a Firebird login\n.` and a missing database file with the server's `I/O error for file ...` (the right fields attach first); D12c `SELECT ID, NAME FROM FB_ITEMS WHERE ID = :id` with `{"id": 2}` answers `[{id: 2, name: "beta"}]`; D12d the three seeded rows with `price` as a number and a NULL as `null`; D12e parameters bind in the order the names appear in the SQL, not the key order of the parameter object (`CAST(:first AS INTEGER) - CAST(:second AS INTEGER)` with 10 and 3 answers 7 whichever order the object lists them); D12f an unknown name fails with `Named parameter "missing" not found in Query Parameters object.` (the same SQL with the name present runs); D12g an INSERT answers `{}` and is read back by the test's own owner (the owner has no row before); D12h a syntax error and an unknown table answer the server's text; D12i `lowercaseKeys: false` answers upper-case keys; D12j a query that fails after the attach leaves its attachment open on the server, a succeeding one does not: two failing runs of a statement that tags its attachment with a per-test context variable leave exactly two tagged attachments in `MON$CONTEXT_VARIABLES`, and a succeeding tagged run does not add a third (NSD-13 candidate, `defect` annotation); D12k the runner connects to the sidecar's port 3050, and a closed port of the same host is refused. Limits: `role`, `blobAsText` and Firebird 4 and 5 are not covered; the sidecar authenticates with Legacy_Auth (see the architecture bullet) | @node-service @node-service-sidecar (opt-in) | 11 | | datasource/plugin-turso-libsql.spec.ts | D13: the Turso plugin against the opt-in libSQL sidecar (sqld 0.24.33 with a JWT key; the data source URL is `http://e2e-libsql:8080`, the recorded `turso` form body with the sidecar's URL and token written over it; each test makes its own table `e2e_t_`). Measured on 3.0.0-e2e and 3.0.1-e2e. D13a CREATE, two INSERTs and a SELECT: a CREATE and an INSERT answer `[]`, the empty table answers `[]` before the inserts, then `integer` is a number, `real` 2 stays 2, a `boolean` column written in lower case is `true`/`false`, a `datetime` text is the ISO text of a `Date` (`2024-01-02T03:04:05.000Z`), NULL is `null`; D13b `includeRaw` answers `values` and the server's `raw` (columns with their declared types, cells such as `{type:"integer", value:"7"}`, the counters; the timing is only checked to be a number); D13c an INSERT answers `[]` with and without `includeRaw`, its raw result has `affected_row_count` 1 and `last_insert_rowid` `"2"` (a string) for the second row; D13d a blob cell is missing from the row (`[{id: 1}]`) while `includeRaw` shows the server sent `{type:"blob", base64:"AP8Q"}` (NSD-14 candidate); D13e `SELECT 9007199254740993` answers 9007199254740992 while the raw cell is the exact string (NSD-15 candidate); D13f `SELEC 1`, an unknown column, a duplicate key and `SELECT 1; SELECT 2` are errors of the server with codes `SQL_PARSE_ERROR`, `SQL_INPUT_ERROR`, `SQLITE_CONSTRAINT` and `SQL_MANY_STATEMENTS` (read by direct calls), and every one of them reaches the app as `Cannot parse result, received error: [object Object]` (NSD-1 candidate; a valid query of the same app succeeds first); D13g a token signed by another key and a string that is no JWT fail with `Failed to execute query. Endpoint returned 401: Unauthorized.` (the sidecar's own token reads the row first; direct calls show the server's `The JWT is invalid` and, without a header, `Expected authorization header but none given`); D13h a read-only token reads, its INSERT fails with `Endpoint returned 403: Forbidden.` and writes nothing (the read-write token then inserts the same row); D13i the published view shows a row after a click; D13j a URL with a trailing slash fails with `Endpoint returned 404: Not Found.` (the plugin builds `//v2/pipeline`; the same URL without it works); D13k the runner reaches the sidecar over HTTP and TCP, a closed port of the same host is refused. Limits: the `libsql://` to `https://` rewrite, a stream with a baton, and Turso's cloud features are not covered | @node-service @node-service-sidecar (opt-in) | 11 | +| datasource/plugin-couchdb.spec.ts | D14: the CouchDB plugin against the opt-in CouchDB sidecar (Apache CouchDB 3.5.1; the data source URL is `http://e2e-couchdb:5984`; the recorded `couchdb` form body with the sidecar's URL and admin written over it; each test makes its own database `e2e_couch_` and removes it). Measured on 3.0.0-e2e and 3.0.1-e2e. D14a a database is created (`{ok: true}`), listed by a key range (`[]` before, `[]` after), described (`GET /`: the member set of 3.5.1, `doc_count` 0), and deleted, with direct reads of the server at each step; D14b a document is created (`{ok, id, rev: 1-...}`), read (`{_id, _rev, ...body}`), updated with `rev` as a query parameter (`2-...`), read at its first revision, listed with `include_docs`, and deleted (`3-...`; the server then answers `deleted`), and the server's own copy matches; D14c a stale revision (query parameter and `If-Match`, on write and delete) and a write without a revision answer `{error: "conflict", reason: "Document update conflict."}` as the data of a SUCCESSFUL query (the server's status is 409), change nothing, and the current revision is accepted by a write and by both kinds of delete (NSD-4 candidate); D14d a missing document, a document of a missing database, the information and the delete of a missing database (404 bodies) and a create of an existing database (412 `file_exists`) are successful queries with the error body as the data (NSD-4 candidate), with successful controls through the same operations (an existing document is read, an existing database is described and deleted, a new one is created); D14e a wrong password answers `{error: "unauthorized", reason: "Name or password is incorrect."}` as the data of a successful query and the refused create made no database, while the right password on the same queries lists and creates (NSD-4 candidate; the account is a second admin the test makes); D14f `docGet` with an empty `If-None-Match` fails with the plugin's own `Required parameter If-None-Match is not provided` (the server reads the same document without the header), a value that is not the current ETag reads the document, and the current ETag (the server answers 304) fails with `status: 304` (NSD-16 candidate); D14g `startkey`/`endkey`, `descending`, `skip` and `limit` give the lists the server gives, for databases and for the documents of a database (`total_rows` counts all of them), and an unscoped list holds the three system databases and the test's own; D14h the published view shows the document's title after a click; D14i the runner reaches the sidecar over HTTP and TCP (`Welcome`, version 3.5.1, `_all_dbs` needs credentials), a closed port of the same host is refused; D14j five wrong passwords of an account are 401 bodies, the sixth and the right password after them are the lockout's 403 body as the data of a successful query (the runner, another client address, is not locked until it fails five times itself, then the server's own status is 403) (NSD-4 candidate). Limits: JWT and cookie authentication, replication, design documents, partitions, attachments and bulk operations are not covered | @node-service @node-service-sidecar (opt-in) | 10 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -496,14 +507,14 @@ first makes sure some admin exists (accepting both answers), so none depends on SEC-R09d (D-38) left the quarantine: the check took the workspace of the first id of a `HashSet`; each id is now decided in its own workspace (Java unit and MongoDB integration tests green 2026-11-24; Docker/e2e confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`)). Accounting of the earlier 3.0.0 run `E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --workers=4 --reporter=list --grep "@quarantine" tests/security` (measured before the `@superadmin` tag existed and before the reassessment, so it listed 44 tests, 19 of which have since left the quarantine): 44 listed, 43 failed, 1 passed (SEC-R09d); the two quarantined tests of `foundation/security-helpers.spec.ts` are outside that folder. -### foundation (312 default, 315 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) +### foundation (319 default, 322 with the quarantined and the `@superadmin` ones; unit and builder tests; several touch the stack) | File | Proves | Tags | Tests | |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization`, and the Firebird sidecar helpers: `firebirdConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the firebird recordings (form fields with the sidecar's values, one query, no session value), `fixtures/firebird/init.sql` equals `FIREBIRD_ITEMS`, the script's Firebird constants equal `FIREBIRD`, and the run script starts, waits for and passes the sidecar only inside `if node_service_sidecars_enabled`; and the libSQL sidecar helpers: `libsqlConnection` (reads the host variable, builds the plain-HTTP URL, throws a named error when it is unset or empty), the script's libSQL values equal `LIBSQL` (alias, port, public key, token, an image pinned by tag and digest, the tmpfs data directory), the three tokens are JWTs with the claims they are named for and only the two sidecar ones verify under the sidecar's key (the foreign one is well-formed and does not), the script starts and waits for the libSQL sidecar only under the flag and appends its `--add-host` and host variable to the Firebird ones, and `libsqlDirect` against a local server (the pipeline body, the bearer header or none, a JSON or a text body) | @node-service | 37 | -| foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources), `@node-service-sidecar` (excluded by default, included by `E2E_INCLUDE_NODE_SERVICE_SIDECARS`, independent of the other flags, never selected on the enterprise and signup-disabled stacks), and the guard that every test of a spec that calls `firebirdConnection` or `libsqlConnection` carries `@node-service-sidecar` (same parsing; synthetic sources) | none | 32 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization`, and the Firebird sidecar helpers: `firebirdConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the firebird recordings (form fields with the sidecar's values, one query, no session value), `fixtures/firebird/init.sql` equals `FIREBIRD_ITEMS`, the script's Firebird constants equal `FIREBIRD`, and the run script starts, waits for and passes the sidecar only inside `if node_service_sidecars_enabled`; and the libSQL sidecar helpers: `libsqlConnection` (reads the host variable, builds the plain-HTTP URL, throws a named error when it is unset or empty), the script's libSQL values equal `LIBSQL` (alias, port, public key, token, an image pinned by tag and digest, the tmpfs data directory), the three tokens are JWTs with the claims they are named for and only the two sidecar ones verify under the sidecar's key (the foreign one is well-formed and does not), the script starts and waits for the libSQL sidecar only under the flag and appends its `--add-host` and host variable to the Firebird ones, and `libsqlDirect` against a local server (the pipeline body, the bearer header or none, a JSON or a text body); and the CouchDB sidecar helpers: `couchdbConnection` (reads the host variable, builds the plain-HTTP URL with the admin, throws a named error when it is unset or empty), the script's CouchDB values equal `COUCHDB` (alias, port, admin, the system databases, an image pinned by tag and digest, the tmpfs data directory), the script starts and waits for the CouchDB sidecar only under the flag, appends its `--add-host` and host variable to the others, bounds the wait by `STARTUP_TIMEOUT` and removes the container in the trap, the CouchDB recordings (one per operation: action name, the form's fields in order, every value the editor's empty default, no session value, no sidecar address), and `couchdbDirect` and `couchdbAdmin` against a local server (method, path, JSON body, extra headers, Basic credentials or none, a JSON or a text body), and the readiness steps of the script (every CouchDB readiness curl carries a connect and a total time limit, the system-database PUT counts only on 201 or 412, the libSQL fetch and the Firebird isql are bounded too) | @node-service | 44 | +| foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources), `@node-service-sidecar` (excluded by default, included by `E2E_INCLUDE_NODE_SERVICE_SIDECARS`, independent of the other flags, never selected on the enterprise and signup-disabled stacks), and the guard that every test of a spec that calls `firebirdConnection`, `libsqlConnection` or `couchdbConnection` carries `@node-service-sidecar` (same parsing; synthetic sources; the specs that use a helper are the CouchDB, Firebird and libSQL ones) | none | 32 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | | foundation/module-host.spec.ts | module created through the API works in a host; republish rules | none | 2 | @@ -545,7 +556,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-1 candidate | the Turso plugin prints a pipeline `error` result as `${result.error}`, an object: a failed statement reaches the app as `Cannot parse result, received error: [object Object]` and the server's own message is lost; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-turso-slack.spec.ts` D5d asserts today's message (characterisation, default run), annotation `{type:"defect", description:"NSD-1 candidate"}`; it changes when the plugin prints the message. Against the real libSQL sidecar the same text is printed for a syntax error, an unknown column, a constraint violation and a two-statement string, each of which the server answers with its own message and code (`datasource/plugin-turso-libsql.spec.ts` D13f, same annotation) | | NSD-3 candidate | the DuckDB plugin answers rows keyed by the column position, not the column name (`SELECT 42 AS answer` arrives as `{"0": 42}`): `getRows()` answers arrays and `serializeBigInts` copies `Object.entries(row)`; measured on 3.0.0-e2e and 3.0.1-e2e. An app cannot read `row.answer`. The id is provisional until the owner assigns one | `datasource/plugin-duckdb.spec.ts` D4a to D4c assert today's keys (characterisation, default run), annotation `{type:"defect", description:"NSD-3 candidate"}`; they change when the plugin keys rows by name | | NSD-2 candidate | the Shopify plugin reads the query's headers and passes `{}` on, and its data source has only `endpoint`: it cannot send Shopify's access token (`X-Shopify-Access-Token`); measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-graphql.spec.ts` D6d asserts today's behaviour after a control that the request did reach the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-2 candidate"}`; it changes when the query's headers are forwarded | -| NSD-4 candidate | the generic Open API plugin returns the body of an error status answer as the query result (`runOpenApi` catch, `e.response.body`): a canned 404 `{"message":"e2e-missing"}` is reported as `success: true`, `queryCode: "OK"`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi.spec.ts` D7d asserts today's behaviour after a control that the request reached the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-4 candidate"}`; it changes when an error status fails the query. `datasource/plugin-openapi-wrappers-apps.spec.ts` D9i shows the same for APITemplate (wrappers share `runOpenApi`) | +| NSD-4 candidate | the generic Open API plugin returns the body of an error status answer as the query result (`runOpenApi` catch, `e.response.body`): a canned 404 `{"message":"e2e-missing"}` is reported as `success: true`, `queryCode: "OK"`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi.spec.ts` D7d asserts today's behaviour after a control that the request reached the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-4 candidate"}`; it changes when an error status fails the query. `datasource/plugin-openapi-wrappers-apps.spec.ts` D9i shows the same for APITemplate (wrappers share `runOpenApi`). Against the real CouchDB sidecar `datasource/plugin-couchdb.spec.ts` D14c, D14d, D14e and D14j show it for the server's own 409 (stale revision), 404 (missing database or document), 412 (database exists), 401 (wrong password) and 403 (locked account) answers: each is `success: true`, `queryCode: "OK"` with the error body as the data and the status is lost; each test first shows the server's status by direct calls and has these successful controls: D14c the current revision accepted by a write and by a delete (as a query parameter and as `If-Match`); D14d an existing document read, the information of an existing database, the delete of an existing database and the create of a new one; D14e the same two queries with the right password; D14j the right password listing before the five failures, and the sidecar's own admin still working after them. Annotation `NSD-4 candidate` | | NSD-5 candidate | the WooCommerce plugin appends `wp-json/wc/v3` to a server URL unless it ends exactly in `/wc/v3`, so a server URL copied with a trailing slash (`/wp-json/wc/v3/`) is requested at `/wp-json/wc/v3/wp-json/wc/v3/products`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-data.spec.ts` D8h asserts today's behaviour (characterisation, default run), annotation `{type:"defect", description:"NSD-5 candidate"}`; it changes when a trailing slash is accepted | | NSD-6 candidate | the UiPath plugin cannot run: `getSchemaExample` (`plugins/openApi/util.ts`) recurses without end on a circular schema of the bundled document, so the query configuration (`POST /api/datasources/getPluginDynamicConfig`, path `$.queryConfig`) answers 500 / code 5000 `get dynamic config error` (the editor lists no operation and cannot save a UiPath query) and every query fails with `Maximum call stack size exceeded` before any request is sent; the cause (`RangeError: Maximum call stack size exceeded` at `getSchemaExample`, from a circular schema) was read in the app container's node-service log while recording, not asserted: the suite asserts only the HTTP 500 / code 5000 of the configuration request, the query's failure message and that no request is sent; measured on 3.0.0-e2e and 3.0.1-e2e. Whether UiPath sends its `Authorization` header (a doubled `Bearer`, or none) cannot be measured today. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9j and D9k assert today's behaviour after a control that another plugin reaches the echo / lists its operations (characterisation, default run), annotation `{type:"defect", description:"NSD-6 candidate"}`; D9l asserts the desired behaviour (`GET /odata/Folders` with `Authorization: Bearer ` exactly), `@quarantine`, same annotation; they change when the plugin runs | | NSD-7 candidate | an OpenAI data source on spec version `v1.0` (the version an empty choice selects) sends no `Authorization` header: the plugin hands the key over as `ApiKeyAuth.value`, the security scheme of the `v2.3` document, while the `v1.0` document names its scheme `ApiKey`; with `v2.3` the same key is sent as `Authorization: Bearer `; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9h asserts today's behaviour after a control that v2.3 sends the key to the same echo (characterisation, default run), annotation `{type:"defect", description:"NSD-7 candidate"}`; it changes when the key reaches the `v1.0` document's scheme | @@ -557,6 +568,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-13 candidate | the Firebird plugin never detaches a connection when its query fails after the attach (`firebirdsql/run.ts`: `detachAsync()` comes after the awaited query, and the unknown-parameter check also runs after the attach), so the attachment stays open on the server; a succeeding query detaches. Measured on 3.0.0-e2e and 3.0.1-e2e against the Firebird sidecar: after two failing runs of a statement that tags its attachment (`RDB$SET_CONTEXT`, then a division by zero) `MON$CONTEXT_VARIABLES` holds exactly 2 attachments with the tag, and a succeeding tagged run leaves it at 2. The id is provisional until the owner assigns one | `datasource/plugin-firebird.spec.ts` D12j, `defect` annotation `NSD-13 candidate`; passes today, expect it to fail once the plugin detaches in `finally` | | NSD-14 candidate | the Turso plugin drops a `blob` cell: the server answers it as `{type:"blob", base64}` with no `value`, `parseValue` returns `undefined` for it, and the key is missing from the row (`SELECT id, data` answers `[{id: 1}]`). Measured on 3.0.0-e2e and 3.0.1-e2e against the libSQL sidecar. The id is provisional until the owner assigns one | `datasource/plugin-turso-libsql.spec.ts` D13d, `defect` annotation `NSD-14 candidate`; passes today, expect it to fail once the plugin returns the bytes | | NSD-15 candidate | the Turso plugin parses an `integer` cell (which the server sends as a string, exact) with `Number.parseInt`, so an integer above 2^53 is rounded: `SELECT 9007199254740993` answers 9007199254740992 while `includeRaw` shows the exact string. Measured on 3.0.0-e2e and 3.0.1-e2e against the libSQL sidecar. The id is provisional until the owner assigns one | `datasource/plugin-turso-libsql.spec.ts` D13e, `defect` annotation `NSD-15 candidate`; passes today, expect it to fail once the plugin keeps large integers exact | +| NSD-16 candidate | the CouchDB plugin cannot run `docGet` without an `If-None-Match` header: the bundled API document marks it required (the server treats it as optional: a read without it answers the document), and `runOpenApi` refuses the query with `Required parameter If-None-Match is not provided`; a value that is not the current ETag (`e2e-no-match` measured) reads the document, and a value equal to the document's current ETag (`""`) makes the server answer 304 with no body, which fails the query with `status: 304`. So a read of a document cannot be made without a header the user has no use for. Measured on 3.0.0-e2e and 3.0.1-e2e against the CouchDB sidecar. The id is provisional until the owner assigns one | `datasource/plugin-couchdb.spec.ts` D14f, `defect` annotation `NSD-16 candidate` (characterisation, passes today after controls that the server reads the document without the header and answers 304 to the current ETag); it changes when the header is optional | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/fixtures/dsl/plugins/couchdb/couchdbDeleteQuery.json b/e2e/fixtures/dsl/plugins/couchdb/couchdbDeleteQuery.json new file mode 100644 index 0000000000..e257264c00 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/couchdb/couchdbDeleteQuery.json @@ -0,0 +1,15 @@ +{ + "compType": "couchdb", + "comp": { + "actionName": "delete", + "action": { + "path_@_db": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/couchdb/couchdbDocDeleteQuery.json b/e2e/fixtures/dsl/plugins/couchdb/couchdbDocDeleteQuery.json new file mode 100644 index 0000000000..71622c4f59 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/couchdb/couchdbDocDeleteQuery.json @@ -0,0 +1,19 @@ +{ + "compType": "couchdb", + "comp": { + "actionName": "docDelete", + "action": { + "path_@_db": "", + "path_@_docid": "", + "header_@_If-Match": "", + "query_@_rev": "", + "query_@_batch": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/couchdb/couchdbDocGetAllQuery.json b/e2e/fixtures/dsl/plugins/couchdb/couchdbDocGetAllQuery.json new file mode 100644 index 0000000000..5049faea4b --- /dev/null +++ b/e2e/fixtures/dsl/plugins/couchdb/couchdbDocGetAllQuery.json @@ -0,0 +1,42 @@ +{ + "compType": "couchdb", + "comp": { + "actionName": "docGetAll", + "action": { + "path_@_db": "", + "query_@_conflicts": "", + "query_@_descending": "", + "query_@_endkey": "", + "query_@_end_key": "", + "query_@_endkey_docid": "", + "query_@_end_key_doc_id": "", + "query_@_group": "", + "query_@_group_level": "", + "query_@_include_docs": "", + "query_@_attachments": "", + "query_@_att_encoding_info": "", + "query_@_inclusive_end": "", + "query_@_revs_info": "", + "query_@_key": "", + "query_@_keys": "", + "query_@_limit": "", + "query_@_reduce": "", + "query_@_skip": "", + "query_@_sorted": "", + "query_@_stable": "", + "query_@_stale": "", + "query_@_startkey": "", + "query_@_start_key": "", + "query_@_startkey_docid": "", + "query_@_start_key_doc_id": "", + "query_@_update": "", + "query_@_update_seq": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/couchdb/couchdbDocGetQuery.json b/e2e/fixtures/dsl/plugins/couchdb/couchdbDocGetQuery.json new file mode 100644 index 0000000000..7d64b10cc5 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/couchdb/couchdbDocGetQuery.json @@ -0,0 +1,29 @@ +{ + "compType": "couchdb", + "comp": { + "actionName": "docGet", + "action": { + "path_@_db": "", + "path_@_docid": "", + "header_@_If-None-Match": "", + "query_@_attachments": "", + "query_@_att_encoding_info": "", + "query_@_atts_since": "", + "query_@_conflicts": "", + "query_@_deleted_conflicts": "", + "query_@_latest": "", + "query_@_local_seq": "", + "query_@_meta": "", + "query_@_open_revs": "", + "query_@_rev": "", + "query_@_revs": "", + "query_@_revs_info": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/couchdb/couchdbDocPutQuery.json b/e2e/fixtures/dsl/plugins/couchdb/couchdbDocPutQuery.json new file mode 100644 index 0000000000..02d359ad9f --- /dev/null +++ b/e2e/fixtures/dsl/plugins/couchdb/couchdbDocPutQuery.json @@ -0,0 +1,21 @@ +{ + "compType": "couchdb", + "comp": { + "actionName": "docPut", + "action": { + "path_@_db": "", + "path_@_docid": "", + "header_@_If-Match": "", + "query_@_rev": "", + "query_@_batch": "", + "query_@_new_edits": "", + "body_@_body": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/couchdb/couchdbGetQuery.json b/e2e/fixtures/dsl/plugins/couchdb/couchdbGetQuery.json new file mode 100644 index 0000000000..386ed49974 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/couchdb/couchdbGetQuery.json @@ -0,0 +1,15 @@ +{ + "compType": "couchdb", + "comp": { + "actionName": "get", + "action": { + "path_@_db": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/couchdb/couchdbPutQuery.json b/e2e/fixtures/dsl/plugins/couchdb/couchdbPutQuery.json new file mode 100644 index 0000000000..2d8a9a4099 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/couchdb/couchdbPutQuery.json @@ -0,0 +1,18 @@ +{ + "compType": "couchdb", + "comp": { + "actionName": "put", + "action": { + "path_@_db": "", + "query_@_q": "", + "query_@_n": "", + "query_@_partitioned": "" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/scripts/run-in-docker.sh b/e2e/scripts/run-in-docker.sh index b31cc59a06..87d580ba3d 100755 --- a/e2e/scripts/run-in-docker.sh +++ b/e2e/scripts/run-in-docker.sh @@ -23,8 +23,9 @@ ## tests); independent of E2E_INCLUDE_QUARANTINE. Nightly: E2E_INCLUDE_INSERT_ALL=1 $0 --grep @insert-all ## E2E_INCLUDE_SUPERADMIN set to 1 to also run the @superadmin tests (SEC-R16a to SEC-R16d, the instance super admin; ## independent of the other flags). Run: E2E_INCLUDE_SUPERADMIN=1 $0 --grep @superadmin -## E2E_INCLUDE_NODE_SERVICE_SIDECARS set to 1 to also start the sidecars of the node-service data sources whose protocol is not HTTP -## (today a Firebird server, FIREBIRD_IMAGE below, and a libSQL server, LIBSQL_IMAGE below) and run their @node-service-sidecar tests; independent of the +## E2E_INCLUDE_NODE_SERVICE_SIDECARS set to 1 to also start the sidecars of the node-service data sources: real servers a plugin can be pointed at, for plugins +## whose protocol the echo cannot serve (Firebird: a wire protocol) or whose real behaviour the echo's canned answers say nothing about (libSQL, CouchDB) +## (today a Firebird server, FIREBIRD_IMAGE below, a libSQL server, LIBSQL_IMAGE below, and a CouchDB server, COUCHDB_IMAGE below) and run their @node-service-sidecar tests; independent of the ## other flags, default stack only (any other profile is an error). Without it the run starts none of them, ## neither lists nor runs those tests, and pulls no extra image. ## Run only these: E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 $0 --grep @node-service-sidecar @@ -43,6 +44,7 @@ ## POSTGRES_IMAGE PostgreSQL sidecar for the data source tests (pinned by digest) ## FIREBIRD_IMAGE Firebird sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS ## LIBSQL_IMAGE libSQL server (sqld) sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS +## COUCHDB_IMAGE CouchDB sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS ## E2E_HOST_PORT also publish the app on 127.0.0.1: to look at it in a browser while the run lasts ## ## Set by the script for each run (a value of the caller is overwritten; the password is new every run, never printed, @@ -86,6 +88,15 @@ ## must equal LIBSQL in e2e/src/constants.ts. The database lives in a tmpfs (the image declares /var/lib/sqld a volume, which `docker rm -f` would ## leave behind), and `cleanup` removes the container however the run ends. Without the flag nothing of this runs. ## +## Only with E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 it also starts a CouchDB sidecar (COUCHDB_IMAGE) under the alias e2e-couchdb, port 5984: the target of the CouchDB data +## source of node-service (a real Apache CouchDB server in place of the echo's canned answers). It starts after the libSQL sidecar and is reached exactly like it: +## `--add-host e2e-couchdb:` for the app container and the runner, and the alias as E2E_COUCHDB_HOST for the runner. The image makes one server admin from +## COUCHDB_USER and COUCHDB_PASSWORD (throw-away constants that must equal COUCHDB in e2e/src/constants.ts). A fresh single node has none of the system databases +## (`_all_dbs` answers an empty list), so the readiness step creates `_users`, `_replicator` and `_global_changes` through the real HTTP API (PUT answers 201, or +## 412 when it exists already) and is ready when `_all_dbs` lists all three; it runs inside the sidecar container (the image has curl) against 127.0.0.1, and is repeated +## until it succeeds or STARTUP_TIMEOUT passes. The data lives in a tmpfs (the image declares /opt/couchdb/data a volume, which `docker rm -f` would leave behind), +## and `cleanup` removes the container however the run ends. Without the flag nothing of this runs. +## ## Not covered: Firefox and WebKit (only Chromium runs), the multi-container compose setup, databases other than ## PostgreSQL. ## @@ -130,6 +141,26 @@ readonly LIBSQL_JWT_PUBLIC_KEY="GC25tiEOubxlGdpbkc60UOXqUQeepEUWZmAbEKjt1rQ" readonly LIBSQL_TOKEN="eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJhIjoicncifQ.tlvnzqEfO2pnCYHReSfLIQ3dHk393fsOH5hLtLo4ZkJWJV6b9q9Zf56QbS5spbT2G9XuzYQaVsZqO4jUVSsPAw" # The image's data directory, mounted as a tmpfs so that no anonymous volume outlives the run readonly LIBSQL_DATA_DIR="/var/lib/sqld" +# CouchDB sidecar of the @node-service-sidecar tests, started only with E2E_INCLUDE_NODE_SERVICE_SIDECARS. The image is Apache CouchDB 3.5.1 by tag and digest. It makes +# one server admin from COUCHDB_USER and COUCHDB_PASSWORD, throw-away values that must equal COUCHDB in e2e/src/constants.ts (the foundation tests check it); the +# container dies with the run. COUCHDB_PORT is the image's own HTTP port. +readonly DEFAULT_COUCHDB_IMAGE="couchdb:3.5.1@sha256:ccea1e8035bf7afd68336e24056a1ca9c1c46d7abe42da686322c0ac7218e5c2" +readonly COUCHDB_IMAGE="${COUCHDB_IMAGE:-$DEFAULT_COUCHDB_IMAGE}" +readonly COUCHDB_ALIAS="e2e-couchdb" +readonly COUCHDB_PORT=5984 +readonly COUCHDB_USER="e2eadmin" +readonly COUCHDB_PASSWORD="e2e-couchdb-password" +# The system databases a fresh single node lacks; the readiness step creates them (names equal COUCHDB.SYSTEM_DATABASES in e2e/src/constants.ts) +readonly COUCHDB_SYSTEM_DATABASES=("_users" "_replicator" "_global_changes") +# The statuses of a PUT of a database that count as "there": 201 created, 412 already exists +readonly COUCHDB_HTTP_CREATED="201" +readonly COUCHDB_HTTP_EXISTS="412" +# Seconds a single readiness request may take to connect and in total (a local server answers in milliseconds); small against POLL_INTERVAL and STARTUP_TIMEOUT +# so that a stalled request ends the attempt and the wait loop checks its deadline again +readonly PROBE_CONNECT_TIMEOUT=2 +readonly PROBE_REQUEST_TIMEOUT=5 +# The image's data directory, mounted as a tmpfs so that no anonymous volume outlives the run +readonly COUCHDB_DATA_DIR="/opt/couchdb/data" # The instance super admin of the throw-away stack; the domain equals TEST_EMAIL_DOMAIN in e2e/src/constants.ts; the suite # reads the name from E2E_SUPERUSER_USERNAME (SUPER_ADMIN_ENV). The password is generated per run (generate_superuser_password). readonly SUPERUSER_USERNAME="e2e-superadmin@example.test" @@ -164,6 +195,7 @@ readonly RUNNER_CONTAINER="${NAME_PREFIX}-runner" readonly ECHO_CONTAINER="${NAME_PREFIX}-echo" readonly FIREBIRD_CONTAINER="${NAME_PREFIX}-fb" readonly LIBSQL_CONTAINER="${NAME_PREFIX}-libsql" +readonly COUCHDB_CONTAINER="${NAME_PREFIX}-couchdb" # The alias and port the app container and the runner use; E2E_ECHO_URL below is built from them (the suite reads it by ECHO_ENV in e2e/src/constants.ts) readonly ECHO_ALIAS="e2e-echo" readonly ECHO_PORT=8080 @@ -173,7 +205,7 @@ readonly ECHO_HEALTH_PATH="/__e2e/health" readonly ECHO_SCRIPT="$SCRIPT_DIR/echo-server.js" # Set by start_echo: the sidecar's IP on the run network (used for --add-host of the app and the runner) ECHO_IP="" -# Set by start_firebird and start_libsql (only with E2E_INCLUDE_NODE_SERVICE_SIDECARS): the extra `--add-host` and `-e` arguments of the app and the runner. Empty otherwise. +# Set by start_firebird, start_libsql and start_couchdb (only with E2E_INCLUDE_NODE_SERVICE_SIDECARS): the extra `--add-host` and `-e` arguments of the app and the runner. Empty otherwise. SIDECAR_ADD_HOST=() SIDECAR_RUNNER_ENV=() @@ -187,7 +219,7 @@ fail() { } cleanup() { - docker rm -f "$RUNNER_CONTAINER" "$APP_CONTAINER" "$POSTGRES_CONTAINER" "$ECHO_CONTAINER" "$FIREBIRD_CONTAINER" "$LIBSQL_CONTAINER" > /dev/null 2>&1 || true + docker rm -f "$RUNNER_CONTAINER" "$APP_CONTAINER" "$POSTGRES_CONTAINER" "$ECHO_CONTAINER" "$FIREBIRD_CONTAINER" "$LIBSQL_CONTAINER" "$COUCHDB_CONTAINER" > /dev/null 2>&1 || true docker network rm "$NETWORK" > /dev/null 2>&1 || true } trap cleanup EXIT @@ -336,7 +368,7 @@ start_firebird() { wait_for_firebird() { local waited=0 - until echo "SELECT COUNT(*) FROM FB_ITEMS;" | docker exec -i "$FIREBIRD_CONTAINER" /opt/firebird/bin/isql -b -user "$FIREBIRD_USER" -password "$FIREBIRD_PASSWORD" "127.0.0.1:${FIREBIRD_DATABASE_PATH}" > /dev/null 2>&1; do + until echo "SELECT COUNT(*) FROM FB_ITEMS;" | docker exec -i "$FIREBIRD_CONTAINER" timeout -s KILL "$PROBE_REQUEST_TIMEOUT" /opt/firebird/bin/isql -b -user "$FIREBIRD_USER" -password "$FIREBIRD_PASSWORD" "127.0.0.1:${FIREBIRD_DATABASE_PATH}" > /dev/null 2>&1; do if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then docker logs --tail "$LOG_TAIL_LINES" "$FIREBIRD_CONTAINER" >&2 || true fail "the Firebird sidecar did not become ready within ${STARTUP_TIMEOUT}s" @@ -365,7 +397,7 @@ start_libsql() { # curl and no shell tools of use): ready when it answers 200 with the integer 1 for `select 1`. wait_for_libsql() { local waited=0 - local probe="fetch(process.env.LIBSQL_PROBE_URL + '/v2/pipeline', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + process.env.LIBSQL_PROBE_TOKEN }, body: JSON.stringify({ requests: [{ type: 'execute', stmt: { sql: 'select 1' } }, { type: 'close' }] }) }).then((r) => r.text().then((t) => process.exit(r.ok && t.includes('\"value\":\"1\"') ? 0 : 1)), () => process.exit(1))" + local probe="fetch(process.env.LIBSQL_PROBE_URL + '/v2/pipeline', { signal: AbortSignal.timeout($((PROBE_REQUEST_TIMEOUT * 1000))), method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + process.env.LIBSQL_PROBE_TOKEN }, body: JSON.stringify({ requests: [{ type: 'execute', stmt: { sql: 'select 1' } }, { type: 'close' }] }) }).then((r) => r.text().then((t) => process.exit(r.ok && t.includes('\"value\":\"1\"') ? 0 : 1)), () => process.exit(1))" until docker exec -e LIBSQL_PROBE_URL="http://${LIBSQL_ALIAS}:${LIBSQL_PORT}" -e LIBSQL_PROBE_TOKEN="$LIBSQL_TOKEN" "$ECHO_CONTAINER" node -e "$probe" > /dev/null 2>&1; do if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then docker logs --tail "$LOG_TAIL_LINES" "$LIBSQL_CONTAINER" >&2 || true @@ -377,6 +409,60 @@ wait_for_libsql() { log "libSQL sidecar ready after ${waited}s" } +# A fresh single-node CouchDB has an admin and no system databases. This probe is idempotent and runs inside the sidecar over 127.0.0.1 (the image has curl): +# the server must answer `_up`, each system database is created through the real API (it counts only when the server answers 201 created or 412 already +# exists; any other answer, or none, is "not ready yet"), and `_all_dbs` must list all of them. Every curl carries a connect and a total time limit, so a +# stalled request ends the probe and the loop of wait_for_couchdb re-checks its deadline instead of blocking past STARTUP_TIMEOUT. +couchdb_curl() { + docker exec "$COUCHDB_CONTAINER" curl --connect-timeout "$PROBE_CONNECT_TIMEOUT" --max-time "$PROBE_REQUEST_TIMEOUT" -u "${COUCHDB_USER}:${COUCHDB_PASSWORD}" "$@" +} + +couchdb_probe() { + local base="http://127.0.0.1:${COUCHDB_PORT}" database status listed + couchdb_curl -sf "${base}/_up" > /dev/null || return 1 + for database in "${COUCHDB_SYSTEM_DATABASES[@]}"; do + status="$(couchdb_curl -s -o /dev/null -w '%{http_code}' -X PUT "${base}/${database}")" || return 1 + case "$status" in + "$COUCHDB_HTTP_CREATED" | "$COUCHDB_HTTP_EXISTS") ;; + *) return 1 ;; + esac + done + listed="$(couchdb_curl -sf "${base}/_all_dbs")" || return 1 + for database in "${COUCHDB_SYSTEM_DATABASES[@]}"; do + case "$listed" in + *"\"${database}\""*) ;; + *) return 1 ;; + esac + done +} + +# The sidecar is started after the libSQL one. The tests make their own databases. +start_couchdb() { + log "Starting $COUCHDB_IMAGE as $COUCHDB_CONTAINER (alias $COUCHDB_ALIAS, port $COUCHDB_PORT)" + docker run -d --name "$COUCHDB_CONTAINER" --network "$NETWORK" --network-alias "$COUCHDB_ALIAS" \ + --tmpfs "$COUCHDB_DATA_DIR" -e COUCHDB_USER="$COUCHDB_USER" -e COUCHDB_PASSWORD="$COUCHDB_PASSWORD" \ + "$COUCHDB_IMAGE" > /dev/null + local couchdb_ip + couchdb_ip="$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$COUCHDB_CONTAINER")" + [ -n "$couchdb_ip" ] || fail "no IP address for $COUCHDB_CONTAINER on $NETWORK" + SIDECAR_ADD_HOST+=(--add-host "${COUCHDB_ALIAS}:${couchdb_ip}") + SIDECAR_RUNNER_ENV+=(-e "E2E_COUCHDB_HOST=${COUCHDB_ALIAS}") + log "CouchDB sidecar is $COUCHDB_ALIAS = $couchdb_ip" +} + +wait_for_couchdb() { + local waited=0 + until couchdb_probe > /dev/null 2>&1; do + if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then + docker logs --tail "$LOG_TAIL_LINES" "$COUCHDB_CONTAINER" >&2 || true + fail "the CouchDB sidecar did not become ready within ${STARTUP_TIMEOUT}s" + fi + sleep "$POLL_INTERVAL" + waited=$((waited + POLL_INTERVAL)) + done + log "CouchDB sidecar ready after ${waited}s" +} + wait_for_app() { local waited=0 log "Waiting for $READY_PATH (at most ${STARTUP_TIMEOUT}s)" @@ -440,6 +526,9 @@ fi if node_service_sidecars_enabled; then start_libsql fi +if node_service_sidecars_enabled; then + start_couchdb +fi start_app wait_for_postgres wait_for_echo @@ -449,5 +538,8 @@ fi if node_service_sidecars_enabled; then wait_for_libsql fi +if node_service_sidecars_enabled; then + wait_for_couchdb +fi wait_for_app run_tests "$@" diff --git a/e2e/src/constants.ts b/e2e/src/constants.ts index 696370c309..65620d1ed9 100644 --- a/e2e/src/constants.ts +++ b/e2e/src/constants.ts @@ -220,9 +220,9 @@ export const TAGS = { */ NODE_SERVICE: "@node-service", /** - * The node-service data source tests that need a sidecar of their own: the plugin's protocol is not HTTP (the Firebird tests, - * `tests/datasource/plugin-firebird.spec.ts`) or the test wants a real server instead of canned answers (the libSQL server tests, - * `tests/datasource/plugin-turso-libsql.spec.ts`). Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of + * The node-service data source tests that need a real server of their own to be pointed at: the echo cannot serve the plugin's protocol (the Firebird tests, a + * wire protocol, `tests/datasource/plugin-firebird.spec.ts`) or its canned answers say nothing about the real server's behaviour (the libSQL server tests, + * `tests/datasource/plugin-turso-libsql.spec.ts`, and the CouchDB server tests, `tests/datasource/plugin-couchdb.spec.ts`). Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of * the default run (neither listed nor run, and the run script starts no such sidecar), in only with * `E2E_INCLUDE_NODE_SERVICE_SIDECARS` (see src/run-selection.ts and scripts/run-in-docker.sh). */ @@ -237,7 +237,7 @@ export const RUN_FLAGS = { /** Enterprise profile only: run SEC-E05 (`@enterprise-takeover`) and nothing else. */ INCLUDE_ENTERPRISE_TAKEOVER: "E2E_INCLUDE_ENTERPRISE_TAKEOVER", /** - * Default stack only: also start the sidecars of the node-service data sources (Firebird, a libSQL server) and run + * Default stack only: also start the sidecars of the node-service data sources (Firebird, a libSQL server, a CouchDB server) and run * their `@node-service-sidecar` tests. Without it the run starts none of them. */ INCLUDE_NODE_SERVICE_SIDECARS: "E2E_INCLUDE_NODE_SERVICE_SIDECARS", @@ -328,6 +328,20 @@ export const LIBSQL = { "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJhIjoicncifQ.QtYpcj3lGU5Rtry83fcTaI-e_WwmcvSDEFrysDlxiHGMfb_GNaJTzOvuSgas_Hivmf4D68Azw-lK7Te4vuIABg", } as const; +/** + * The CouchDB sidecar that scripts/run-in-docker.sh starts on the run's network ONLY when `E2E_INCLUDE_NODE_SERVICE_SIDECARS` is set. The run script + * passes the host name (the sidecar's network alias); the rest is fixed there and must equal the `COUCHDB_*` values of the script. The server has one + * admin, made by the image from `USERNAME` and `PASSWORD`: throw-away values (the container is removed when the run ends and holds no other data), + * never real secrets. A fresh single node has no system databases, so the run script creates `SYSTEM_DATABASES` while it waits for the server. + */ +export const COUCHDB = { + HOST_ENV: "E2E_COUCHDB_HOST", + PORT: 5984, + USERNAME: "e2eadmin", + PASSWORD: "e2e-couchdb-password", + SYSTEM_DATABASES: ["_users", "_replicator", "_global_changes"], +} as const; + export const SEEDED_ITEM_NAMES = ["alpha", "beta"] as const; /** Component type, panel search text, drop position and generated name of the button the editor tests drop. */ diff --git a/e2e/src/datasource/couchdb.ts b/e2e/src/datasource/couchdb.ts new file mode 100644 index 0000000000..13c82f049d --- /dev/null +++ b/e2e/src/datasource/couchdb.ts @@ -0,0 +1,93 @@ +import { COUCHDB, RUN_FLAGS } from "../constants"; + +/** Where a CouchDB data source connects: the CouchDB sidecar of the run, as the app container reaches it (by the sidecar's network alias, over plain HTTP). */ +export interface CouchdbConnection { + /** `http://:`, no trailing slash: the plugin appends the operation's path. */ + serverURL: string; + /** The server admin of the sidecar (throw-away). */ + username: string; + password: string; +} + +/** The sidecar's host variable is not set: the run did not start the CouchDB sidecar. */ +export class CouchdbSidecarMissingError extends Error { + constructor() { + super( + `${COUCHDB.HOST_ENV} is not set: the CouchDB sidecar was not started. Run the suite through e2e/scripts/run-in-docker.sh with ${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}=1.`, + ); + this.name = "CouchdbSidecarMissingError"; + } +} + +/** + * The connection to the run's CouchDB sidecar from the environment. Throws `CouchdbSidecarMissingError` when the run script did not set the + * host variable (it does so only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`), so a test that was selected without its sidecar fails loudly + * instead of passing vacuously or connecting to a name that happens to resolve elsewhere. Reads only `env`. + */ +export function couchdbConnection(env: NodeJS.ProcessEnv = process.env): CouchdbConnection { + const host = env[COUCHDB.HOST_ENV]; + if (!host) throw new CouchdbSidecarMissingError(); + return { serverURL: `http://${host}:${COUCHDB.PORT}`, username: COUCHDB.USERNAME, password: COUCHDB.PASSWORD }; +} + +/** How long a direct call to the sidecar may take before it is abandoned: a local server answers in milliseconds. */ +const DIRECT_CALL_TIMEOUT_MS = 10_000; + +/** The answer of a direct call: the status line and the body parsed as JSON (or the text when it is not JSON). */ +export interface CouchdbDirectAnswer { + status: number; + statusText: string; + body: unknown; +} + +/** What a direct call sends besides the method and the path. */ +export interface CouchdbDirectOptions { + /** The JSON body, sent as `application/json`. */ + json?: unknown; + /** Further request headers (e.g. `If-Match`), sent as given. */ + headers?: Record; + /** The credentials of the Basic `Authorization` header; none are sent when it is `undefined`. */ + credentials?: { username: string; password: string }; +} + +/** + * One HTTP call to the sidecar from the TEST process (`path` starts with `/`, e.g. `/_all_dbs` or `//?rev=...`). This is what the + * plugin sends, minus the plugin: it is the control that shows what the server itself answers, next to what the plugin makes of it for the + * app, and the way a test sets up and removes its own databases. The runner reaches the sidecar by the same alias the app container does. + */ +export async function couchdbDirect( + connection: Pick, + method: string, + path: string, + options: CouchdbDirectOptions = {}, +): Promise { + const headers: Record = { ...options.headers }; + if (options.json !== undefined) headers["Content-Type"] = "application/json"; + if (options.credentials) { + headers.Authorization = `Basic ${Buffer.from(`${options.credentials.username}:${options.credentials.password}`).toString("base64")}`; + } + const response = await fetch(`${connection.serverURL}${path}`, { + method, + headers, + body: options.json === undefined ? undefined : JSON.stringify(options.json), + signal: AbortSignal.timeout(DIRECT_CALL_TIMEOUT_MS), + }); + const text = await response.text(); + let body: unknown = text; + try { + body = JSON.parse(text); + } catch { + // not JSON: the text itself is the body + } + return { status: response.status, statusText: response.statusText, body }; +} + +/** `couchdbDirect` with the sidecar's admin, for what a test does to its own databases (creating one, removing it afterwards). */ +export async function couchdbAdmin( + connection: CouchdbConnection, + method: string, + path: string, + options: Pick = {}, +): Promise { + return couchdbDirect(connection, method, path, { ...options, credentials: { username: connection.username, password: connection.password } }); +} diff --git a/e2e/src/run-selection.ts b/e2e/src/run-selection.ts index dddd93a376..7ce044cc6b 100644 --- a/e2e/src/run-selection.ts +++ b/e2e/src/run-selection.ts @@ -9,7 +9,7 @@ export interface RunFlags { /** Tests tagged `@superadmin` (SEC-R16a to SEC-R16d: they break a stack that holds more than ~420 workspaces, D-47). */ includeSuperAdmin: boolean; /** - * Tests tagged `@node-service-sidecar` (the node-service data sources that need a sidecar of their own, Firebird): they need the + * Tests tagged `@node-service-sidecar` (the node-service data sources that need a real server of their own: Firebird, libSQL, CouchDB): they need the * run script to start that sidecar, which it does only for this flag. Default stack only: the other stacks select their own tags. */ includeNodeServiceSidecars: boolean; diff --git a/e2e/tests/datasource/plugin-couchdb.spec.ts b/e2e/tests/datasource/plugin-couchdb.spec.ts new file mode 100644 index 0000000000..f8396f4633 --- /dev/null +++ b/e2e/tests/datasource/plugin-couchdb.spec.ts @@ -0,0 +1,706 @@ +import { randomBytes } from "node:crypto"; +import { connect } from "node:net"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, COUCHDB, TAGS } from "../../src/constants"; +import { appDsl, button, nodePluginQuery, stackItems } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { boundText, boundTextTestId, openSeededView } from "../../src/components/scenario"; +import { couchdbAdmin, couchdbConnection, couchdbDirect, type CouchdbConnection } from "../../src/datasource/couchdb"; +import { expect, test } from "../../src/fixtures"; + +/** + * D14: the CouchDB plugin of node-service (`server/node-service/src/plugins/couchdb/index.ts`, the plugin id `couchdb`, an OpenAPI wrapper) run + * against a REAL Apache CouchDB server, the sidecar of the run (`scripts/run-in-docker.sh` starts it only with + * `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`; image, admin and setup in the README, "CouchDB sidecar"). D8a to D8i run the same plugin against the + * echo's canned answers; here the answers are the server's own. Every connection of these tests goes to the sidecar: the data source URL is + * `http://:5984` from `E2E_COUCHDB_HOST`, never a placeholder. Each test makes its own database, named by a per-test marker, and removes + * it in a `finally`, so parallel tests share nothing; the sidecar's system databases are only read. + * + * "Direct" calls (`couchdbDirect`, `couchdbAdmin`) go from the test process to the sidecar. They are the controls that show what the server + * itself answers (a status code the plugin hides, the stored document), next to what the plugin makes of it for the app, and the way a test + * sets up and removes what it needs. + * + * Measured on the images `3.0.0-e2e` and `3.0.1-e2e` against CouchDB 3.5.1 (the plugin's bundled document is the 3.1.1 one): + * - Every operation the plugin runs answers the JSON body of the server's answer as the query's data (`success: true`, `queryCode: "OK"`). + * - An HTTP error answer that carries a body is ALSO reported as `success: true`, with the error body as the data: 412 (database exists), 404 + * (missing database or document), 409 (stale revision), 401 (wrong password) all arrive this way (NSD-4 candidate, the defect D7d shows + * against a canned answer). The status code is lost; the body's `error` member is the only sign. + * - An error answer WITHOUT a body fails the query: a conditional read whose ETag still matches is `304` and the query fails with `status: 304`. + * - `docGet` cannot run without an `If-None-Match` header: the bundled document marks it required (the server treats it as optional: a read + * without it answers the document), and the plugin refuses the query with its own message (NSD-16 candidate). A value that is not the + * current ETag (`e2e-no-match` here) reads the document; the current ETag is a 304. + * - The plugin sends the Basic credentials of the data source (the admin of the sidecar); `_all_dbs` of a fresh node lists the three system + * databases the run script creates, plus every database of the tests running at that time, so the exact lists below are scoped by a key range. + * + * Not covered: the JWT credential (the image's default configuration has no JWT authentication handler, so a token cannot be accepted); cookie + * sessions (the plugin sends the `Authorization` header only); replication, design documents, partitions, attachments, bulk operations and the + * rest of the document's operations (the query form offers them; these tests run the ones named below). + */ +/** Candidate defect: an HTTP error answer that carries a body is returned as the query's data with `success: true`. */ +const ERROR_BODY_DEFECT = { type: "defect", description: "NSD-4 candidate" } as const; +/** Candidate defect: the bundled document marks the `If-None-Match` header of `docGet` required, so the query cannot run without it, and a matching ETag (304) fails it. */ +const IF_NONE_MATCH_DEFECT = { type: "defect", description: "NSD-16 candidate" } as const; + +const HTTP_OK = 200; +const HTTP_CREATED = 201; +const HTTP_NOT_MODIFIED = 304; +const HTTP_UNAUTHORIZED = 401; +const HTTP_NOT_FOUND = 404; +const HTTP_FORBIDDEN = 403; +const HTTP_CONFLICT = 409; +const HTTP_PRECONDITION_FAILED = 412; +const QUERY_CODE_OK = "OK"; +const QUERY_CODE_FAILED = "FAILED"; +const MARKER_BYTES = 4; +const QUERY_ID = "q1"; +const QUERY_NAME = "q"; + +/** A password the sidecar's admin does not have: the control that a refusal is about the credential. */ +const WRONG_PASSWORD = "e2e-wrong-password"; + +/** The form the server stores an admin's password in once it has hashed it. */ +const HASHED_PASSWORD = /^-pbkdf2/; + +/** Failed logins of one account after which CouchDB 3.5 locks it (the next login is refused with 403, whatever its password). */ +const LOCKOUT_FAILURES = 5; + +/** The server's own error bodies (CouchDB 3.5.1): what the plugin returns as data for the answers below, and what a direct call shows with its status. */ +const SERVER_ERRORS = { + /** 412 for a `PUT` of a database that exists. */ + DATABASE_EXISTS: { error: "file_exists", reason: "The database could not be created, the file already exists." }, + /** 409 for a write or a delete with a revision that is not the current one. */ + CONFLICT: { error: "conflict", reason: "Document update conflict." }, + /** 404 for any call on a database that does not exist. */ + DATABASE_MISSING: { error: "not_found", reason: "Database does not exist." }, + /** 404 for a read of a document that was never written. */ + DOCUMENT_MISSING: { error: "not_found", reason: "missing" }, + /** 404 for a read of a document whose latest revision is a deletion. */ + DOCUMENT_DELETED: { error: "not_found", reason: "deleted" }, + /** 401 for a wrong password. */ + BAD_PASSWORD: { error: "unauthorized", reason: "Name or password is incorrect." }, + /** 403 for a login of an account that failed five times in a row (the right password is refused too). */ + ACCOUNT_LOCKED: { error: "forbidden", reason: "Account is temporarily locked due to multiple authentication failures" }, + /** 401 for a call without credentials on the server level. */ + NOT_SERVER_ADMIN: { error: "unauthorized", reason: "You are not a server admin." }, +} as const; + +/** The plugin's text for a query that omits the required header of `docGet`, and for the 304 answer (no body). */ +const MISSING_HEADER_MESSAGE = "Required parameter If-None-Match is not provided"; +const NOT_MODIFIED_MESSAGE = "status: 304"; + +/** A header value that is not the current ETag of any document: the workaround that lets `docGet` run (NSD-16 candidate). */ +const NO_MATCH_ETAG = "e2e-no-match"; + +/** The revision a first write answers (`1-` and the md5 of the body, 32 hex digits), and the one of an update or a delete. */ +const FIRST_REVISION = /^1-[0-9a-f]{32}$/; +const SECOND_REVISION = /^2-[0-9a-f]{32}$/; +const THIRD_REVISION = /^3-[0-9a-f]{32}$/; + +/** The members of the information a database answers (`GET /`), CouchDB 3.5.1. */ +const DATABASE_INFO_KEYS = ["cluster", "compact_running", "db_name", "disk_format_version", "doc_count", "doc_del_count", "instance_start_time", "props", "purge_seq", "sizes", "update_seq"]; + +/** The `ok` answer of a database create or delete. */ +const OK = { ok: true }; + +/** A port of the sidecar's host where nothing listens: the control that a refused connection is seen as one. */ +const CLOSED_PORT = 5985; +const CONNECT_TIMEOUT_MS = 5000; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +/** A database name of this test only (CouchDB: lower case letters, digits, `_`; it must start with a letter). */ +function uniqueDatabase(): string { + return `e2e_couch_${uniqueMarker()}`; +} + +/** One saved query: the recording's variant (`""` is the editor's default, `allDBs`) and the action's fields over the recorded defaults. */ +interface CouchQuery { + variant: string; + action: Record; +} + +/** The recorded variants of the operations these tests run (`recordedPluginQuery("couchdb", variant)`). */ +const VARIANT = { + ALL_DBS: "", + PUT: "Put", + GET: "Get", + DELETE: "Delete", + DOC_PUT: "DocPut", + DOC_GET: "DocGet", + DOC_DELETE: "DocDelete", + DOC_GET_ALL: "DocGetAll", +} as const; + +/** The queries of the operations, with the action fields the form keys them by (`path_@_`, `query_@_`, `header_@_`, `body_@_`). */ +const allDbs = (action: Record = {}): CouchQuery => ({ variant: VARIANT.ALL_DBS, action }); +const putDatabase = (db: string): CouchQuery => ({ variant: VARIANT.PUT, action: { "path_@_db": db } }); +const getDatabase = (db: string): CouchQuery => ({ variant: VARIANT.GET, action: { "path_@_db": db } }); +const deleteDatabase = (db: string): CouchQuery => ({ variant: VARIANT.DELETE, action: { "path_@_db": db } }); +const putDocument = (db: string, docid: string, body: unknown, extra: Record = {}): CouchQuery => ({ + variant: VARIANT.DOC_PUT, + action: { "path_@_db": db, "path_@_docid": docid, "body_@_body": JSON.stringify(body), ...extra }, +}); +const getDocument = (db: string, docid: string, extra: Record = {}): CouchQuery => ({ + variant: VARIANT.DOC_GET, + action: { "path_@_db": db, "path_@_docid": docid, "header_@_If-None-Match": NO_MATCH_ETAG, ...extra }, +}); +const deleteDocument = (db: string, docid: string, extra: Record): CouchQuery => ({ + variant: VARIANT.DOC_DELETE, + action: { "path_@_db": db, "path_@_docid": docid, ...extra }, +}); +const listDocuments = (db: string, extra: Record = {}): CouchQuery => ({ + variant: VARIANT.DOC_GET_ALL, + action: { "path_@_db": db, ...extra }, +}); + +/** The credentials a data source holds when they are not the sidecar's admin. */ +interface Credentials { + username?: string; + password?: string; +} + +/** The data source fields of the sidecar over the recorded form body; the JWT field is left out (the document lists it with the Basic one as one requirement, D8f). */ +function sidecarConfig(overrides: Credentials = {}): Record { + const sidecar = couchdbConnection(); + return { + serverURL: sidecar.serverURL, + "BasicAuth.username": overrides.username ?? sidecar.username, + "BasicAuth.password": overrides.password ?? sidecar.password, + "JwtAuth.value": undefined, + }; +} + +async function couchdbDatasource(page: Page, apiUser: RegisteredUser, overrides: Credentials = {}): Promise { + return createNodePluginDatasource(page.request, { orgId: apiUser.orgId, recorded: recordedPluginDatasource("couchdb"), config: sidecarConfig(overrides) }); +} + +function savedQueries(datasourceId: string, queries: Record): ReturnType[] { + return Object.entries(queries).map(([id, query]) => + nodePluginQuery({ id, name: id, datasourceId, recorded: recordedPluginQuery("couchdb", query.variant), action: query.action }), + ); +} + +/** A saved app with one manual CouchDB query per entry of `queries` on one data source (not published: the draft runs with `viewMode: false`). */ +async function couchApp(page: Page, apiUser: RegisteredUser, queries: Record, overrides: Credentials = {}): Promise { + const datasourceId = await couchdbDatasource(page, apiUser, overrides); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: "e2e-couchdb", dsl: appDsl([], { queries: savedQueries(datasourceId, queries) }) }); + return appId; +} + +async function runDraft(page: Page, appId: string, queryId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +function expectSucceeded(answer: RawAnswer): void { + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); +} + +function expectFailed(answer: RawAnswer, message: string): void { + expectRan(answer); + expect( + { success: envelopeOf(answer).success, queryCode: envelopeOf(answer).queryCode, message: envelopeOf(answer).message, data: envelopeOf(answer).data }, + "the query failed with the measured message", + ).toEqual({ success: false, queryCode: QUERY_CODE_FAILED, message, data: null }); +} + +/** Runs a query whose answer the test asserts as data: the success state first, then the data. */ +async function runForData(page: Page, appId: string, queryId: string): Promise { + const answer = await runDraft(page, appId, queryId); + expectSucceeded(answer); + return envelopeOf(answer).data; +} + +/** The sidecar's answer to a call made as the admin. */ +async function admin(method: string, path: string, options: { json?: unknown; headers?: Record } = {}): Promise<{ status: number; body: unknown }> { + const answer = await couchdbAdmin(couchdbConnection(), method, path, options); + return { status: answer.status, body: answer.body }; +} + +/** Makes a database straight on the sidecar and checks the server created it (201). */ +async function createDirect(db: string): Promise { + expect((await admin("PUT", `/${db}`)).status, `the server created ${db}`).toBe(HTTP_CREATED); +} + +/** Removes a test's database whatever state the test ended in (404 when it is already gone is fine). */ +async function removeDirect(db: string): Promise { + const { status } = await admin("DELETE", `/${db}`); + expect([HTTP_OK, HTTP_NOT_FOUND], `removing ${db}`).toContain(status); +} + +/** Writes a document straight on the sidecar (a database of the test) and returns its revision. */ +async function putDirect(db: string, docid: string, body: object): Promise { + const answer = await admin("PUT", `/${db}/${docid}`, { json: body }); + expect(answer.status, `the server stored ${docid}`).toBe(HTTP_CREATED); + return (answer.body as { rev: string }).rev; +} + +/** A character above every name character of the tests: appended to a prefix it closes the key range of the names that start with the prefix. */ +const KEY_RANGE_END = "\uFFF0"; + +/** + * A second server admin, made through the server's configuration API (`PUT /_node/_local/_config/admins/`) for one test. CouchDB 3.5 + * temporarily locks an account after five failed logins (HTTP 403, `forbidden`), and a locked account is refused WITH the right password + * too: a test that sends a wrong password must never do it as the sidecar's own admin, which every other test uses. Only a real account is + * locked: failures for a name that does not exist are not counted (measured). + */ +async function createThrowawayAdmin(): Promise> { + const username = `e2e_admin_${uniqueMarker()}`; + const password = `e2e-throwaway-${uniqueMarker()}`; + const answer = await admin("PUT", `/_node/_local/_config/admins/${username}`, { json: password }); + expect(answer.status, `the server made the admin ${username}`).toBe(HTTP_OK); + // the server stores the password as given and hashes it a moment later; until it has, a login of the account fails (and counts toward the lockout) + try { + await expect + .poll(async () => (await admin("GET", `/_node/_local/_config/admins/${username}`)).body, { message: `the server hashed the password of ${username}` }) + .toMatch(HASHED_PASSWORD); + } catch (error) { + // the caller never gets the name, so nobody else would remove the account + await removeThrowawayAdmin(username); + throw error; + } + return { username, password }; +} + +async function removeThrowawayAdmin(username: string): Promise { + expect((await admin("DELETE", `/_node/_local/_config/admins/${username}`)).status, `the server removed the admin ${username}`).toBe(HTTP_OK); +} + +/** The key range that holds exactly the names starting with `prefix`: `list` runs it as `startkey` and `endkey` (CouchDB wants them JSON-encoded). */ +function rangeOf(prefix: string): Record { + return { "query_@_startkey": JSON.stringify(prefix), "query_@_endkey": JSON.stringify(`${prefix}${KEY_RANGE_END}`) }; +} + +/** How a TCP connection to `host:port` ended: `connected`, or the error code Node reports (`ECONNREFUSED`, ...). */ +async function tcpOutcome(host: string, port: number): Promise { + return new Promise((resolve) => { + const socket = connect({ host, port }); + socket.setTimeout(CONNECT_TIMEOUT_MS, () => { + socket.destroy(); + resolve("timeout"); + }); + socket.once("connect", () => { + socket.destroy(); + resolve("connected"); + }); + socket.once("error", (error: NodeJS.ErrnoException) => resolve(error.code ?? error.message)); + }); +} + +test.describe("CouchDB data source against a real CouchDB server", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { + test("D14a: a database is created, listed, described and deleted, and the server agrees at each step", async ({ page, apiUser }) => { + const db = uniqueDatabase(); + try { + const appId = await couchApp(page, apiUser, { + list: allDbs(rangeOf(db)), + create: putDatabase(db), + info: getDatabase(db), + remove: deleteDatabase(db), + }); + + expect(await runForData(page, appId, "list"), "before the create no database of this test is listed").toEqual([]); + expect((await admin("GET", `/${db}`)).status, "the server has no such database yet").toBe(HTTP_NOT_FOUND); + expect(await runForData(page, appId, "create"), "the create answers ok").toEqual(OK); + expect(await runForData(page, appId, "list"), "the new database is listed").toEqual([db]); + const info = (await runForData(page, appId, "info")) as Record; + expect(Object.keys(info).sort(), "the information's members").toEqual(DATABASE_INFO_KEYS); + expect({ db_name: info.db_name, doc_count: info.doc_count, doc_del_count: info.doc_del_count, compact_running: info.compact_running }, "an empty database").toEqual({ + db_name: db, + doc_count: 0, + doc_del_count: 0, + compact_running: false, + }); + const direct = await admin("GET", `/${db}`); + expect({ status: direct.status, db_name: (direct.body as { db_name: string }).db_name }, "the server's own view of the database").toEqual({ status: HTTP_OK, db_name: db }); + expect(await runForData(page, appId, "remove"), "the delete answers ok").toEqual(OK); + expect(await runForData(page, appId, "list"), "after the delete the database is not listed").toEqual([]); + expect(await admin("GET", `/${db}`), "the server no longer has it").toEqual({ status: HTTP_NOT_FOUND, body: SERVER_ERRORS.DATABASE_MISSING }); + } finally { + await removeDirect(db); + } + }); + + test("D14b: a document is created, read, updated, read at its old revision, listed and deleted, and the server holds what the plugin wrote", async ({ page, apiUser }) => { + const db = uniqueDatabase(); + const docid = "doc-1"; + const first = { title: `first-${uniqueMarker()}`, count: 1 }; + const second = { title: `second-${uniqueMarker()}`, count: 2 }; + try { + await createDirect(db); + const appId = await couchApp(page, apiUser, { + create: putDocument(db, docid, first), + read: getDocument(db, docid), + listAll: listDocuments(db, { "query_@_include_docs": "true" }), + listRows: listDocuments(db), + }); + expect(await runForData(page, appId, "listRows"), "before the create the database holds no document").toEqual({ total_rows: 0, offset: 0, rows: [] }); + + const created = (await runForData(page, appId, "create")) as { ok: boolean; id: string; rev: string }; + expect({ ok: created.ok, id: created.id }, "the create answers ok and the id").toEqual({ ok: true, id: docid }); + expect(created.rev, "the first revision").toMatch(FIRST_REVISION); + expect(await runForData(page, appId, "read"), "the document as the server stores it, with the id and revision added").toEqual({ _id: docid, _rev: created.rev, ...first }); + expect((await admin("GET", `/${db}/${docid}`)).body, "the server's own copy").toEqual({ _id: docid, _rev: created.rev, ...first }); + + // the update names the revision it replaces, as a query parameter + const updateApp = await couchApp(page, apiUser, { + update: putDocument(db, docid, second, { "query_@_rev": created.rev }), + readOld: getDocument(db, docid, { "query_@_rev": created.rev }), + read: getDocument(db, docid), + }); + const updated = (await runForData(page, updateApp, "update")) as { ok: boolean; id: string; rev: string }; + expect({ ok: updated.ok, id: updated.id }, "the update answers ok and the id").toEqual({ ok: true, id: docid }); + expect(updated.rev, "the second revision").toMatch(SECOND_REVISION); + expect(await runForData(page, updateApp, "read"), "the latest revision is the new body").toEqual({ _id: docid, _rev: updated.rev, ...second }); + expect(await runForData(page, updateApp, "readOld"), "the first revision is still readable by its revision").toEqual({ _id: docid, _rev: created.rev, ...first }); + expect(await runForData(page, appId, "listAll"), "the listing with the documents").toEqual({ + total_rows: 1, + offset: 0, + rows: [{ id: docid, key: docid, value: { rev: updated.rev }, doc: { _id: docid, _rev: updated.rev, ...second } }], + }); + + const deleteApp = await couchApp(page, apiUser, { + remove: deleteDocument(db, docid, { "query_@_rev": updated.rev }), + read: getDocument(db, docid), + }); + const removed = (await runForData(page, deleteApp, "remove")) as { ok: boolean; id: string; rev: string }; + expect({ ok: removed.ok, id: removed.id }, "the delete answers ok and the id").toEqual({ ok: true, id: docid }); + expect(removed.rev, "a delete is a third revision").toMatch(THIRD_REVISION); + expect((await admin("GET", `/${db}/${docid}`)).body, "the server: the document is deleted").toEqual(SERVER_ERRORS.DOCUMENT_DELETED); + expect(await runForData(page, appId, "listRows"), "the deleted document is not listed").toEqual({ total_rows: 0, offset: 0, rows: [] }); + } finally { + await removeDirect(db); + } + }); + + test("D14c: a stale revision answers a conflict body as a successful query and changes nothing, and the right revision on the same query succeeds", { annotation: ERROR_BODY_DEFECT }, async ({ page, apiUser }) => { + const db = uniqueDatabase(); + const docid = "doc-1"; + try { + await createDirect(db); + const revision = await putDirect(db, docid, { n: 1 }); + // two more documents for the successful controls of the delete queries + const revisionByQuery = await putDirect(db, "doc-delete-rev", { n: 1 }); + const revisionByHeader = await putDirect(db, "doc-delete-if-match", { n: 1 }); + const staleRevision = "1-00000000000000000000000000000000"; + const appId = await couchApp(page, apiUser, { + staleWrite: putDocument(db, docid, { n: 2 }, { "query_@_rev": staleRevision }), + noRevisionWrite: putDocument(db, docid, { n: 3 }), + staleDelete: deleteDocument(db, docid, { "query_@_rev": staleRevision }), + staleIfMatchDelete: deleteDocument(db, docid, { "header_@_If-Match": staleRevision }), + goodWrite: putDocument(db, docid, { n: 4 }, { "query_@_rev": revision }), + goodDeleteByQuery: deleteDocument(db, "doc-delete-rev", { "query_@_rev": revisionByQuery }), + goodDeleteByHeader: deleteDocument(db, "doc-delete-if-match", { "header_@_If-Match": revisionByHeader }), + }); + + // what the server itself says: 409 for each of the four refused calls (the controls that the answer is an error) + const direct = [ + await admin("PUT", `/${db}/${docid}?rev=${staleRevision}`, { json: { n: 2 } }), + await admin("PUT", `/${db}/${docid}`, { json: { n: 3 } }), + await admin("DELETE", `/${db}/${docid}?rev=${staleRevision}`), + await admin("DELETE", `/${db}/${docid}`, { headers: { "If-Match": staleRevision } }), + ]; + expect( + direct.map((answer) => ({ status: answer.status, body: answer.body })), + "the server's answers to the refused calls", + ).toEqual(Array.from({ length: 4 }, () => ({ status: HTTP_CONFLICT, body: SERVER_ERRORS.CONFLICT }))); + + // NSD-4 candidate: the plugin reports the 409 body as the data of a successful query + for (const query of ["staleWrite", "noRevisionWrite", "staleDelete", "staleIfMatchDelete"]) { + expect(await runForData(page, appId, query), `${query}: the error body is the data`).toEqual(SERVER_ERRORS.CONFLICT); + } + expect((await admin("GET", `/${db}/${docid}`)).body, "none of them changed the document").toEqual({ _id: docid, _rev: revision, n: 1 }); + + // positive control: the current revision on the same kind of query is accepted + const accepted = (await runForData(page, appId, "goodWrite")) as { ok: boolean; id: string; rev: string }; + expect({ ok: accepted.ok, id: accepted.id }, "the write with the current revision").toEqual({ ok: true, id: docid }); + expect(accepted.rev, "the second revision").toMatch(SECOND_REVISION); + expect((await admin("GET", `/${db}/${docid}`)).body, "the server holds the accepted write").toEqual({ _id: docid, _rev: accepted.rev, n: 4 }); + // positive controls for the two kinds of refused delete: the current revision, as a query parameter and as If-Match, deletes + for (const [query, id] of [["goodDeleteByQuery", "doc-delete-rev"], ["goodDeleteByHeader", "doc-delete-if-match"]] as const) { + const deleted = (await runForData(page, appId, query)) as { ok: boolean; id: string; rev: string }; + expect({ ok: deleted.ok, id: deleted.id }, `${query}: the delete with the current revision`).toEqual({ ok: true, id }); + expect((await admin("GET", `/${db}/${id}`)).body, `${query}: the server: the document is deleted`).toEqual(SERVER_ERRORS.DOCUMENT_DELETED); + } + } finally { + await removeDirect(db); + } + }); + + test("D14d: a missing database or document and an existing database answer their error bodies as successful queries", { annotation: ERROR_BODY_DEFECT }, async ({ page, apiUser }) => { + const db = uniqueDatabase(); + const missingDb = `${db}_missing`; + const oldDb = `${db}_old`; + const newDb = `${db}_new`; + try { + await createDirect(db); + await createDirect(oldDb); + await putDirect(db, "present", { here: true }); + const appId = await couchApp(page, apiUser, { + readPresent: getDocument(db, "present"), + readMissingDoc: getDocument(db, "absent"), + readMissingDb: getDocument(missingDb, "present"), + infoMissingDb: getDatabase(missingDb), + deleteMissingDb: deleteDatabase(missingDb), + createExisting: putDatabase(db), + infoExisting: getDatabase(db), + deleteExisting: deleteDatabase(oldDb), + createNew: putDatabase(newDb), + }); + + // the server's statuses (controls: the errors exist, and they are the specific ones) + expect( + [ + await admin("GET", `/${db}/absent`), + await admin("GET", `/${missingDb}/present`), + await admin("GET", `/${missingDb}`), + await admin("DELETE", `/${missingDb}`), + await admin("PUT", `/${db}`), + ], + "the server's answers", + ).toEqual([ + { status: HTTP_NOT_FOUND, body: SERVER_ERRORS.DOCUMENT_MISSING }, + { status: HTTP_NOT_FOUND, body: SERVER_ERRORS.DATABASE_MISSING }, + { status: HTTP_NOT_FOUND, body: SERVER_ERRORS.DATABASE_MISSING }, + { status: HTTP_NOT_FOUND, body: SERVER_ERRORS.DATABASE_MISSING }, + { status: HTTP_PRECONDITION_FAILED, body: SERVER_ERRORS.DATABASE_EXISTS }, + ]); + + expect(await runForData(page, appId, "readPresent"), "positive control: the document that exists is read").toEqual({ _id: "present", _rev: expect.stringMatching(FIRST_REVISION), here: true }); + // NSD-4 candidate: each error body is the data of a successful query + expect(await runForData(page, appId, "readMissingDoc"), "a missing document").toEqual(SERVER_ERRORS.DOCUMENT_MISSING); + expect(await runForData(page, appId, "readMissingDb"), "a document of a missing database").toEqual(SERVER_ERRORS.DATABASE_MISSING); + expect(await runForData(page, appId, "infoMissingDb"), "the information of a missing database").toEqual(SERVER_ERRORS.DATABASE_MISSING); + expect(await runForData(page, appId, "deleteMissingDb"), "the delete of a missing database").toEqual(SERVER_ERRORS.DATABASE_MISSING); + expect(await runForData(page, appId, "createExisting"), "the create of a database that exists").toEqual(SERVER_ERRORS.DATABASE_EXISTS); + expect((await admin("GET", `/${db}/present`)).status, "the refused create did not touch the existing database").toBe(HTTP_OK); + + // positive controls through the same operations: the information of an existing database, the delete of an existing one, the create of a new one + expect(((await runForData(page, appId, "infoExisting")) as { db_name: string }).db_name, "the information of an existing database").toBe(db); + expect((await admin("GET", `/${newDb}`)).status, "before the create the new database does not exist").toBe(HTTP_NOT_FOUND); + expect(await runForData(page, appId, "createNew"), "the create of a database that does not exist").toEqual(OK); + expect((await admin("GET", `/${newDb}`)).status, "the server has the new database").toBe(HTTP_OK); + expect((await admin("GET", `/${oldDb}`)).status, "before the delete the old database exists").toBe(HTTP_OK); + expect(await runForData(page, appId, "deleteExisting"), "the delete of a database that exists").toEqual(OK); + expect((await admin("GET", `/${oldDb}`)).status, "the server no longer has the old database").toBe(HTTP_NOT_FOUND); + } finally { + await removeDirect(db); + await removeDirect(oldDb); + await removeDirect(newDb); + } + }); + + test("D14e: a wrong password answers an unauthorized body as a successful query and writes nothing, and the right password on the same queries works", { annotation: ERROR_BODY_DEFECT }, async ({ page, apiUser }) => { + const db = uniqueDatabase(); + const sidecar = couchdbConnection(); + const account = await createThrowawayAdmin(); + try { + const queries = { list: allDbs(rangeOf(db)), create: putDatabase(db) }; + const wrongApp = await couchApp(page, apiUser, queries, { ...account, password: WRONG_PASSWORD }); + const rightApp = await couchApp(page, apiUser, queries, account); + + // what the server says: 401 for a wrong password (once, so the account stays below the lockout), for a user that does not exist, and for no credential at all + const direct = [ + await couchdbDirect(sidecar, "GET", "/_all_dbs", { credentials: { username: account.username, password: WRONG_PASSWORD } }), + await couchdbDirect(sidecar, "GET", "/_all_dbs", { credentials: { username: `${account.username}_other`, password: account.password } }), + await couchdbDirect(sidecar, "GET", "/_all_dbs"), + ]; + expect( + direct.map((answer) => ({ status: answer.status, body: answer.body })), + "the server's answers to the three refused calls", + ).toEqual([ + { status: HTTP_UNAUTHORIZED, body: SERVER_ERRORS.BAD_PASSWORD }, + { status: HTTP_UNAUTHORIZED, body: SERVER_ERRORS.BAD_PASSWORD }, + { status: HTTP_UNAUTHORIZED, body: SERVER_ERRORS.NOT_SERVER_ADMIN }, + ]); + expect((await couchdbDirect(sidecar, "GET", "/_all_dbs", { credentials: account })).status, "positive control: the account's own password is accepted by the server").toBe(HTTP_OK); + + // NSD-4 candidate: the wrong password's 401 body is the data of a successful query + expect(await runForData(page, wrongApp, "list"), "the listing with the wrong password").toEqual(SERVER_ERRORS.BAD_PASSWORD); + expect(await runForData(page, wrongApp, "create"), "the create with the wrong password").toEqual(SERVER_ERRORS.BAD_PASSWORD); + expect((await admin("GET", `/${db}`)).status, "the refused create made no database").toBe(HTTP_NOT_FOUND); + + // positive control: the same two queries with the right password + expect(await runForData(page, rightApp, "list"), "the listing with the right password").toEqual([]); + expect(await runForData(page, rightApp, "create"), "the create with the right password").toEqual(OK); + expect(await runForData(page, rightApp, "list"), "and the database is there").toEqual([db]); + } finally { + await removeDirect(db); + await removeThrowawayAdmin(account.username); + } + }); + + test("D14j: five wrong passwords lock the account for the client address, and it is refused with its right password too, as a successful query (HTTP 403 body)", { annotation: ERROR_BODY_DEFECT }, async ({ page, apiUser }) => { + const sidecar = couchdbConnection(); + const account = await createThrowawayAdmin(); + try { + const queries = { list: allDbs() }; + const wrongApp = await couchApp(page, apiUser, queries, { ...account, password: WRONG_PASSWORD }); + const rightApp = await couchApp(page, apiUser, queries, account); + + const rightBefore = (await runForData(page, rightApp, "list")) as string[]; + expect(rightBefore, "before the failures the account's right password lists the databases").toEqual(expect.arrayContaining([...COUCHDB.SYSTEM_DATABASES])); + const attempts: unknown[] = []; + for (let attempt = 0; attempt < LOCKOUT_FAILURES + 1; attempt++) attempts.push(await runForData(page, wrongApp, "list")); + // NSD-4 candidate: every refusal is the data of a successful query; the sixth is the lockout's 403 body + expect(attempts, "five wrong passwords are 401 bodies, the next one is the lockout's body").toEqual([ + ...Array.from({ length: LOCKOUT_FAILURES }, () => SERVER_ERRORS.BAD_PASSWORD), + SERVER_ERRORS.ACCOUNT_LOCKED, + ]); + expect(await runForData(page, rightApp, "list"), "the right password is refused as well").toEqual(SERVER_ERRORS.ACCOUNT_LOCKED); + // measured: the server keeps the failures per account AND client address, so the runner, a different address than the app container's, is not locked yet + const fromRunner = await couchdbDirect(sidecar, "GET", "/_all_dbs", { credentials: account }); + expect(fromRunner.status, "the runner's login of the same account still works").toBe(HTTP_OK); + // the same five failures from the runner show the status the plugin hides: 401 five times, then 403 even with the right password + const runnerStatuses: number[] = []; + for (let attempt = 0; attempt < LOCKOUT_FAILURES + 1; attempt++) { + runnerStatuses.push((await couchdbDirect(sidecar, "GET", "/_all_dbs", { credentials: { ...account, password: WRONG_PASSWORD } })).status); + } + expect(runnerStatuses, "the server's statuses: five 401, then 403").toEqual([...Array.from({ length: LOCKOUT_FAILURES }, () => HTTP_UNAUTHORIZED), HTTP_FORBIDDEN]); + const lockedDirect = await couchdbDirect(sidecar, "GET", "/_all_dbs", { credentials: account }); + expect({ status: lockedDirect.status, body: lockedDirect.body }, "the right password from the locked address").toEqual({ status: HTTP_FORBIDDEN, body: SERVER_ERRORS.ACCOUNT_LOCKED }); + expect((await admin("GET", "/_all_dbs")).status, "positive control: the sidecar's own admin is not locked").toBe(HTTP_OK); + } finally { + await removeThrowawayAdmin(account.username); + } + }); + + test("D14f: docGet refuses to run without If-None-Match, a value that is not the ETag reads the document, a matching ETag fails with 304", { annotation: IF_NONE_MATCH_DEFECT }, async ({ page, apiUser }) => { + const db = uniqueDatabase(); + const docid = "doc-1"; + try { + await createDirect(db); + const revision = await putDirect(db, docid, { n: 1 }); + const appId = await couchApp(page, apiUser, { + withoutHeader: getDocument(db, docid, { "header_@_If-None-Match": "" }), + withHeader: getDocument(db, docid), + matching: getDocument(db, docid, { "header_@_If-None-Match": `"${revision}"` }), + }); + + // the server's own view (controls): the header is optional, a document without it is read, and the current ETag is 304 + const withoutHeader = await admin("GET", `/${db}/${docid}`); + expect(withoutHeader, "the server reads the document without the header").toEqual({ status: HTTP_OK, body: { _id: docid, _rev: revision, n: 1 } }); + const matchingDirect = await admin("GET", `/${db}/${docid}`, { headers: { "If-None-Match": `"${revision}"` } }); + expect(matchingDirect.status, "the server answers 304 to the current ETag").toBe(HTTP_NOT_MODIFIED); + + // NSD-16 candidate + expectFailed(await runDraft(page, appId, "withoutHeader"), MISSING_HEADER_MESSAGE); + expect(await runForData(page, appId, "withHeader"), "positive control: with a header of any other value the document is read").toEqual({ _id: docid, _rev: revision, n: 1 }); + expectFailed(await runDraft(page, appId, "matching"), NOT_MODIFIED_MESSAGE); + } finally { + await removeDirect(db); + } + }); + + test("D14g: the listing options reach the server: a key range, descending order, skip and limit, on databases and on documents", async ({ page, apiUser }) => { + const db = uniqueDatabase(); + const names = [db, `${db}_b`, `${db}_c`]; + try { + for (const name of names) await createDirect(name); + const revisions: Record = {}; + for (const docid of ["doc-a", "doc-b", "doc-c"]) revisions[docid] = await putDirect(names[0] as string, docid, { id: docid }); + const row = (docid: string): { id: string; key: string; value: { rev: string } } => ({ id: docid, key: docid, value: { rev: revisions[docid] as string } }); + const upper = JSON.stringify(`${db}${KEY_RANGE_END}`); + const lower = JSON.stringify(db); + const appId = await couchApp(page, apiUser, { + ascending: allDbs(rangeOf(db)), + descending: allDbs({ "query_@_startkey": upper, "query_@_endkey": lower, "query_@_descending": "true" }), + firstOne: allDbs({ ...rangeOf(db), "query_@_limit": "1" }), + secondOne: allDbs({ ...rangeOf(db), "query_@_skip": "1", "query_@_limit": "1" }), + unscoped: allDbs(), + firstTwoDocs: listDocuments(db, { "query_@_limit": "2" }), + secondDoc: listDocuments(db, { "query_@_skip": "1", "query_@_limit": "1" }), + lastDocFirst: listDocuments(db, { "query_@_descending": "true", "query_@_limit": "1" }), + }); + + expect(await runForData(page, appId, "ascending"), "the range in key order").toEqual(names); + expect(await runForData(page, appId, "descending"), "the same range, descending").toEqual([...names].reverse()); + expect(await runForData(page, appId, "firstOne"), "limit 1").toEqual([names[0]]); + expect(await runForData(page, appId, "secondOne"), "skip 1, limit 1").toEqual([names[1]]); + // not scoped: every database of the server, so a test running in parallel adds its own; the three system databases and these three are there + const all = (await runForData(page, appId, "unscoped")) as string[]; + expect(all, "every database is listed, the system ones and the three of this test").toEqual(expect.arrayContaining([...COUCHDB.SYSTEM_DATABASES, ...names])); + expect(all, "in key order").toEqual([...all].sort()); + // the documents of the first database + expect(await runForData(page, appId, "firstTwoDocs"), "limit 2 of three documents: the total still counts all of them").toEqual({ total_rows: 3, offset: 0, rows: [row("doc-a"), row("doc-b")] }); + expect(await runForData(page, appId, "secondDoc"), "skip 1, limit 1").toEqual({ total_rows: 3, offset: 1, rows: [row("doc-b")] }); + expect(await runForData(page, appId, "lastDocFirst"), "descending, limit 1").toEqual({ total_rows: 3, offset: 0, rows: [row("doc-c")] }); + } finally { + for (const name of names) await removeDirect(name); + } + }); + + test("D14h: the published view shows a document of the server after a click", async ({ page, apiUser }) => { + const db = uniqueDatabase(); + const docid = "doc-1"; + const title = `title-${uniqueMarker()}`; + try { + await createDirect(db); + await putDirect(db, docid, { title }); + const datasourceId = await couchdbDatasource(page, apiUser); + // before the first run `q.data` is not a document + const expression = `{{${QUERY_NAME}.data ? ${QUERY_NAME}.data.title : ""}}`; + const view = await openSeededView( + page, + apiUser.orgId, + "e2e-couchdb-view", + stackItems([ + button({ id: "b1", name: "button1", text: "Run", testId: "e2e-couchdb-run", onClickQuery: QUERY_NAME }), + boundText({ id: "t1", name: "label", expression }), + // `success` also reads `true` before the first run (measured, D5e), so only the state after the click proves anything + boundText({ id: "t2", name: "succeeded", expression: `{{String(${QUERY_NAME}.success)}}` }), + ]), + { + queries: [ + nodePluginQuery({ + id: QUERY_ID, + name: QUERY_NAME, + datasourceId, + recorded: recordedPluginQuery("couchdb", VARIANT.DOC_GET), + action: getDocument(db, docid).action, + }), + ], + }, + ); + + await expect(view.byTestId(boundTextTestId("label")), "before the click the text is empty").toHaveText(""); + await view.buttonByTestId("e2e-couchdb-run").click(); + await expect(view.byTestId(boundTextTestId("succeeded")), "after the click the query succeeded").toHaveText("true"); + await expect(view.byTestId(boundTextTestId("label")), "after the click the text shows the server's document").toHaveText(title); + } finally { + await removeDirect(db); + } + }); + + test("D14i: the runner reaches the sidecar over HTTP and TCP, and a closed port of the same host is refused", async () => { + const sidecar: CouchdbConnection = couchdbConnection(); + const host = new URL(sidecar.serverURL).hostname; + + const root = await couchdbDirect(sidecar, "GET", "/"); + + expect(root.status, "the server's root answers").toBe(HTTP_OK); + expect(root.body, "the welcome of an Apache CouchDB 3.5.1").toMatchObject({ couchdb: "Welcome", version: "3.5.1", vendor: { name: "The Apache Software Foundation" } }); + expect((await couchdbDirect(sidecar, "GET", "/_all_dbs")).status, "the server level needs credentials").toBe(HTTP_UNAUTHORIZED); + expect(await tcpOutcome(host, COUCHDB.PORT), "the sidecar's HTTP port").toBe("connected"); + expect(await tcpOutcome(host, CLOSED_PORT), "positive control: a port nothing listens on is refused").toBe("ECONNREFUSED"); + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index b5ffcd1e49..86c4607d07 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -5,7 +5,7 @@ import type { AddressInfo } from "node:net"; import { join } from "node:path"; import { expect, test } from "@playwright/test"; import { createNodePluginDatasource, LowcoderApiError, nodePluginDatasourceBody, pluginDynamicConfigRaw, testDatasourceRaw } from "../../src/api/client"; -import { API_OK, API_PATHS, FIREBIRD, LIBSQL, orgDatasourceTypesPath, RUN_FLAGS, TAGS } from "../../src/constants"; +import { API_OK, API_PATHS, COUCHDB, FIREBIRD, LIBSQL, orgDatasourceTypesPath, RUN_FLAGS, TAGS } from "../../src/constants"; import { nodePluginQuery } from "../../src/dsl/builders"; import { parsePluginRecording, @@ -16,6 +16,7 @@ import { type RecordedPluginDatasource, type RecordedPluginQuery, } from "../../src/dsl/recorded"; +import { couchdbAdmin, couchdbConnection, couchdbDirect, CouchdbSidecarMissingError } from "../../src/datasource/couchdb"; import { FIREBIRD_ITEMS, firebirdConnection, FirebirdSidecarMissingError } from "../../src/datasource/firebird"; import { LIBSQL_PIPELINE_PATH, libsqlConnection, libsqlDirect, LibsqlSidecarMissingError } from "../../src/datasource/libsql"; import { @@ -589,6 +590,8 @@ test.describe("node-service data source request helpers", { tag: [TAGS.NODE_SERV const FIREBIRD_ALIAS = "e2e-firebird"; /** The alias the run script gives the libSQL sidecar. */ const LIBSQL_ALIAS = "e2e-libsql"; +/** The alias the run script gives the CouchDB sidecar. */ +const COUCHDB_ALIAS = "e2e-couchdb"; /** The text of `scripts/run-in-docker.sh` and of `fixtures/firebird/init.sql`. */ const RUN_SCRIPT = readFileSync(join(__dirname, "..", "..", "scripts", "run-in-docker.sh"), "utf8"); @@ -779,4 +782,189 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = await new Promise((resolve) => server.close(() => resolve())); } }); + + test("couchdbConnection reads the host from the environment and builds a plain-HTTP URL with the sidecar's admin", () => { + expect(couchdbConnection({ [COUCHDB.HOST_ENV]: COUCHDB_ALIAS })).toEqual({ + serverURL: `http://${COUCHDB_ALIAS}:${COUCHDB.PORT}`, + username: COUCHDB.USERNAME, + password: COUCHDB.PASSWORD, + }); + }); + + test("couchdbConnection throws a named error that names the variable and the flag when the host is unset or empty", () => { + for (const env of [{}, { [COUCHDB.HOST_ENV]: "" }]) { + expect(() => couchdbConnection(env), `env ${JSON.stringify(env)}`).toThrow(CouchdbSidecarMissingError); + expect(() => couchdbConnection(env)).toThrow(COUCHDB.HOST_ENV); + expect(() => couchdbConnection(env)).toThrow(`${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}=1`); + } + }); + + test("the run script's CouchDB values equal COUCHDB in the constants", () => { + expect(scriptConstant("COUCHDB_ALIAS"), "alias").toBe(COUCHDB_ALIAS); + expect(Number(RUN_SCRIPT.match(/^readonly COUCHDB_PORT=(\d+)$/m)?.[1]), "port").toBe(COUCHDB.PORT); + expect(scriptConstant("COUCHDB_USER"), "admin user").toBe(COUCHDB.USERNAME); + expect(scriptConstant("COUCHDB_PASSWORD"), "admin password").toBe(COUCHDB.PASSWORD); + const systemDatabases = /^readonly COUCHDB_SYSTEM_DATABASES=\(([^)]*)\)$/m.exec(RUN_SCRIPT)?.[1] ?? ""; + expect(systemDatabases.split(" ").map((name) => name.replaceAll('"', "")), "the system databases the readiness step creates").toEqual([...COUCHDB.SYSTEM_DATABASES]); + expect(scriptConstant("DEFAULT_COUCHDB_IMAGE"), "the image is pinned by tag and digest").toMatch(/^couchdb:\d+\.\d+\.\d+@sha256:[0-9a-f]{64}$/); + expect(scriptConstant("COUCHDB_DATA_DIR"), "the data directory the image declares a volume").toBe("/opt/couchdb/data"); + expect(RUN_SCRIPT, "the data directory is a tmpfs, so no anonymous volume outlives the run").toContain('--tmpfs "$COUCHDB_DATA_DIR"'); + }); + + test("the run script starts, waits for and passes the CouchDB sidecar only under the flag, next to the other two", () => { + const lines = RUN_SCRIPT.split("\n"); + for (const fn of ["start_couchdb", "wait_for_couchdb"]) { + const calls = lines.map((line, index) => ({ line, index })).filter(({ line }) => line.trim() === fn); + expect(calls, `${fn} is called exactly once`).toHaveLength(1); + const call = calls[0] as { index: number }; + expect(lines[call.index - 1]?.trim(), `${fn} is the first line of an if node_service_sidecars_enabled block`).toBe("if node_service_sidecars_enabled; then"); + expect(lines[call.index + 1]?.trim(), `${fn} is the only line of that block`).toBe("fi"); + } + const startBody = /start_couchdb\(\) \{[\s\S]*?\n\}/.exec(RUN_SCRIPT)?.[0] ?? ""; + // `+=`, so that the entries set before stay: all three sidecars are passed to the app container and the runner + expect(startBody, "start_couchdb appends the runner's host variable").toContain(`SIDECAR_RUNNER_ENV+=(-e "${COUCHDB.HOST_ENV}=`); + expect(startBody, "start_couchdb appends the --add-host entry").toContain("SIDECAR_ADD_HOST+=(--add-host"); + const codeLines = lines.filter((line) => !line.trim().startsWith("#")).join("\n"); + expect(codeLines.match(new RegExp(COUCHDB.HOST_ENV, "g")), "the host variable is named once in the script's code, in start_couchdb").toHaveLength(1); + expect(RUN_SCRIPT, "the cleanup trap removes the container").toMatch(/docker rm -f [^\n]*"\$COUCHDB_CONTAINER"/); + expect(RUN_SCRIPT, "the readiness step is bounded by the startup timeout").toMatch(/wait_for_couchdb\(\) \{[\s\S]*?"\$waited" -ge "\$STARTUP_TIMEOUT"[\s\S]*?\n\}/); + }); + + test("every request of the sidecar readiness steps has a time limit, and the CouchDB system databases count only on 201 or 412", () => { + const functionBody = (name: string): string => new RegExp(`${name}\\(\\) \\{[\\s\\S]*?\\n\\}`).exec(RUN_SCRIPT)?.[0] ?? ""; + const curlBody = functionBody("couchdb_curl"); + const probeBody = functionBody("couchdb_probe"); + expect(curlBody, "couchdb_curl exists and runs curl in the sidecar").toContain('docker exec "$COUCHDB_CONTAINER" curl'); + expect(curlBody, "a connect limit on every CouchDB readiness curl").toContain('--connect-timeout "$PROBE_CONNECT_TIMEOUT"'); + expect(curlBody, "a total limit on every CouchDB readiness curl").toContain('--max-time "$PROBE_REQUEST_TIMEOUT"'); + // structurally: the probe reaches curl only through couchdb_curl, which is the one place that carries the limits + expect(probeBody.match(/\bcurl\b/g), "the probe names curl nowhere itself").toBeNull(); + expect(probeBody.match(/\bcouchdb_curl\b/g), "the probe's requests: _up, one PUT per system database (in a loop), the listing").toHaveLength(3); + expect(RUN_SCRIPT.match(/curl --connect-timeout/g), "no other curl of the script lacks the limits: the only curl calls are couchdb_curl's and the app's own readiness check").toHaveLength(1); + const limits = { connect: Number(RUN_SCRIPT.match(/^readonly PROBE_CONNECT_TIMEOUT=(\d+)$/m)?.[1]), request: Number(RUN_SCRIPT.match(/^readonly PROBE_REQUEST_TIMEOUT=(\d+)$/m)?.[1]) }; + const pollInterval = Number(RUN_SCRIPT.match(/^readonly POLL_INTERVAL=(\d+)$/m)?.[1]); + const startupTimeout = Number(RUN_SCRIPT.match(/^readonly STARTUP_TIMEOUT=(\d+)$/m)?.[1]); + expect(limits.connect, "a positive connect limit").toBeGreaterThan(0); + expect(limits.request, "the total limit is at least the connect limit").toBeGreaterThanOrEqual(limits.connect); + expect(limits.request, "and small against the startup timeout, so the wait loop re-checks its deadline").toBeLessThanOrEqual(startupTimeout / 10); + expect(pollInterval, "the poll interval is positive").toBeGreaterThan(0); + // the status check of the PUT: exactly 201 and 412 are accepted, anything else is "not ready yet" + expect(scriptConstant("COUCHDB_HTTP_CREATED"), "201 created").toBe("201"); + expect(scriptConstant("COUCHDB_HTTP_EXISTS"), "412 already exists").toBe("412"); + expect(probeBody, "the PUT's status is read from the answer").toContain("-w '%{http_code}' -X PUT"); + const accepted = /case "\$status" in\n([\s\S]*?)\n\s*esac/.exec(probeBody)?.[1] ?? ""; + expect( + accepted + .split("\n") + .map((line) => line.trim()) + .filter((line) => line !== ""), + "the status switch accepts exactly the two statuses and refuses everything else", + ).toEqual(['"$COUCHDB_HTTP_CREATED" | "$COUCHDB_HTTP_EXISTS") ;;', "*) return 1 ;;"]); + expect(probeBody, "the listing must hold every system database").toContain("/_all_dbs"); + // the libSQL and Firebird readiness calls are bounded the same way + expect(functionBody("wait_for_libsql"), "the libSQL readiness fetch aborts after the request limit").toContain("AbortSignal.timeout($((PROBE_REQUEST_TIMEOUT * 1000)))"); + expect(functionBody("wait_for_firebird"), "the Firebird readiness isql is bounded by the container's own timeout, with SIGKILL because isql ignores SIGTERM while it connects (a Linux coreutils tool, so the host needs none)").toContain( + 'docker exec -i "$FIREBIRD_CONTAINER" timeout -s KILL "$PROBE_REQUEST_TIMEOUT" /opt/firebird/bin/isql', + ); + const hostCommands = RUN_SCRIPT.split("\n").filter((line) => /^\s*[^#\s].*\|\s*timeout\b|^\s*timeout\b|\$\(timeout\b/.test(line)); + expect(hostCommands, "no readiness call uses a host `timeout` (macOS has none by default)").toEqual([]); + }); + + test("the CouchDB recordings are the editor's saved query per operation, with no value of the recording session", () => { + const expectations: { variant: string; action: string; keys: string[] }[] = [ + { variant: "", action: "allDBs", keys: ["query_@_descending", "query_@_endkey", "query_@_end_key", "query_@_limit", "query_@_skip", "query_@_startkey", "query_@_start_key"] }, + { variant: "Put", action: "put", keys: ["path_@_db", "query_@_q", "query_@_n", "query_@_partitioned"] }, + { variant: "Get", action: "get", keys: ["path_@_db"] }, + { variant: "Delete", action: "delete", keys: ["path_@_db"] }, + { variant: "DocPut", action: "docPut", keys: ["path_@_db", "path_@_docid", "header_@_If-Match", "query_@_rev", "query_@_batch", "query_@_new_edits", "body_@_body"] }, + { + variant: "DocGet", + action: "docGet", + keys: [ + "path_@_db", + "path_@_docid", + "header_@_If-None-Match", + "query_@_attachments", + "query_@_att_encoding_info", + "query_@_atts_since", + "query_@_conflicts", + "query_@_deleted_conflicts", + "query_@_latest", + "query_@_local_seq", + "query_@_meta", + "query_@_open_revs", + "query_@_rev", + "query_@_revs", + "query_@_revs_info", + ], + }, + { variant: "DocDelete", action: "docDelete", keys: ["path_@_db", "path_@_docid", "header_@_If-Match", "query_@_rev", "query_@_batch"] }, + { + variant: "DocGetAll", + action: "docGetAll", + keys: [ + "path_@_db", + ...["conflicts", "descending", "endkey", "end_key", "endkey_docid", "end_key_doc_id", "group", "group_level", "include_docs", "attachments", "att_encoding_info"].map((name) => `query_@_${name}`), + ...["inclusive_end", "revs_info", "key", "keys", "limit", "reduce", "skip", "sorted", "stable", "stale", "startkey", "start_key", "startkey_docid", "start_key_doc_id", "update", "update_seq"].map( + (name) => `query_@_${name}`, + ), + ], + }, + ]; + for (const { variant, action, keys } of expectations) { + const query = recordedPluginQuery("couchdb", variant); + expect(query.compType, `${variant || "default"}: the query type`).toBe("couchdb"); + expect(query.comp.actionName, `${variant || "default"}: the recorded operation`).toBe(action); + expect(Object.keys(query), `${variant || "default"}: only what the builder keeps`).toEqual(["compType", "comp"]); + expect(Object.keys(query.comp.action), `${variant || "default"}: the form's fields, in the operation's order`).toEqual(keys); + expect(Object.values(query.comp.action), `${variant || "default"}: every field is the editor's empty default`).toEqual(keys.map(() => "")); + expect(query.comp.headers, `${variant || "default"}: the editor's empty header row`).toEqual([{ key: "", value: "" }]); + const text = readFileSync(join(RECORDED_PLUGINS_DIR, "couchdb", `couchdb${variant}Query.json`), "utf8"); + expect(text, `${variant || "default"}: a 24-hex id`).not.toMatch(/\b[0-9a-f]{24}\b/); + expect(text, `${variant || "default"}: a sidecar address`).not.toContain(COUCHDB_ALIAS); + expect(text, `${variant || "default"}: an epoch of 10 digits or more`).not.toMatch(/\b\d{10,}\b/); + } + }); + + test("couchdbDirect sends the method, path, JSON body, extra headers and Basic credentials, none when not given, and parses a JSON or a text body; couchdbAdmin adds the admin", async () => { + const received: { method?: string; url?: string; authorization?: string; contentType?: string; ifMatch?: string; body: string }[] = []; + const server: Server = createServer((request: IncomingMessage, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + received.push({ + method: request.method, + url: request.url, + authorization: request.headers.authorization, + contentType: request.headers["content-type"], + ifMatch: request.headers["if-match"] as string | undefined, + body: Buffer.concat(chunks).toString("utf8"), + }); + if (request.url === "/text") { + response.writeHead(401, "Unauthorized").end("plain text, not JSON"); + } else { + response.writeHead(201, { "Content-Type": "application/json" }).end(JSON.stringify({ ok: true })); + } + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const serverURL = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + const basic = (user: string, password: string): string => `Basic ${Buffer.from(`${user}:${password}`).toString("base64")}`; + try { + const json = await couchdbDirect({ serverURL }, "PUT", "/db/doc?rev=1-a", { json: { a: 1 }, credentials: { username: "u", password: "p" }, headers: { "If-Match": "1-a" } }); + const text = await couchdbDirect({ serverURL }, "GET", "/text"); + const asAdmin = await couchdbAdmin({ serverURL, username: "admin", password: "secret" }, "DELETE", "/db", { headers: { "If-Match": "2-b" } }); + + expect(json, "a JSON body is parsed").toEqual({ status: 201, statusText: "Created", body: { ok: true } }); + expect(text, "a body that is not JSON stays text").toEqual({ status: 401, statusText: "Unauthorized", body: "plain text, not JSON" }); + expect(asAdmin.status, "the admin call is answered").toBe(201); + expect(received, "method, path, headers and body of the three calls").toEqual([ + { method: "PUT", url: "/db/doc?rev=1-a", authorization: basic("u", "p"), contentType: "application/json", ifMatch: "1-a", body: JSON.stringify({ a: 1 }) }, + { method: "GET", url: "/text", authorization: undefined, contentType: undefined, ifMatch: undefined, body: "" }, + { method: "DELETE", url: "/db", authorization: basic("admin", "secret"), contentType: undefined, ifMatch: "2-b", body: "" }, + ]); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }); }); diff --git a/e2e/tests/foundation/run-selection.spec.ts b/e2e/tests/foundation/run-selection.spec.ts index 44cf749f56..35c709dc1c 100644 --- a/e2e/tests/foundation/run-selection.spec.ts +++ b/e2e/tests/foundation/run-selection.spec.ts @@ -566,8 +566,8 @@ test.describe("run selection: the node-service sidecar tests are opt-in", () => }); }); -/** The names of the helpers whose use makes a spec need a sidecar (Firebird, libSQL), and the tag every test of such a spec must wear. */ -const SIDECAR_HELPERS = ["firebirdConnection", "libsqlConnection"] as const; +/** The names of the helpers whose use makes a spec need a sidecar (Firebird, libSQL, CouchDB), and the tag every test of such a spec must wear. */ +const SIDECAR_HELPERS = ["firebirdConnection", "libsqlConnection", "couchdbConnection"] as const; const SIDECAR_HELPER = SIDECAR_HELPERS[0]; const SIDECAR_TAG_KEY = "NODE_SERVICE_SIDECAR"; @@ -589,7 +589,7 @@ function detailsTagWithSidecar(details: ts.Expression): boolean { } /** - * The tests of a spec source that does not wear `TAGS.NODE_SERVICE_SIDECAR`, when the source uses a sidecar helper (`firebirdConnection` or `libsqlConnection`; a spec that needs the + * The tests of a spec source that does not wear `TAGS.NODE_SERVICE_SIDECAR`, when the source uses a sidecar helper (`firebirdConnection`, `libsqlConnection` or `couchdbConnection`; a spec that needs the * sidecar: untagged, its tests would run in the default run, where the sidecar is not started). A source that does not use the helper * reports nothing. A tag on an enclosing `test.describe*(title, details, body)` counts for every test inside. Each result is `line `. * Limits: the same as `untaggedSuperAdminTests` (a `test` passed through a parameter is not recognised, a tag through a variable is not followed). @@ -624,7 +624,7 @@ function untaggedSidecarTests(source: string, fileName = "synthetic.spec.ts"): s } test.describe("run selection: every test that needs a sidecar carries the opt-in tag", () => { - test("every spec that uses a sidecar helper tags all its tests with TAGS.NODE_SERVICE_SIDECAR, and the Firebird and libSQL specs do use one", () => { + test("every spec that uses a sidecar helper tags all its tests with TAGS.NODE_SERVICE_SIDECAR, and the Firebird, libSQL and CouchDB specs do use one", () => { const untagged: string[] = []; const users: string[] = []; for (const file of specFilesUnder(join(__dirname, ".."))) { @@ -634,7 +634,11 @@ test.describe("run selection: every test that needs a sidecar carries the opt-in untagged.push(...untaggedSidecarTests(source, file).map((entry) => `${file}: ${entry}`)); } - expect(users.map((file) => file.split("tests/")[1]), "the specs that use the helper (a positive control that the guard looks at the Firebird and the libSQL spec)").toEqual(["datasource/plugin-firebird.spec.ts", "datasource/plugin-turso-libsql.spec.ts"]); + expect(users.map((file) => file.split("tests/")[1]), "the specs that use the helper (a positive control that the guard looks at the CouchDB, the Firebird and the libSQL spec)").toEqual([ + "datasource/plugin-couchdb.spec.ts", + "datasource/plugin-firebird.spec.ts", + "datasource/plugin-turso-libsql.spec.ts", + ]); expect(untagged, "tests of a sidecar spec without TAGS.NODE_SERVICE_SIDECAR (they would run, and fail, in the default run)").toEqual([]); }); @@ -649,5 +653,7 @@ test.describe("run selection: every test that needs a sidecar carries the opt-in expect(untaggedSidecarTests(`test("a", async () => {});`), "a spec that does not use the helper is not asked").toEqual([]); expect(untaggedSidecarTests(`const c = libsqlConnection();\ntest("a", async () => {});`), "the libSQL helper is asked too").toEqual(["line 2"]); expect(untaggedSidecarTests(`const c = libsqlConnection();\ntest.describe("g", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { test("a", async () => {}); });`), "and accepts its describe tag").toEqual([]); + expect(untaggedSidecarTests(`const c = couchdbConnection();\ntest("a", async () => {});`), "the CouchDB helper is asked too").toEqual(["line 2"]); + expect(untaggedSidecarTests(`const c = couchdbConnection();\ntest.describe("g", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { test("a", async () => {}); });`), "and accepts its describe tag").toEqual([]); }); }); From 905745f724739ce23d548fd76b665c0169446bc4 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Wed, 25 Nov 2026 06:45:15 +0100 Subject: [PATCH 17/20] test: add an opt-in DynamoDB Local sidecar and DynamoDB scenarios against it With E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 the run script now also starts a pinned DynamoDB Local server next to the Firebird, libSQL and CouchDB ones, waits until it answers a real ListTables request, makes it reachable from the app container and the test runner, and removes it on exit even when the run fails. Without the flag nothing extra is started and the tests are neither listed nor run. The readiness loops of all four sidecars now measure real elapsed time instead of counting their sleeps, so a stalled probe can no longer push a run past the startup timeout by more than one poll interval and one probe limit. The CouchDB probe shares one time budget across its requests, and structural tests keep each loop and probe bounded. Adds scenarios that run the DynamoDB plugin against the real server: table creation and listing with paging, attribute type mapping both ways, queries and scans with typed continuation keys, update and delete effects checked by direct reads with conditional controls, error messages, access keys, the published view after a click and reachability from the runner. Typed keys and attributes in some answers, string and number arrays always written as sets, numbers and binary values that do not round-trip, and a plain-form start key that fails with an SDK error are characterised and annotated as defect candidates. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 14 +- e2e/README.md | 43 +- .../dynamodb/dynamodbCreateTableQuery.json | 15 + .../dynamodb/dynamodbDeleteItemQuery.json | 16 + .../plugins/dynamodb/dynamodbScanQuery.json | 16 + .../dynamodb/dynamodbUpdateItemQuery.json | 16 + e2e/scripts/run-in-docker.sh | 96 ++- e2e/src/constants.ts | 19 +- e2e/src/datasource/dynamodb.ts | 79 ++ e2e/src/run-selection.ts | 2 +- .../datasource/plugin-dynamodb-local.spec.ts | 737 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 176 ++++- e2e/tests/foundation/run-selection.spec.ts | 13 +- 13 files changed, 1198 insertions(+), 44 deletions(-) create mode 100644 e2e/fixtures/dsl/plugins/dynamodb/dynamodbCreateTableQuery.json create mode 100644 e2e/fixtures/dsl/plugins/dynamodb/dynamodbDeleteItemQuery.json create mode 100644 e2e/fixtures/dsl/plugins/dynamodb/dynamodbScanQuery.json create mode 100644 e2e/fixtures/dsl/plugins/dynamodb/dynamodbUpdateItemQuery.json create mode 100644 e2e/src/datasource/dynamodb.ts create mode 100644 e2e/tests/datasource/plugin-dynamodb-local.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index 00b8107517..4e4be0766b 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,8 +129,8 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `tests/datasource/plugin-supabase-storage.spec.ts`, D11; `tests/datasource/plugin-firebird.spec.ts`, D12, `tests/datasource/plugin-turso-libsql.spec.ts`, D13, and `tests/datasource/plugin-couchdb.spec.ts`, D14, which also wear the opt-in tag of the next bullet; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. -- `@node-service-sidecar`: a node-service data source test that needs a real server of its own to be pointed at: either the echo cannot serve the plugin's protocol (Firebird, a wire protocol, `tests/datasource/plugin-firebird.spec.ts`, D12) or the echo's canned answers say nothing about the real server's behaviour (a libSQL server for the Turso plugin, `tests/datasource/plugin-turso-libsql.spec.ts`, D13, and a CouchDB server for the CouchDB plugin, `tests/datasource/plugin-couchdb.spec.ts`, D14); `TAGS.NODE_SERVICE_SIDECAR`. Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of the default run (neither listed nor run, and `run-in-docker.sh` starts no such container), in only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` (default stack only). A spec that calls `firebirdConnection()`, `libsqlConnection()` or `couchdbConnection()` must tag every test with it (a guard in `foundation/run-selection.spec.ts` parses the spec: write `{ tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }` on the describe or the test, not through a variable). Never put the tag text in a test title: the default `grepInvert` matches titles too and would drop the test. The helper that reads a sidecar's host variable throws when it is unset, so a test selected without its sidecar fails loudly. All three sidecars start together under the one flag; later sidecars add their container under it too. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `tests/datasource/plugin-supabase-storage.spec.ts`, D11; `tests/datasource/plugin-firebird.spec.ts`, D12, `tests/datasource/plugin-turso-libsql.spec.ts`, D13, `tests/datasource/plugin-couchdb.spec.ts`, D14, and `tests/datasource/plugin-dynamodb-local.spec.ts`, D15, which also wear the opt-in tag of the next bullet; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service-sidecar`: a node-service data source test that needs a real server of its own to be pointed at: either the echo cannot serve the plugin's protocol (Firebird, a wire protocol, `tests/datasource/plugin-firebird.spec.ts`, D12) or the echo's canned answers say nothing about the real server's behaviour (a libSQL server for the Turso plugin, `tests/datasource/plugin-turso-libsql.spec.ts`, D13, a CouchDB server for the CouchDB plugin, `tests/datasource/plugin-couchdb.spec.ts`, D14, and a DynamoDB Local server for the DynamoDB plugin, `tests/datasource/plugin-dynamodb-local.spec.ts`, D15); `TAGS.NODE_SERVICE_SIDECAR`. Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of the default run (neither listed nor run, and `run-in-docker.sh` starts no such container), in only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` (default stack only). A spec that calls `firebirdConnection()`, `libsqlConnection()`, `couchdbConnection()` or `dynamodbConnection()` must tag every test with it (a guard in `foundation/run-selection.spec.ts` parses the spec: write `{ tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }` on the describe or the test, not through a variable). Never put the tag text in a test title: the default `grepInvert` matches titles too and would drop the test. The helper that reads a sidecar's host variable throws when it is unset, so a test selected without its sidecar fails loudly. All four sidecars start together under the one flag; later sidecars add their container under it too. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). @@ -171,9 +171,9 @@ MUST NOT: `test-results`, `playwright-report`), and do not run `playwright test` directly while a stack of this checkout runs. - Edit anything in `e2e/evidence/` (git-ignored, local). Do not cite it as if it were in git. - Reach a real external host, switch the guard off, or add a route that allows another origin. Only `@npm` tests need - the app container to reach the npm registry. The places the backend may be pointed at are the run's own echo sidecar (`echo` fixture, `src/security/echo.ts`) and, only in a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, the opt-in node-service sidecars: the Firebird sidecar (`firebirdConnection()`, `src/datasource/firebird.ts`), the libSQL server sidecar (`libsqlConnection()`, `src/datasource/libsql.ts`) and the CouchDB sidecar (`couchdbConnection()`, `src/datasource/couchdb.ts`). Later opt-in sidecars add their names to this sentence. Never give a data source or a registry entry any other URL, and never rely on a placeholder host failing to resolve: every connection of a sidecar test goes to the sidecar. + the app container to reach the npm registry. The places the backend may be pointed at are the run's own echo sidecar (`echo` fixture, `src/security/echo.ts`) and, only in a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, the opt-in node-service sidecars: the Firebird sidecar (`firebirdConnection()`, `src/datasource/firebird.ts`), the libSQL server sidecar (`libsqlConnection()`, `src/datasource/libsql.ts`), the CouchDB sidecar (`couchdbConnection()`, `src/datasource/couchdb.ts`) and the DynamoDB Local sidecar (`dynamodbConnection()`, `src/datasource/dynamodb.ts`). Later opt-in sidecars add their names to this sentence. Never give a data source or a registry entry any other URL, and never rely on a placeholder host failing to resolve: every connection of a sidecar test goes to the sidecar. - Import `test` from `@playwright/test` in a spec that opens a page or uses the stack: the network guard exists only in the `test` of `src/fixtures.ts` (accepted exception for stack-free unit specs below). -- Commit secrets. The PostgreSQL password in `src/constants.ts` is the throw-away one of the sidecar. The Firebird password in `src/constants.ts` is likewise the throw-away one of its own sidecar, and so are the libSQL tokens (`LIBSQL`): signed with a key pair generated once, whose private half was thrown away, and the CouchDB admin of its sidecar (`COUCHDB`). +- Commit secrets. The PostgreSQL password in `src/constants.ts` is the throw-away one of the sidecar. The Firebird password in `src/constants.ts` is likewise the throw-away one of its own sidecar, and so are the libSQL tokens (`LIBSQL`): signed with a key pair generated once, whose private half was thrown away, the CouchDB admin of its sidecar (`COUCHDB`), and the access key of the DynamoDB Local sidecar (`DYNAMODB`: the server checks no credential). - Let the super admin's password (`E2E_SUPERUSER_PASSWORD`, new every run, set by `run-in-docker.sh`) reach a command line, log, trace, report, test title, annotation or error message; keep `set -x` off in the script. Never give the password to a matcher as the expected or received value (`expect(text).not.toContain(password)` prints it when it fails): assert `text.includes(password)` is `false`. The sign-in lives in an automatic worker fixture (`superAdminState`) because a request context created inside a test lands in its trace; do not sign the super admin in from a test or a helper, and create no request context in a helper. Every test that uses the `superAdmin` fixture carries `TAGS.SUPERADMIN` (a guard in `foundation/run-selection.spec.ts` checks it by parsing the spec with the TypeScript compiler: write the tag as `TAGS.SUPERADMIN` in the test's or its describe's details, a mention in a comment or title does not count). The super admin is ONE account shared by all workers: never switch its workspace or change its password. It hangs once the stack holds more than about 420 workspaces (README, security section): the SEC-R16 tests therefore carry `@superadmin` and run only on request (`E2E_INCLUDE_SUPERADMIN=1`); keep such runs short. - Duplicate a helper that exists: @@ -196,6 +196,7 @@ MUST NOT: | Firebird sidecar connection (opt-in sidecar: throws `FirebirdSidecarMissingError` when `E2E_FIREBIRD_HOST` is unset), the rows of `fixtures/firebird/init.sql` | `firebirdConnection`, `FirebirdSidecarMissingError`, `FIREBIRD_ITEMS` | `src/datasource/firebird.ts` | | libSQL sidecar connection (opt-in sidecar: throws `LibsqlSidecarMissingError` when `E2E_LIBSQL_HOST` is unset) and a direct pipeline call to it from the test process (the control that shows the server's own answer) | `libsqlConnection`, `libsqlDirect`, `LibsqlSidecarMissingError`, `LIBSQL_PIPELINE_PATH` | `src/datasource/libsql.ts` | | CouchDB sidecar connection (opt-in sidecar: throws `CouchdbSidecarMissingError` when `E2E_COUCHDB_HOST` is unset) and a direct HTTP call to it from the test process, plain or as the sidecar's admin (the control that shows the server's own status and body, and the way a test makes and removes its own database) | `couchdbConnection`, `couchdbDirect`, `couchdbAdmin`, `CouchdbSidecarMissingError` | `src/datasource/couchdb.ts` | +| DynamoDB Local sidecar connection (opt-in sidecar: throws `DynamodbSidecarMissingError` when `E2E_DYNAMODB_HOST` is unset) and a direct call of the DynamoDB JSON protocol to it from the test process in the API's typed form (the control that shows what the server holds, and the way a test makes and removes its own tables) | `dynamodbConnection`, `dynamodbDirect`, `DynamodbSidecarMissingError`, `DYNAMODB_CONTENT_TYPE`, `DYNAMODB_TARGET_PREFIX` | `src/datasource/dynamodb.ts` | | pages | `EditorPage`, `AppViewPage`, `PropertyPanel`, `QueryPanel`, `TableView`, `ExtensionsPanel`, `AppListPage`, `AuthPage`, `LoginPage`, `UserMenu`, `SettingPage`, `DatasourcePage` | `src/pages/` | Accepted exception to the `test` import rule: stack-free unit specs that open no browser page (no `page`, no app) may @@ -273,7 +274,8 @@ E2E_INCLUDE_INSERT_ALL=1 e2e/scripts/run-in-docker.sh --grep @insert-all --worke E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin # SEC-R16a, R16b (R16c, R16d also need E2E_INCLUDE_QUARANTINE=1) E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-firebird.spec.ts # D12 gate: starts the Firebird sidecar (image pull, a few seconds) E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-turso-libsql.spec.ts # D13 gate: starts both sidecars (Firebird and libSQL) -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-couchdb.spec.ts # D14 gate: starts all three sidecars (Firebird, libSQL and CouchDB) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-couchdb.spec.ts # D14 gate: starts all four sidecars (Firebird, libSQL, CouchDB and DynamoDB Local) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-dynamodb-local.spec.ts # D15 gate: starts all four sidecars E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # only the tests that need a sidecar e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/modules/module-editor-host.spec.ts # M3 gate E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/security/enterprise.spec.ts # ENTERPRISE stack gate (its own stack; never at the same time as another run) @@ -288,7 +290,7 @@ Directory `e2e/` (no stack; `--reporter=list` is required so no report files are LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_INCLUDE_QUARANTINE=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_INCLUDE_SUPERADMIN=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # adds the D12, D13 and D14 tests +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # adds the D12, D13, D14 and D15 tests E2E_INCLUDE_INSERT_ALL=1 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_SUPERADMIN=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_STACK_PROFILE=enterprise LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # the SEC-E tests only ``` diff --git a/e2e/README.md b/e2e/README.md index 93b802a7ca..123c39e2fc 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; Firebird (node-firebird over TCP, D12) runs against a Firebird sidecar of its own that only a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` starts, and a default run neither starts it nor lists or runs those tests, and Turso also runs against a real libSQL server (sqld, D13) the same way, where the `libsql://` to `https://` rewrite of the URL is not covered because the sidecar speaks plain HTTP, and CouchDB also runs against a real Apache CouchDB server (D14) the same way, where the JWT credential and cookie sessions are not covered because the image's default configuration has no JWT authentication handler and the plugin sends the `Authorization` header only; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; Firebird (node-firebird over TCP, D12) runs against a Firebird sidecar of its own that only a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` starts, and a default run neither starts it nor lists or runs those tests, and Turso also runs against a real libSQL server (sqld, D13) the same way, where the `libsql://` to `https://` rewrite of the URL is not covered because the sidecar speaks plain HTTP, and CouchDB also runs against a real Apache CouchDB server (D14) the same way, where the JWT credential and cookie sessions are not covered because the image's default configuration has no JWT authentication handler and the plugin sends the `Authorization` header only, and DynamoDB also runs against a real DynamoDB Local server (D15) the same way, where indexes, transactions, batch operations, streams and the request signature (the server verifies none) are not covered; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -44,18 +44,25 @@ lifecycle (insert, save, publish, load) is covered by S1 when `@insert-all` runs - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar` (or name the spec file). - **Cost, measured here:** image 156 MB (`docker image inspect`), a cold pull of the pinned digest took 3 s (a fast link and a warm registry mirror: expect more elsewhere), the container accepted the readiness SELECT within about 3 s of starting (the script logged `Firebird sidecar ready after 0s`: the wait ran after the PostgreSQL wait of 2 s), and a gate of 110 tests ran in about 23 s. Runs without the flag pay nothing. - **libSQL sidecar (opt-in):** the Turso plugin of node-service posts Hrana pipelines to `/v2/pipeline` over HTTP, so the echo can stand in for it (D5, canned answers); a real server adds what canned answers cannot: the real column types and cells, real SQL errors, real authentication (D13, `tests/datasource/plugin-turso-libsql.spec.ts`). It is OPT-IN under the same flag and tag as the Firebird sidecar and the sidecars start together: - - **A default run** starts no libSQL container, pulls no libSQL image, passes no `E2E_LIBSQL_HOST` to the runner, and neither lists nor runs the D13 tests. **A run with the flag** starts the sidecar right after the Firebird one, waits (at most `STARTUP_TIMEOUT`, 300 s, polled every 2 s) until one real `select 1` pipeline with the read-write token, posted from the echo container to `http://e2e-libsql:8080/v2/pipeline` over the run network, answers 200 with the integer 1, gives the app container and the runner `--add-host e2e-libsql:` (added to the Firebird entry, not replacing it), passes `E2E_LIBSQL_HOST=e2e-libsql` to the runner, and removes the container in the cleanup trap however the run ends. The data source URL is `http://e2e-libsql:8080` (`libsqlConnection()` throws a named error when the host variable is unset). + - **A default run** starts no libSQL container, pulls no libSQL image, passes no `E2E_LIBSQL_HOST` to the runner, and neither lists nor runs the D13 tests. **A run with the flag** starts the sidecar right after the Firebird one, waits (`STARTUP_TIMEOUT`, 300 s of real elapsed time, polled every 2 s; see "Readiness bound" under the DynamoDB Local sidecar) until one real `select 1` pipeline with the read-write token, posted from the echo container to `http://e2e-libsql:8080/v2/pipeline` over the run network, answers 200 with the integer 1, gives the app container and the runner `--add-host e2e-libsql:` (added to the Firebird entry, not replacing it), passes `E2E_LIBSQL_HOST=e2e-libsql` to the runner, and removes the container in the cleanup trap however the run ends. The data source URL is `http://e2e-libsql:8080` (`libsqlConnection()` throws a named error when the host variable is unset). - **Image:** `ghcr.io/tursodatabase/libsql-server:v0.24.33`, sqld 0.24.33, pinned by tag and digest (`sha256:f8ca0134cdded747793888e48591aece07647d9d598d3ac229aabfa93159ca88`; `LIBSQL_IMAGE` overrides it). It is the libSQL project's own server image. Its `latest` tag, pulled at the same time, was another build that also reports sqld 0.24.33 (digest `sha256:6dd3eb276d9d3604e4a48ac4a999a2e267814732d57d7e94c04ba71482333a67`), so the pin uses the version tag. The image declares `/var/lib/sqld` a volume, so the script mounts a tmpfs there: the database is in memory and no anonymous volume outlives the run. - **Auth setup:** sqld started with `SQLD_AUTH_JWT_KEY` accepts only a JWT signed with the matching Ed25519 key (a plain `--http-auth` would want Basic credentials, but the plugin sends `Authorization: Bearer `). A key pair was generated once and its private half thrown away; `LIBSQL` in `src/constants.ts` and `LIBSQL_JWT_PUBLIC_KEY` / `LIBSQL_TOKEN` in the script hold the public key and tokens signed with it, without an expiry: a read-write token (claim `a: "rw"`), a read-only one (`a: "ro"`, the server answers 403 to a write) and a "foreign" one signed by a second throw-away pair (the server answers 401). A foundation test verifies the three signatures against the public key. Without a token, with a malformed one or with the foreign one the server answers 401. - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-turso-libsql.spec.ts` (every sidecar starts; `--grep @node-service-sidecar` runs D12 and D14 as well). - - **Cost, measured here:** the image is 153 MB (`docker image inspect`, uncompressed) and a cold pull of the pinned digest took 9 s (a fast link: expect more elsewhere); the container started with the Firebird one and answered the readiness call within about a second (the script logged `libSQL sidecar ready after 0s`, the wait running after the PostgreSQL, echo and Firebird waits), so the two sidecars together add no waiting of their own beyond the slower one; a gate of 110 tests (`--repeat-each=10 --workers=4`) ran in about 27 s. Runs without the flag pay nothing. A readiness failure is bounded: with a copy of the script whose key did not match the readiness token and `STARTUP_TIMEOUT=6`, the run stopped after about 11 s with `the libSQL sidecar did not become ready within 6s`, the server's log tail, and the containers and network removed. + - **Cost, measured here:** the image is 153 MB (`docker image inspect`, uncompressed) and a cold pull of the pinned digest took 9 s (a fast link: expect more elsewhere); the container started with the Firebird one and answered the readiness call within about a second (the script logged `libSQL sidecar ready after 0s`, the wait running after the PostgreSQL, echo and Firebird waits), so the two sidecars together add no waiting of their own beyond the slower one; a gate of 110 tests (`--repeat-each=10 --workers=4`) ran in about 27 s. Runs without the flag pay nothing. The readiness bound is described under the DynamoDB Local sidecar. - **CouchDB sidecar (opt-in):** the CouchDB plugin of node-service is an OpenAPI wrapper that sends HTTP, so the echo can stand in for it (D8a to D8i, canned answers); a real server adds what canned answers cannot: the server's own status codes and error bodies, stored documents and revisions, key ranges, real authentication and its lockout (D14, `tests/datasource/plugin-couchdb.spec.ts`). It is OPT-IN under the same flag and tag as the other sidecars and all three start together: - - **A default run** starts no CouchDB container, pulls no CouchDB image, passes no `E2E_COUCHDB_HOST` to the runner, and neither lists nor runs the D14 tests (`--list --grep @node-service-sidecar` shows 0). Measured: the containers a default run created (`docker events`) were the app, the echo, PostgreSQL and the runner. **A run with the flag** starts the sidecar right after the libSQL one, waits (at most `STARTUP_TIMEOUT`, 300 s, polled every 2 s; every readiness request has a 2 s connect and a 5 s total limit, so a stalled request ends the attempt and the deadline is checked again) until the server answers `_up`, creates the system databases (a `PUT` counts only on 201 or 412) and lists them, gives the app container and the runner `--add-host e2e-couchdb:` (appended to the entries of the other sidecars), passes `E2E_COUCHDB_HOST=e2e-couchdb` to the runner, and removes the container in the cleanup trap however the run ends. The data source URL is `http://e2e-couchdb:5984` (`couchdbConnection()` throws a named error when the host variable is unset). Reached from both sides: the plugin's requests come from the app container, and D14i and the direct calls come from the runner. + - **A default run** starts no CouchDB container, pulls no CouchDB image, passes no `E2E_COUCHDB_HOST` to the runner, and neither lists nor runs the D14 tests (`--list --grep @node-service-sidecar` shows 0). Measured: the containers a default run created (`docker events`) were the app, the echo, PostgreSQL and the runner. **A run with the flag** starts the sidecar right after the libSQL one, waits (`STARTUP_TIMEOUT`, 300 s of real elapsed time, polled every 2 s; the whole probe of five requests has one 5 s budget and each request a 2 s connect limit; see "Readiness bound" under the DynamoDB Local sidecar) until the server answers `_up`, creates the system databases (a `PUT` counts only on 201 or 412) and lists them, gives the app container and the runner `--add-host e2e-couchdb:` (appended to the entries of the other sidecars), passes `E2E_COUCHDB_HOST=e2e-couchdb` to the runner, and removes the container in the cleanup trap however the run ends. The data source URL is `http://e2e-couchdb:5984` (`couchdbConnection()` throws a named error when the host variable is unset). Reached from both sides: the plugin's requests come from the app container, and D14i and the direct calls come from the runner. - **Image:** `couchdb:3.5.1`, Apache CouchDB 3.5.1 (the official image; the plugin bundles the 3.1.1 API document), pinned by tag and digest (`sha256:ccea1e8035bf7afd68336e24056a1ca9c1c46d7abe42da686322c0ac7218e5c2`; `COUCHDB_IMAGE` overrides it). The image declares `/opt/couchdb/data` a volume, so the script mounts a tmpfs there: the data is in memory and this sidecar leaves no anonymous volume (measured: `docker inspect` of the running container shows `Mounts` empty and the tmpfs; a default run left one dangling volume, PostgreSQL's, and a run with the flag two, PostgreSQL's and Firebird's, so the CouchDB sidecar adds none). - **Admin setup:** the image makes one server admin from `COUCHDB_USER` and `COUCHDB_PASSWORD` (`COUCHDB` in `src/constants.ts` and the script: `e2eadmin` and a throw-away password, never a real secret). A fresh single node has no system databases (`_all_dbs` answers `[]`), so the readiness step creates `_users`, `_replicator` and `_global_changes` with `PUT` through the real HTTP API (201, or 412 when they exist) and is ready when `_all_dbs` lists all three; it runs inside the container (the image has curl), is idempotent, and is repeated until it succeeds. The tests make their own databases (`e2e_couch_`) and remove them. - **Lockout (measured, CouchDB 3.5.1):** after five failed logins of a real account the server answers 403 `Account is temporarily locked due to multiple authentication failures` to that account, from that client address, even with the right password (the message says "temporarily"; how long it lasts was not measured). A test that sends a wrong password therefore does it as a second admin it makes for the purpose (D14e, D14j) and never as the sidecar's admin, which every other test uses; failures for a name that does not exist are not counted. A freshly made config admin cannot log in until the server has hashed its password (a moment after the `PUT`), so the helper waits for the hash before the first login. - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-couchdb.spec.ts` (all three sidecars start; `--grep @node-service-sidecar` runs D12 and D13 as well). - - **Cost, measured here:** the image is 276 MB (`docker image inspect`, uncompressed); CouchDB answered the readiness probe on its first try, about a second after it started (the script logged `CouchDB sidecar ready after 0s`: the wait runs after the PostgreSQL, echo, Firebird and libSQL waits, and the server's log shows it started in about half a second), so all three sidecars together added no waiting of their own beyond the slowest. A cold pull of the pinned digest took 6.4 s (a fast link: expect more elsewhere). A readiness failure is bounded: with a copy of the script whose readiness probe used a wrong password and `STARTUP_TIMEOUT=6`, the run stopped after 12 s with `the CouchDB sidecar did not become ready within 6s`, the server's log tail, and the containers and network removed. A test that fails still ends with every container and the network removed (measured with a deliberately failing test under the flag: seven containers created, none left, no network left). + - **Cost, measured here:** the image is 276 MB (`docker image inspect`, uncompressed); CouchDB answered the readiness probe on its first try, about a second after it started (the script logged `CouchDB sidecar ready after 0s`: the wait runs after the PostgreSQL, echo, Firebird and libSQL waits, and the server's log shows it started in about half a second), so all three sidecars together added no waiting of their own beyond the slowest. A cold pull of the pinned digest took 6.4 s (a fast link: expect more elsewhere). The readiness bound is described under the DynamoDB Local sidecar. A test that fails still ends with every container and the network removed (measured with a deliberately failing test under the flag: seven containers created, none left, no network left). +- **DynamoDB Local sidecar (opt-in):** the DynamoDB plugin of node-service uses the AWS SDK v3 with a configurable endpoint, so the echo can stand in for it (D10a to D10f, canned answers and the signed request); a real server adds what canned answers cannot: real tables and items, the typed attribute form on the wire, pagination keys, and the server's own errors (D15, `tests/datasource/plugin-dynamodb-local.spec.ts`). It is OPT-IN under the same flag and tag as the other sidecars and all four start together: + - **A default run** starts no DynamoDB Local container, pulls no DynamoDB Local image, passes no `E2E_DYNAMODB_HOST` to the runner, and neither lists nor runs the D15 tests (`--list --grep @node-service-sidecar` shows 0). **A run with the flag** starts the sidecar right after the CouchDB one, waits (`STARTUP_TIMEOUT`, 300 s of real elapsed time, polled every 2 s; every readiness request is aborted after 5 s; see "Readiness bound" below) until one real `ListTables` call, posted from the echo container to `http://e2e-dynamodb:8000/` over the run network, answers exactly 200 with a JSON body whose `TableNames` member is an array, gives the app container and the runner `--add-host e2e-dynamodb:` (appended to the entries of the other sidecars), passes `E2E_DYNAMODB_HOST=e2e-dynamodb` to the runner, and removes the container in the cleanup trap however the run ends. The data source's endpoint is `http://e2e-dynamodb:8000` (`dynamodbConnection()` throws a named error when the host variable is unset). Reached from both sides: the plugin's requests come from the app container, and the direct calls and D15l come from the runner. + - **Image:** `amazon/dynamodb-local:3.3.2` (AWS's own image, DynamoDB Local 3.3.2, Java 17), pinned by tag and digest (`sha256:6ada631ec7aa5fc83446855eb17233e3dad184fec47477e8140c6c569cfe0c86`, the digest of `3.3.2` and `latest` on Docker Hub when it was pulled; `DYNAMODB_IMAGE` overrides it). It runs `-jar DynamoDBLocal.jar -inMemory -sharedDb -port 8000`: every table is in memory (nothing is written to a file) and one database serves every access key, so table names are global to the sidecar and each test names its tables with a per-test marker (`e2e_ddb_`) and removes them in a `finally`. The image declares no volume (`docker image inspect` shows no `Volumes`), so no `--tmpfs` is needed: measured, the running container's `Mounts` is empty and a flagged run left two dangling volumes, PostgreSQL's and Firebird's, the same two the CouchDB sidecar's run left (before and after counts in the Docker evidence of the counts paragraph below). + - **Credentials:** the server checks none: it wants an `Authorization` header with a `Credential=` scope and accepts any access key and any signature (measured: a signature of zeros is accepted; a request without the header is refused with `MissingAuthenticationToken`). `DYNAMODB` in `src/constants.ts` holds a throw-away key, secret and region, never a real secret; the direct calls of the tests send the same header form with a signature of zeros. + - **Readiness bound (the Firebird, libSQL, CouchDB and DynamoDB Local waits):** each loop takes the shell's `SECONDS` at its start and, after every failed probe, compares the elapsed seconds with `STARTUP_TIMEOUT` before it sleeps and probes again, so the time a probe takes counts (an earlier version added up its sleeps only: with probes that take 5 s each it ran several times past the limit). The check comes before the sleep and the next probe, and one probe is bounded as a WHOLE: the Firebird probe is one `isql` run under `timeout -s KILL 5`, the libSQL and DynamoDB probes are one fetch aborted after 5 s, and the CouchDB probe, which makes five requests (`_up`, three `PUT`s, `_all_dbs`), shares one 5 s budget (`couchdb_curl` gives each request the time left of the probe's deadline as its `--max-time`, and a request that finds nothing left is not made). So for each of the four the worst case is `STARTUP_TIMEOUT` + `POLL_INTERVAL` (2 s) + `PROBE_REQUEST_TIMEOUT` (5 s), that is 7 s past the limit, plus up to one second of clock granularity (`SECONDS` counts whole seconds) and the start-up time of the `docker exec` calls, which has no limit of its own; not an unbounded multiple. A foundation test fails for any of the four loops that goes back to the sleep-only counter. The PostgreSQL, echo and app waits were not changed: they still add up their sleeps only and their probes have no time limit. Measured by hand on one machine, no artifacts committed, with temporary copies of the script (`STARTUP_TIMEOUT=6`): the sidecar's probe was made unable to succeed (DynamoDB: another accepted status; libSQL: a token the server refuses; CouchDB: other accepted statuses; Firebird: a table that does not exist) so that it failed fast, and 4 s after the container appeared the server was frozen (`docker pause` for DynamoDB and libSQL, whose probe runs in the echo container; SIGSTOP of the server processes for CouchDB and Firebird, whose probe runs inside the container), so that the probes were accepted by the kernel and never answered and each ended at its 5 s limit. Each run ended with `the sidecar did not become ready within 6s` and no container or network left. Total duration of the script, start of the stack included (about 2 s): with the sleep-only counter 20 s for DynamoDB Local, 19 s for libSQL, 19 s for CouchDB and 19 s for Firebird; with the elapsed-time deadline 12 s for each of the four (the stack takes about 2 s, so the wait ended about 10 s after it began, inside the worst case of 6 + 2 + 5 = 13 s). CouchDB was measured again after its probe got the shared budget, three runs of the same method: 12 s, 13 s and 12 s. A frozen server stalls only the first request of its probe, so this method does not show the budget; the budget was shown with a stub `docker` that answers each of the five requests correctly but takes 3 s for it: the probe of the earlier form took 15 s and succeeded, the probe with the shared budget stopped after 5 s and failed, and a foundation test fails for the earlier form (the structural assertions of the probe's deadline). An earlier measurement of 10 s with a paused DynamoDB container did not exercise a stalled probe: the container was frozen before the server listened, so the connection was refused at once. + - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-dynamodb-local.spec.ts` (all four sidecars start; `--grep @node-service-sidecar` runs D12, D13 and D14 as well). + - **Cost, measured here:** the image is 512 MB (`docker image inspect`, uncompressed); the JVM server answered the readiness call on its first try, within a second or two of starting (the script logged `DynamoDB Local sidecar ready after 0s`: the wait runs after the PostgreSQL, echo, Firebird, libSQL and CouchDB waits), so the sidecars were all ready about three seconds after the first container of the run was created, while the app needs 10 to 12 s (measured: `Application ready after 10s` and `after 12s` in flagged runs; the readiness waits run after the app container is started). A cold pull of the pinned digest took 10 s (a fast link: expect more elsewhere). A test that fails still ends with every container and the network removed (measured with twelve deliberately inverted assertions under the flag: none left, no network left). These results were measured by hand on one machine; no artifacts are committed. A gate of 120 tests (`--repeat-each=10 --workers=4`) ran in about 31 s. Runs without the flag pay nothing. - **HTTP echo sidecar** (`scripts/echo-server.js`, started by `run-in-docker.sh` on the already pinned runner image, so no extra image or download; network alias `e2e-echo`, port 8080; the runner gets `E2E_ECHO_URL` and the sidecar's IP address on the run network as `E2E_ECHO_IP`): the target of the requests the SERVER makes inside the app container (node-service's npm registry proxy, the n8n plugin). It records `{ method, path, headers, body }` of every request in @@ -145,7 +152,7 @@ e2e/scripts/run-in-docker.sh -g "sign-up through the UI" # one test b e2e/scripts/run-in-docker.sh --grep @smoke # by tag: @smoke @core @slow @npm E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --grep @quarantine E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin # SEC-R16a, SEC-R16b (R16c, R16d also need E2E_INCLUDE_QUARANTINE=1) -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # D12, D13 and D14, the Firebird, libSQL and CouchDB sidecar tests (starts all three sidecars) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # D12 to D15, the Firebird, libSQL, CouchDB and DynamoDB Local sidecar tests (starts all four sidecars) E2E_INCLUDE_INSERT_ALL=1 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh # everything on the default stack (not the @enterprise tests) E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh tests/security/enterprise.spec.ts # the ENTERPRISE stack, SEC-E01 to E04, E06a, E06b, E07a, E07b E2E_STACK_PROFILE=signup-disabled e2e/scripts/run-in-docker.sh tests/auth/signup-disabled.spec.ts # the stack with e-mail sign-up switched off, LC-AU20 to AU24 @@ -200,11 +207,13 @@ data; its tests are untagged. | `PLAYWRIGHT_IMAGE` | run-in-docker.sh | runner image; version must equal `@playwright/test` in `package-lock.json` (1.64.0) | | `POSTGRES_IMAGE` | run-in-docker.sh | PostgreSQL sidecar image | | `FIREBIRD_IMAGE` | run-in-docker.sh | Firebird sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | -| `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | script and config | non-empty, default stack only (any other profile stops the script): start the Firebird, libSQL and CouchDB sidecars and include the `@node-service-sidecar` tests (D12, D13, D14) | +| `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | script and config | non-empty, default stack only (any other profile stops the script): start the Firebird, libSQL, CouchDB and DynamoDB Local sidecars and include the `@node-service-sidecar` tests (D12, D13, D14, D15) | | `LIBSQL_IMAGE` | run-in-docker.sh | libSQL server (sqld) sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | | `E2E_LIBSQL_HOST` | set by run-in-docker.sh | the libSQL sidecar's network alias, only in a run with the flag; `libsqlConnection()` reads it | | `COUCHDB_IMAGE` | run-in-docker.sh | CouchDB sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | | `E2E_COUCHDB_HOST` | set by run-in-docker.sh | the CouchDB sidecar's network alias, only in a run with the flag; `couchdbConnection()` reads it | +| `DYNAMODB_IMAGE` | run-in-docker.sh | DynamoDB Local sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | +| `E2E_DYNAMODB_HOST` | set by run-in-docker.sh | the DynamoDB Local sidecar's network alias, only in a run with the flag; `dynamodbConnection()` reads it | | `E2E_FIREBIRD_HOST` | set by run-in-docker.sh | the Firebird sidecar's network alias, only in a run with the flag; `firebirdConnection()` reads it | | `E2E_INCLUDE_QUARANTINE`, `E2E_INCLUDE_INSERT_ALL`, `E2E_INCLUDE_SUPERADMIN` | script and config | non-empty: include that opt-in group | | `E2E_STACK_PROFILE` | run-in-docker.sh, config | `default` (the default), `signup-disabled` (the app container gets `LOWCODER_EMAIL_SIGNUP_ENABLED=false` and the run keeps only the `@signup-disabled` tests; `E2E_INCLUDE_QUARANTINE` is the only flag that applies) or `enterprise`: the app container gets `LOWCODER_WORKSPACE_MODE=ENTERPRISE` and the run keeps only the `@enterprise` tests (`grep`); another value stops the run. On the enterprise profile `E2E_INCLUDE_QUARANTINE` opens nothing extra (no enterprise test is quarantined any more), `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` change nothing (the stack has one workspace, so the D-47 limit does not arise). A `--grep` of the command line narrows the profile's selection further; it does not replace it (measured with Playwright 1.64: enterprise profile with `--grep SEC-R01b` lists 0 tests, with `--grep SEC-E02` lists 1, with the default profile `--grep SEC-E02` lists 0) | @@ -238,7 +247,7 @@ e2e/ fixtures/firebird/init.sql Firebird sidecar data (opt-in sidecar): FB_ITEMS, FB_NOTES fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb` (the form's body with placeholders, `couchdbQuery.json` is the editor's saved `allDBs`, and one query recording per further operation of the CouchDB sidecar tests, `couchdbQuery.json`: Put, Get, Delete, DocPut, DocGet, DocDelete, DocGetAll; recorded in a session on a stack with the sidecar, the data source typed with the sidecar's own host and login, operation picked in the editor's Resource and Operation lists; the field values of every recording are the editor's empty defaults, so no host or login survives), `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate), `firebird` (the form's body with the sidecar's own host, port, database path and throw-away login, because the host cannot be a placeholder, and the editor's saved query; recorded in a session on a stack with the sidecar), `supabase` (the form's body, and one query recording per action: `supabaseQuery.json` is listBuckets, the others are `supabaseQuery.json`: ListObjects, ReadFile, UploadData, DeleteFile, CreateSignedUrl), `dynamodb` and `s3` (the form's body, and one query recording per action because the saved query differs by action: `Query.json` is the editor's default action, the others are `Query.json`, loaded by `recordedPluginQuery(id, "")`: `dynamodb` Query, ListTables, GetItem, PutItem; `s3` listBuckets, ListObjects, ReadFile, UploadData, DeleteFile) + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb` (the form's body with placeholders, `couchdbQuery.json` is the editor's saved `allDBs`, and one query recording per further operation of the CouchDB sidecar tests, `couchdbQuery.json`: Put, Get, Delete, DocPut, DocGet, DocDelete, DocGetAll; recorded in a session on a stack with the sidecar, the data source typed with the sidecar's own host and login, operation picked in the editor's Resource and Operation lists; the field values of every recording are the editor's empty defaults, so no host or login survives), `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate), `firebird` (the form's body with the sidecar's own host, port, database path and throw-away login, because the host cannot be a placeholder, and the editor's saved query; recorded in a session on a stack with the sidecar), `supabase` (the form's body, and one query recording per action: `supabaseQuery.json` is listBuckets, the others are `supabaseQuery.json`: ListObjects, ReadFile, UploadData, DeleteFile, CreateSignedUrl), `dynamodb` and `s3` (the form's body, and one query recording per action because the saved query differs by action: `Query.json` is the editor's default action, the others are `Query.json`, loaded by `recordedPluginQuery(id, "")`: `dynamodb` Query, Scan, PutItem, GetItem, UpdateItem, DeleteItem, ListTables, CreateTable (the first four were recorded against the echo, the other four in a session on a stack with the DynamoDB Local sidecar: the data source typed with the sidecar's own endpoint and throw-away key, one query per action picked in the editor's Action list; the field values are the editor's defaults, so no host or key survives); `s3` listBuckets, ListObjects, ReadFile, UploadData, DeleteFile) src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -287,15 +296,16 @@ Test titles carry these ids. - D12 the Firebird plugin of node-service against the opt-in Firebird sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): the connection test attaches, a wrong password and a missing database file fail it with the server's text, a named parameter answers the lower-cased row, every column type of the seeded table, parameters bound in SQL order, not object order, an unknown parameter is refused with its name, an INSERT is read back by its own owner, a SQL error is the failed query's message, the lower-case option, a failing query leaves its attachment open (NSD-13 candidate), and the runner reaches the sidecar over TCP. - D13 the Turso plugin of node-service against the opt-in libSQL server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): create, insert and select answer typed rows (integer, real, a lower-case `boolean`, `datetime`, NULL), `includeRaw` answers the server's own result set, a write answers no values and its raw result counts the change, a blob cell is dropped from the row (NSD-14 candidate), an integer beyond 2^53 is rounded (NSD-15 candidate), a real SQL error (syntax, unknown column, constraint, two statements) fails the query with `[object Object]` (NSD-1 candidate, the defect of D5d against a real server), a token of another key or a malformed one is a 401, a read-only token reads and its write is a 403, the published view after a click, a trailing slash after the URL is a 404, and the runner reaches the sidecar. The `libsql://` rewrite is not covered. - D14 the CouchDB plugin of node-service against the opt-in CouchDB server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): a database is created, listed (by a key range), described and deleted, and the server agrees at each step; a document is created, read, updated by its revision, read at its old revision, listed and deleted; a stale revision (as a query parameter or as `If-Match`) answers a conflict body and changes nothing (NSD-4 candidate); a missing database or document and an existing database answer their error bodies (NSD-4 candidate); a wrong password answers an unauthorized body and writes nothing (NSD-4 candidate); five wrong passwords lock the account for the client address and even the right password then gets the lockout's 403 body (NSD-4 candidate); `docGet` cannot run without `If-None-Match` and a matching ETag fails with `status: 304` (NSD-16 candidate); the listing options (`startkey`, `endkey`, `descending`, `skip`, `limit`) reach the server; the published view shows a document after a click; and the runner reaches the sidecar. The JWT credential and cookie sessions are not covered. +- D15 the DynamoDB plugin of node-service against the opt-in DynamoDB Local server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): a table is created (the description's complete shape), refused when it exists, listed and paged by name, and the server agrees at each step (D15a); an item of every type the plugin writes (string, empty string, integers, negative, fraction, booleans, null, map, number set, string set, mixed list, list of maps) is stored in the typed form and read back as plain values (D15b); Query (key condition, range, projection, descending, `Limit`) and Scan (filter, `Select: COUNT`) answer unwrapped items with the counts, `LastEvaluatedKey` stays typed, and a scan with `Limit: 2` is paged by feeding each returned typed key into the next request until none is returned: no item missing or twice, no page above the limit, at least three requests, the last page without a key (D15c); UpdateItem and DeleteItem change the server's data, a failed condition changes nothing, and `ReturnValues` answers `Attributes` that stay typed (D15d, D15e, NSD-17 candidate); a missing table, a failed condition, a missing or mistyped key, an empty key, a bad table name and an existing table fail the query with the server's own message (D15f); an array of strings or numbers is always a set (order lost, duplicates and an empty array refused, NSD-18 candidate, D15g); a binary attribute reads as an object with index keys and a number beyond a double loses digits (NSD-19 candidate, D15h); an `ExclusiveStartKey` in the plain form fails with the SDK's `TypeError` (NSD-20 candidate, D15i); any access key reaches the same tables and a closed port of the sidecar's host fails with the connection error (D15j); the published view shows an item after a click (D15k); and the runner reaches the sidecar (D15l). DescribeTable and DeleteTable are not offered by the form (direct calls only); indexes, transactions, batch operations and streams are not covered. - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue -Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 839-test suite (before the last unit test, the readiness-limit one, was added; the suite lists 840 now) after the CouchDB sidecar scenarios (D14) landed, `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (no variable set): 44 failed, 795 passed. It started no Firebird, libSQL or CouchDB container (the script logged only the PostgreSQL, echo and app starts; a separate default run measured with `docker events` created the app, the echo, PostgreSQL and the runner) and ran no D12, D13 or D14 test (they are not in the listing). The baseline from a clean worktree of the previous commit (833 tests, same command and image): 44 failed, 789 passed. The failing sets are identical (compared by test name): 25 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`; `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag, not analysed one by one). `SEC-R09d` is one of the 25 in both runs (the earlier full run, 43 failed, did not fail it: it is intermittent); the periodic trigger test of `logic/triggers.spec.ts` failed in neither. The six extra passes are the six new unit tests of `foundation/node-plugins.spec.ts`. No node-service scenario failed. The D12, D13 and D14 evidence is a separate gate each, `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 `: for `tests/datasource/plugin-firebird.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D12 landed), for `tests/datasource/plugin-turso-libsql.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D13 landed), for `tests/datasource/plugin-couchdb.spec.ts` 100 passed on `3.0.0-e2e` and 100 passed on `3.0.1-e2e`, and after the readiness probes got their time limits 110 passed for the Firebird spec and 110 for the libSQL spec on `3.0.0-e2e` (all three sidecars start; the app was ready 15 s after the first container started with the flag against 14 s without it). With the flag, `--grep @node-service-sidecar` ran all 32 sidecar tests (D12, D13, D14) in one run: 32 passed. These Docker results were measured by hand on one machine; no result files are committed, so re-run the commands named here to reproduce them.): -default **840 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **854 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **845 in 114**; with both of those **859 in 115**; -with `E2E_INCLUDE_INSERT_ALL=1` **952 in 115**; with all three opt-in variables **971 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **872 in 117** (the 11 D12 tests of the Firebird sidecar, the 11 D13 tests of the libSQL sidecar and the 10 D14 tests of the CouchDB sidecar, which no other variable lists), and **1003 in 119** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: +Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 847-test suite after the DynamoDB Local sidecar scenarios (D15) landed (measured before the readiness loops of the four sidecars got their elapsed-time deadline and before one more unit test and the extra controls of D15c, D15e and D15f were added; it was not repeated after them, only the gates below were), `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (no variable set): 43 failed, 804 passed (6.7 min). It started no Firebird, libSQL, CouchDB or DynamoDB Local container (a separate default run measured with `docker events` created the PostgreSQL, echo, app and runner containers only) and ran no D12 to D15 test (they are not in the listing). The baseline from a clean worktree of the previous commit (840 tests, same command and image): 44 failed, 796 passed. The failing sets are identical except one test (compared by test name): 24 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`; `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag, not analysed one by one). The one difference is `SEC-R09d`, which failed in the baseline and passed in this run (it is intermittent: it passed here and in an earlier full run, and failed in both baselines); the periodic trigger test of `logic/triggers.spec.ts` failed in neither. The eight extra passes are the seven new unit tests of `foundation/node-plugins.spec.ts` and the one more test that passed here instead of failing. No node-service scenario failed. The D12, D13 and D14 evidence is a separate gate each, `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 `: for `tests/datasource/plugin-firebird.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D12 landed), for `tests/datasource/plugin-turso-libsql.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D13 landed), for `tests/datasource/plugin-couchdb.spec.ts` 100 passed on `3.0.0-e2e` and 100 passed on `3.0.1-e2e`, and after the readiness probes got their time limits 110 passed for the Firebird spec and 110 for the libSQL spec on `3.0.0-e2e` (all three sidecars start; the app was ready 15 s after the first container started with the flag against 14 s without it). For `tests/datasource/plugin-dynamodb-local.spec.ts` (D15) 120 passed on `3.0.0-e2e` and 120 passed on `3.0.1-e2e`, run after the last change of the spec (all four sidecars start; `docker events` showed the PostgreSQL, echo, Firebird, libSQL, CouchDB and DynamoDB Local containers created within one second, and the script logged every readiness wait as `ready after 0s`, the last one three seconds after the first container was created; the readiness waits run after the app container is started, so they do not delay it). A flagged run left two dangling volumes (PostgreSQL's and Firebird's) and so did the same run before this sidecar existed, and a default run left one (PostgreSQL's): the DynamoDB Local sidecar adds none (`docker volume ls -f dangling=true | wc -l` before and after: 134 to 136 for a flagged run, 133 to 134 for a default run). With the flag, `--grep @node-service-sidecar` ran all the sidecar tests (D12, D13, D14) in one run when D14 landed: 32 passed; D15 was run through its own gate above, not in that combined run. After the four readiness loops got their elapsed-time deadline, `tests/datasource/plugin-firebird.spec.ts` (11), `plugin-turso-libsql.spec.ts` (11) and `plugin-couchdb.spec.ts` (10) each ran once on `3.0.0-e2e` with the flag and passed, and the D15 gate above was repeated (120 passed on both images). These Docker results were measured by hand on one machine; no result files are committed, so re-run the commands named here to reproduce them.): +default **848 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **862 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **853 in 114**; with both of those **867 in 115**; +with `E2E_INCLUDE_INSERT_ALL=1` **960 in 115**; with all three opt-in variables **979 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **892 in 118** (the 11 D12 tests of the Firebird sidecar, the 11 D13 tests of the libSQL sidecar, the 10 D14 tests of the CouchDB sidecar and the 12 D15 tests of the DynamoDB Local sidecar, which no other variable lists), and **1023 in 120** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 135 in 10 files (the 44 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **167 in 13 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests, the 11 D13 tests and the 10 D14 tests); `@node-service-sidecar` 0 (**32 in 3 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests, D13a to D13k, the libSQL sidecar tests, and D14a to D14j, the CouchDB sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 143 in 10 files (the 52 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **187 in 14 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests, the 11 D13 tests, the 10 D14 tests and the 12 D15 tests); `@node-service-sidecar` 0 (**44 in 4 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests, D13a to D13k, the libSQL sidecar tests, D14a to D14j, the CouchDB sidecar tests, and D15a to D15l, the DynamoDB Local sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -363,6 +373,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/plugin-firebird.spec.ts | D12: the Firebird plugin against the opt-in Firebird sidecar (Firebird 3.0.12, `fixtures/firebird/init.sql`; host, port, database path and login of the sidecar written over the recorded form body). Measured on 3.0.0-e2e and 3.0.1-e2e. D12a the connection test answers `code` 1, `success` true, `data` true; D12b a wrong password answers `code` 500 with `Failed to connect data source: Your user name and password are not defined. Ask your database\nadministrator to set up a Firebird login\n.` and a missing database file with the server's `I/O error for file ...` (the right fields attach first); D12c `SELECT ID, NAME FROM FB_ITEMS WHERE ID = :id` with `{"id": 2}` answers `[{id: 2, name: "beta"}]`; D12d the three seeded rows with `price` as a number and a NULL as `null`; D12e parameters bind in the order the names appear in the SQL, not the key order of the parameter object (`CAST(:first AS INTEGER) - CAST(:second AS INTEGER)` with 10 and 3 answers 7 whichever order the object lists them); D12f an unknown name fails with `Named parameter "missing" not found in Query Parameters object.` (the same SQL with the name present runs); D12g an INSERT answers `{}` and is read back by the test's own owner (the owner has no row before); D12h a syntax error and an unknown table answer the server's text; D12i `lowercaseKeys: false` answers upper-case keys; D12j a query that fails after the attach leaves its attachment open on the server, a succeeding one does not: two failing runs of a statement that tags its attachment with a per-test context variable leave exactly two tagged attachments in `MON$CONTEXT_VARIABLES`, and a succeeding tagged run does not add a third (NSD-13 candidate, `defect` annotation); D12k the runner connects to the sidecar's port 3050, and a closed port of the same host is refused. Limits: `role`, `blobAsText` and Firebird 4 and 5 are not covered; the sidecar authenticates with Legacy_Auth (see the architecture bullet) | @node-service @node-service-sidecar (opt-in) | 11 | | datasource/plugin-turso-libsql.spec.ts | D13: the Turso plugin against the opt-in libSQL sidecar (sqld 0.24.33 with a JWT key; the data source URL is `http://e2e-libsql:8080`, the recorded `turso` form body with the sidecar's URL and token written over it; each test makes its own table `e2e_t_`). Measured on 3.0.0-e2e and 3.0.1-e2e. D13a CREATE, two INSERTs and a SELECT: a CREATE and an INSERT answer `[]`, the empty table answers `[]` before the inserts, then `integer` is a number, `real` 2 stays 2, a `boolean` column written in lower case is `true`/`false`, a `datetime` text is the ISO text of a `Date` (`2024-01-02T03:04:05.000Z`), NULL is `null`; D13b `includeRaw` answers `values` and the server's `raw` (columns with their declared types, cells such as `{type:"integer", value:"7"}`, the counters; the timing is only checked to be a number); D13c an INSERT answers `[]` with and without `includeRaw`, its raw result has `affected_row_count` 1 and `last_insert_rowid` `"2"` (a string) for the second row; D13d a blob cell is missing from the row (`[{id: 1}]`) while `includeRaw` shows the server sent `{type:"blob", base64:"AP8Q"}` (NSD-14 candidate); D13e `SELECT 9007199254740993` answers 9007199254740992 while the raw cell is the exact string (NSD-15 candidate); D13f `SELEC 1`, an unknown column, a duplicate key and `SELECT 1; SELECT 2` are errors of the server with codes `SQL_PARSE_ERROR`, `SQL_INPUT_ERROR`, `SQLITE_CONSTRAINT` and `SQL_MANY_STATEMENTS` (read by direct calls), and every one of them reaches the app as `Cannot parse result, received error: [object Object]` (NSD-1 candidate; a valid query of the same app succeeds first); D13g a token signed by another key and a string that is no JWT fail with `Failed to execute query. Endpoint returned 401: Unauthorized.` (the sidecar's own token reads the row first; direct calls show the server's `The JWT is invalid` and, without a header, `Expected authorization header but none given`); D13h a read-only token reads, its INSERT fails with `Endpoint returned 403: Forbidden.` and writes nothing (the read-write token then inserts the same row); D13i the published view shows a row after a click; D13j a URL with a trailing slash fails with `Endpoint returned 404: Not Found.` (the plugin builds `//v2/pipeline`; the same URL without it works); D13k the runner reaches the sidecar over HTTP and TCP, a closed port of the same host is refused. Limits: the `libsql://` to `https://` rewrite, a stream with a baton, and Turso's cloud features are not covered | @node-service @node-service-sidecar (opt-in) | 11 | | datasource/plugin-couchdb.spec.ts | D14: the CouchDB plugin against the opt-in CouchDB sidecar (Apache CouchDB 3.5.1; the data source URL is `http://e2e-couchdb:5984`; the recorded `couchdb` form body with the sidecar's URL and admin written over it; each test makes its own database `e2e_couch_` and removes it). Measured on 3.0.0-e2e and 3.0.1-e2e. D14a a database is created (`{ok: true}`), listed by a key range (`[]` before, `[]` after), described (`GET /`: the member set of 3.5.1, `doc_count` 0), and deleted, with direct reads of the server at each step; D14b a document is created (`{ok, id, rev: 1-...}`), read (`{_id, _rev, ...body}`), updated with `rev` as a query parameter (`2-...`), read at its first revision, listed with `include_docs`, and deleted (`3-...`; the server then answers `deleted`), and the server's own copy matches; D14c a stale revision (query parameter and `If-Match`, on write and delete) and a write without a revision answer `{error: "conflict", reason: "Document update conflict."}` as the data of a SUCCESSFUL query (the server's status is 409), change nothing, and the current revision is accepted by a write and by both kinds of delete (NSD-4 candidate); D14d a missing document, a document of a missing database, the information and the delete of a missing database (404 bodies) and a create of an existing database (412 `file_exists`) are successful queries with the error body as the data (NSD-4 candidate), with successful controls through the same operations (an existing document is read, an existing database is described and deleted, a new one is created); D14e a wrong password answers `{error: "unauthorized", reason: "Name or password is incorrect."}` as the data of a successful query and the refused create made no database, while the right password on the same queries lists and creates (NSD-4 candidate; the account is a second admin the test makes); D14f `docGet` with an empty `If-None-Match` fails with the plugin's own `Required parameter If-None-Match is not provided` (the server reads the same document without the header), a value that is not the current ETag reads the document, and the current ETag (the server answers 304) fails with `status: 304` (NSD-16 candidate); D14g `startkey`/`endkey`, `descending`, `skip` and `limit` give the lists the server gives, for databases and for the documents of a database (`total_rows` counts all of them), and an unscoped list holds the three system databases and the test's own; D14h the published view shows the document's title after a click; D14i the runner reaches the sidecar over HTTP and TCP (`Welcome`, version 3.5.1, `_all_dbs` needs credentials), a closed port of the same host is refused; D14j five wrong passwords of an account are 401 bodies, the sixth and the right password after them are the lockout's 403 body as the data of a successful query (the runner, another client address, is not locked until it fails five times itself, then the server's own status is 403) (NSD-4 candidate). Limits: JWT and cookie authentication, replication, design documents, partitions, attachments and bulk operations are not covered | @node-service @node-service-sidecar (opt-in) | 10 | +| datasource/plugin-dynamodb-local.spec.ts | D15: the DynamoDB plugin against the opt-in DynamoDB Local sidecar (DynamoDB Local 3.3.2, `-inMemory -sharedDb`; the endpoint is `http://e2e-dynamodb:8000`; the recorded `dynamodb` form body with the sidecar's endpoint and throw-away key written over it; each test makes its own tables `e2e_ddb_` and removes them). Measured on 3.0.0-e2e and 3.0.1-e2e. D15a to D15l as in the catalogue (D15): table create, list and paging, the typed round trip of every type, Query and Scan with pagination keys, UpdateItem and DeleteItem with conditions and `ReturnValues`, the server's error messages, sets, binary and big numbers, the plain `ExclusiveStartKey`, any access key and a closed port, the published view, and the runner's reach. NSD-17 to NSD-20 candidates are characterised and annotated. Not covered: indexes, transactions, batch operations, streams, TTL, the signature (the server does not verify it) | @node-service @node-service-sidecar (opt-in) | 12 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -513,8 +524,8 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization`, and the Firebird sidecar helpers: `firebirdConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the firebird recordings (form fields with the sidecar's values, one query, no session value), `fixtures/firebird/init.sql` equals `FIREBIRD_ITEMS`, the script's Firebird constants equal `FIREBIRD`, and the run script starts, waits for and passes the sidecar only inside `if node_service_sidecars_enabled`; and the libSQL sidecar helpers: `libsqlConnection` (reads the host variable, builds the plain-HTTP URL, throws a named error when it is unset or empty), the script's libSQL values equal `LIBSQL` (alias, port, public key, token, an image pinned by tag and digest, the tmpfs data directory), the three tokens are JWTs with the claims they are named for and only the two sidecar ones verify under the sidecar's key (the foreign one is well-formed and does not), the script starts and waits for the libSQL sidecar only under the flag and appends its `--add-host` and host variable to the Firebird ones, and `libsqlDirect` against a local server (the pipeline body, the bearer header or none, a JSON or a text body); and the CouchDB sidecar helpers: `couchdbConnection` (reads the host variable, builds the plain-HTTP URL with the admin, throws a named error when it is unset or empty), the script's CouchDB values equal `COUCHDB` (alias, port, admin, the system databases, an image pinned by tag and digest, the tmpfs data directory), the script starts and waits for the CouchDB sidecar only under the flag, appends its `--add-host` and host variable to the others, bounds the wait by `STARTUP_TIMEOUT` and removes the container in the trap, the CouchDB recordings (one per operation: action name, the form's fields in order, every value the editor's empty default, no session value, no sidecar address), and `couchdbDirect` and `couchdbAdmin` against a local server (method, path, JSON body, extra headers, Basic credentials or none, a JSON or a text body), and the readiness steps of the script (every CouchDB readiness curl carries a connect and a total time limit, the system-database PUT counts only on 201 or 412, the libSQL fetch and the Firebird isql are bounded too) | @node-service | 44 | -| foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources), `@node-service-sidecar` (excluded by default, included by `E2E_INCLUDE_NODE_SERVICE_SIDECARS`, independent of the other flags, never selected on the enterprise and signup-disabled stacks), and the guard that every test of a spec that calls `firebirdConnection`, `libsqlConnection` or `couchdbConnection` carries `@node-service-sidecar` (same parsing; synthetic sources; the specs that use a helper are the CouchDB, Firebird and libSQL ones) | none | 32 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization`, and the Firebird sidecar helpers: `firebirdConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the firebird recordings (form fields with the sidecar's values, one query, no session value), `fixtures/firebird/init.sql` equals `FIREBIRD_ITEMS`, the script's Firebird constants equal `FIREBIRD`, and the run script starts, waits for and passes the sidecar only inside `if node_service_sidecars_enabled`; and the libSQL sidecar helpers: `libsqlConnection` (reads the host variable, builds the plain-HTTP URL, throws a named error when it is unset or empty), the script's libSQL values equal `LIBSQL` (alias, port, public key, token, an image pinned by tag and digest, the tmpfs data directory), the three tokens are JWTs with the claims they are named for and only the two sidecar ones verify under the sidecar's key (the foreign one is well-formed and does not), the script starts and waits for the libSQL sidecar only under the flag and appends its `--add-host` and host variable to the Firebird ones, and `libsqlDirect` against a local server (the pipeline body, the bearer header or none, a JSON or a text body); and the CouchDB sidecar helpers: `couchdbConnection` (reads the host variable, builds the plain-HTTP URL with the admin, throws a named error when it is unset or empty), the script's CouchDB values equal `COUCHDB` (alias, port, admin, the system databases, an image pinned by tag and digest, the tmpfs data directory), the script starts and waits for the CouchDB sidecar only under the flag, appends its `--add-host` and host variable to the others, bounds the wait by `STARTUP_TIMEOUT` and removes the container in the trap, the CouchDB recordings (one per operation: action name, the form's fields in order, every value the editor's empty default, no session value, no sidecar address), and `couchdbDirect` and `couchdbAdmin` against a local server (method, path, JSON body, extra headers, Basic credentials or none, a JSON or a text body), and the readiness steps of the script (every CouchDB readiness curl carries a connect and a total time limit, the system-database PUT counts only on 201 or 412, the libSQL fetch and the Firebird isql are bounded too), and the DynamoDB Local sidecar helpers: `dynamodbConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the script's DynamoDB values equal `DYNAMODB` (alias, port, image pinned by tag and digest, `-inMemory -sharedDb`), the start and wait steps run only under the flag and the host variable is named once, the readiness call has the abort limit, accepts exactly status 200 and needs a `TableNames` member, the eight dynamodb query recordings (one per action, no session value), the readiness loops of all four sidecars (elapsed-time deadline from `SECONDS`, compared with `STARTUP_TIMEOUT` after every failed probe; a loop that adds up its sleeps only fails), the DynamoDB probe parses the body as JSON and needs a `TableNames` array, and `dynamodbDirect` against a local server (method, path, target header, content type, typed body, credential scope, a JSON or a text answer) | @node-service | 52 | +| foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources), `@node-service-sidecar` (excluded by default, included by `E2E_INCLUDE_NODE_SERVICE_SIDECARS`, independent of the other flags, never selected on the enterprise and signup-disabled stacks), and the guard that every test of a spec that calls `firebirdConnection`, `libsqlConnection`, `couchdbConnection` or `dynamodbConnection` carries `@node-service-sidecar` (same parsing; synthetic sources; the specs that use a helper are the CouchDB, DynamoDB Local, Firebird and libSQL ones) | none | 32 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | | foundation/module-host.spec.ts | module created through the API works in a host; republish rules | none | 2 | @@ -569,6 +580,10 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-14 candidate | the Turso plugin drops a `blob` cell: the server answers it as `{type:"blob", base64}` with no `value`, `parseValue` returns `undefined` for it, and the key is missing from the row (`SELECT id, data` answers `[{id: 1}]`). Measured on 3.0.0-e2e and 3.0.1-e2e against the libSQL sidecar. The id is provisional until the owner assigns one | `datasource/plugin-turso-libsql.spec.ts` D13d, `defect` annotation `NSD-14 candidate`; passes today, expect it to fail once the plugin returns the bytes | | NSD-15 candidate | the Turso plugin parses an `integer` cell (which the server sends as a string, exact) with `Number.parseInt`, so an integer above 2^53 is rounded: `SELECT 9007199254740993` answers 9007199254740992 while `includeRaw` shows the exact string. Measured on 3.0.0-e2e and 3.0.1-e2e against the libSQL sidecar. The id is provisional until the owner assigns one | `datasource/plugin-turso-libsql.spec.ts` D13e, `defect` annotation `NSD-15 candidate`; passes today, expect it to fail once the plugin keeps large integers exact | | NSD-16 candidate | the CouchDB plugin cannot run `docGet` without an `If-None-Match` header: the bundled API document marks it required (the server treats it as optional: a read without it answers the document), and `runOpenApi` refuses the query with `Required parameter If-None-Match is not provided`; a value that is not the current ETag (`e2e-no-match` measured) reads the document, and a value equal to the document's current ETag (`""`) makes the server answer 304 with no body, which fails the query with `status: 304`. So a read of a document cannot be made without a header the user has no use for. Measured on 3.0.0-e2e and 3.0.1-e2e against the CouchDB sidecar. The id is provisional until the owner assigns one | `datasource/plugin-couchdb.spec.ts` D14f, `defect` annotation `NSD-16 candidate` (characterisation, passes today after controls that the server reads the document without the header and answers 304 to the current ETag); it changes when the header is optional | +| NSD-17 candidate | the DynamoDB plugin unwraps `Item` and `Items` of an answer (`processItems`) and nothing else: `Attributes` of a `ReturnValues` answer (`ALL_NEW`, `ALL_OLD`) and `LastEvaluatedKey` stay in DynamoDB's typed form (`{"age":{"N":"19"}}`), while the same item read by GetItem is plain (`{"age":19}`). `LastEvaluatedKey` staying typed is what a typed `ExclusiveStartKey` needs to continue; `Attributes` has no such use. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15d and D15e, `defect` annotation `NSD-17 candidate` (characterisation, passes today next to a direct read of the server's data and a plain GetItem of the same item); it changes when `Attributes` is unwrapped | +| NSD-18 candidate | the DynamoDB plugin writes every array of strings as a string set and every array of numbers as a number set (`dynamodb-data-types` `detectType`; only other arrays are lists), so a list of strings or numbers cannot be stored: the order is lost (`["zeta","alpha","mid"]` reads back `["alpha","mid","zeta"]`), duplicates fail the query (`Input collection [a, a] contains duplicates`) and an empty array fails with `An number set may not be empty` (sic, the server's text). An array of mixed values is a list and keeps its order. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15g, `defect` annotation `NSD-18 candidate` (characterisation, passes today next to the mixed array, which is a list); it changes when a list can be written | +| NSD-19 candidate | the DynamoDB plugin reads a number with `Number()`, so a number beyond a double loses digits (`12345678901234567890` reads `12345678901234567000`; the server holds it exactly), and a binary attribute (`B`, `BS`) is read as a byte array that the answer's JSON turns into an object with index keys (`{"0":104,"1":101,...}`); a binary cannot be written either: a typed `{"B":"..."}` inside `Item` is wrapped like any object and stored as a map. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15h, `defect` annotation `NSD-19 candidate` (characterisation, passes today next to a direct read that shows the exact number and the binary); it changes when numbers and binaries are returned exactly | +| NSD-20 candidate | an `ExclusiveStartKey` given in the plain form (`{"id": 1}`, as `Key` is written) is not wrapped (only `Key`, `Item` and `Items` are) and fails inside the SDK's serialiser with the JavaScript text `Cannot read properties of undefined (reading '0')` instead of a validation message; the typed form (`{"id": {"N": "1"}}`) works. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15i, `defect` annotation `NSD-20 candidate` (characterisation, passes today next to the typed form of the same key, which continues the read); it changes when the key is wrapped or refused with a message | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/fixtures/dsl/plugins/dynamodb/dynamodbCreateTableQuery.json b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbCreateTableQuery.json new file mode 100644 index 0000000000..83a84d6479 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbCreateTableQuery.json @@ -0,0 +1,15 @@ +{ + "compType": "dynamodb", + "comp": { + "actionName": "CreateTable", + "action": { + "params": "{\n \"TableName\": \"users\",\n \"AttributeDefinitions\": [\n {\n \"AttributeName\": \"id\",\n \"AttributeType\": \"N\"\n }\n ],\n \"KeySchema\": [\n {\n \"AttributeName\": \"id\",\n \"KeyType\": \"HASH\"\n }\n ],\n \"ProvisionedThroughput\": {\n \"ReadCapacityUnits\": 1,\n \"WriteCapacityUnits\": 1\n },\n \"StreamSpecification\": {\n \"StreamEnabled\": false\n }\n}" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/dynamodb/dynamodbDeleteItemQuery.json b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbDeleteItemQuery.json new file mode 100644 index 0000000000..30b73f52f6 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbDeleteItemQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "dynamodb", + "comp": { + "actionName": "DeleteItem", + "action": { + "tableName": "", + "params": "{\n \"Key\": {\n \"id\": 1\n }\n}" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/dynamodb/dynamodbScanQuery.json b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbScanQuery.json new file mode 100644 index 0000000000..faaa399fd2 --- /dev/null +++ b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbScanQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "dynamodb", + "comp": { + "actionName": "Scan", + "action": { + "tableName": "", + "params": "{\n \"FilterExpression\": \"id > :n\",\n \"ExpressionAttributeValues\": {\n \":n\": {\n \"N\": \"0\"\n }\n }\n}" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/fixtures/dsl/plugins/dynamodb/dynamodbUpdateItemQuery.json b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbUpdateItemQuery.json new file mode 100644 index 0000000000..7a38a5141b --- /dev/null +++ b/e2e/fixtures/dsl/plugins/dynamodb/dynamodbUpdateItemQuery.json @@ -0,0 +1,16 @@ +{ + "compType": "dynamodb", + "comp": { + "actionName": "UpdateItem", + "action": { + "tableName": "", + "params": "{\n \"Key\": {\n \"id\": 1\n },\n \"UpdateExpression\": \"set age = :n\",\n \"ExpressionAttributeValues\": {\n \":n\": {\n \"N\": \"18\"\n }\n }\n}" + }, + "headers": [ + { + "key": "", + "value": "" + } + ] + } +} \ No newline at end of file diff --git a/e2e/scripts/run-in-docker.sh b/e2e/scripts/run-in-docker.sh index 87d580ba3d..276b86f551 100755 --- a/e2e/scripts/run-in-docker.sh +++ b/e2e/scripts/run-in-docker.sh @@ -24,8 +24,8 @@ ## E2E_INCLUDE_SUPERADMIN set to 1 to also run the @superadmin tests (SEC-R16a to SEC-R16d, the instance super admin; ## independent of the other flags). Run: E2E_INCLUDE_SUPERADMIN=1 $0 --grep @superadmin ## E2E_INCLUDE_NODE_SERVICE_SIDECARS set to 1 to also start the sidecars of the node-service data sources: real servers a plugin can be pointed at, for plugins -## whose protocol the echo cannot serve (Firebird: a wire protocol) or whose real behaviour the echo's canned answers say nothing about (libSQL, CouchDB) -## (today a Firebird server, FIREBIRD_IMAGE below, a libSQL server, LIBSQL_IMAGE below, and a CouchDB server, COUCHDB_IMAGE below) and run their @node-service-sidecar tests; independent of the +## whose protocol the echo cannot serve (Firebird: a wire protocol) or whose real behaviour the echo's canned answers say nothing about (libSQL, CouchDB, DynamoDB Local) +## (today a Firebird server, FIREBIRD_IMAGE below, a libSQL server, LIBSQL_IMAGE below, a CouchDB server, COUCHDB_IMAGE below, and a DynamoDB Local server, DYNAMODB_IMAGE below) and run their @node-service-sidecar tests; independent of the ## other flags, default stack only (any other profile is an error). Without it the run starts none of them, ## neither lists nor runs those tests, and pulls no extra image. ## Run only these: E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 $0 --grep @node-service-sidecar @@ -45,6 +45,7 @@ ## FIREBIRD_IMAGE Firebird sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS ## LIBSQL_IMAGE libSQL server (sqld) sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS ## COUCHDB_IMAGE CouchDB sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS +## DYNAMODB_IMAGE DynamoDB Local sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS ## E2E_HOST_PORT also publish the app on 127.0.0.1: to look at it in a browser while the run lasts ## ## Set by the script for each run (a value of the caller is overwritten; the password is new every run, never printed, @@ -97,6 +98,12 @@ ## until it succeeds or STARTUP_TIMEOUT passes. The data lives in a tmpfs (the image declares /opt/couchdb/data a volume, which `docker rm -f` would leave behind), ## and `cleanup` removes the container however the run ends. Without the flag nothing of this runs. ## +## Only with E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 it also starts a DynamoDB Local sidecar (DYNAMODB_IMAGE) under the alias e2e-dynamodb, port 8000: the target of the DynamoDB data +## source of node-service (a real server that implements the DynamoDB wire API in place of the echo's canned answers). It starts after the CouchDB sidecar and is reached exactly +## like it: `--add-host e2e-dynamodb:` for the app container and the runner, and the alias as E2E_DYNAMODB_HOST for the runner. It runs in memory with one database shared by +## every access key (`-inMemory -sharedDb`), checks no credential, and the image declares no volume, so `cleanup` removes everything however the run ends. The script waits until +## one real ListTables call, posted from the echo container over the run network, answers 200 with a `TableNames` member. Without the flag nothing of this runs. +## ## Not covered: Firefox and WebKit (only Chromium runs), the multi-container compose setup, databases other than ## PostgreSQL. ## @@ -157,10 +164,24 @@ readonly COUCHDB_HTTP_CREATED="201" readonly COUCHDB_HTTP_EXISTS="412" # Seconds a single readiness request may take to connect and in total (a local server answers in milliseconds); small against POLL_INTERVAL and STARTUP_TIMEOUT # so that a stalled request ends the attempt and the wait loop checks its deadline again +# The wait loops of the four sidecars (Firebird, libSQL, CouchDB, DynamoDB Local) measure real elapsed time with the shell's SECONDS and compare it with STARTUP_TIMEOUT after every +# failed probe, so the time a probe takes counts. The check comes before the sleep and the next probe, hence the worst case is STARTUP_TIMEOUT + POLL_INTERVAL + PROBE_REQUEST_TIMEOUT +# (plus the overhead of the docker calls and up to one second of clock granularity, SECONDS counts whole seconds), not an unbounded multiple. This holds for each of the four because +# one probe is bounded as a whole: the Firebird probe is one isql under `timeout -s KILL`, the libSQL and DynamoDB probes are one fetch with an abort signal, and the CouchDB +# probe (five requests) shares one PROBE_REQUEST_TIMEOUT budget (couchdb_curl). The PostgreSQL, echo and app waits still count sleeps only (their probes have no time limit). readonly PROBE_CONNECT_TIMEOUT=2 readonly PROBE_REQUEST_TIMEOUT=5 # The image's data directory, mounted as a tmpfs so that no anonymous volume outlives the run readonly COUCHDB_DATA_DIR="/opt/couchdb/data" +# DynamoDB Local sidecar of the @node-service-sidecar tests, started only with E2E_INCLUDE_NODE_SERVICE_SIDECARS. The image is amazon/dynamodb-local 3.3.2 by tag and +# digest. It runs in memory (`-inMemory`) with one database for every access key (`-sharedDb`); it checks no credential, and the image declares no volume, so nothing +# outlives the container. DYNAMODB_PORT is the image's own HTTP port. +readonly DEFAULT_DYNAMODB_IMAGE="amazon/dynamodb-local:3.3.2@sha256:6ada631ec7aa5fc83446855eb17233e3dad184fec47477e8140c6c569cfe0c86" +readonly DYNAMODB_IMAGE="${DYNAMODB_IMAGE:-$DEFAULT_DYNAMODB_IMAGE}" +readonly DYNAMODB_ALIAS="e2e-dynamodb" +readonly DYNAMODB_PORT=8000 +# The one status the readiness ListTables call counts as "there" +readonly DYNAMODB_HTTP_OK=200 # The instance super admin of the throw-away stack; the domain equals TEST_EMAIL_DOMAIN in e2e/src/constants.ts; the suite # reads the name from E2E_SUPERUSER_USERNAME (SUPER_ADMIN_ENV). The password is generated per run (generate_superuser_password). readonly SUPERUSER_USERNAME="e2e-superadmin@example.test" @@ -196,6 +217,7 @@ readonly ECHO_CONTAINER="${NAME_PREFIX}-echo" readonly FIREBIRD_CONTAINER="${NAME_PREFIX}-fb" readonly LIBSQL_CONTAINER="${NAME_PREFIX}-libsql" readonly COUCHDB_CONTAINER="${NAME_PREFIX}-couchdb" +readonly DYNAMODB_CONTAINER="${NAME_PREFIX}-dynamodb" # The alias and port the app container and the runner use; E2E_ECHO_URL below is built from them (the suite reads it by ECHO_ENV in e2e/src/constants.ts) readonly ECHO_ALIAS="e2e-echo" readonly ECHO_PORT=8080 @@ -205,7 +227,7 @@ readonly ECHO_HEALTH_PATH="/__e2e/health" readonly ECHO_SCRIPT="$SCRIPT_DIR/echo-server.js" # Set by start_echo: the sidecar's IP on the run network (used for --add-host of the app and the runner) ECHO_IP="" -# Set by start_firebird, start_libsql and start_couchdb (only with E2E_INCLUDE_NODE_SERVICE_SIDECARS): the extra `--add-host` and `-e` arguments of the app and the runner. Empty otherwise. +# Set by start_firebird, start_libsql, start_couchdb and start_dynamodb (only with E2E_INCLUDE_NODE_SERVICE_SIDECARS): the extra `--add-host` and `-e` arguments of the app and the runner. Empty otherwise. SIDECAR_ADD_HOST=() SIDECAR_RUNNER_ENV=() @@ -219,7 +241,7 @@ fail() { } cleanup() { - docker rm -f "$RUNNER_CONTAINER" "$APP_CONTAINER" "$POSTGRES_CONTAINER" "$ECHO_CONTAINER" "$FIREBIRD_CONTAINER" "$LIBSQL_CONTAINER" "$COUCHDB_CONTAINER" > /dev/null 2>&1 || true + docker rm -f "$RUNNER_CONTAINER" "$APP_CONTAINER" "$POSTGRES_CONTAINER" "$ECHO_CONTAINER" "$FIREBIRD_CONTAINER" "$LIBSQL_CONTAINER" "$COUCHDB_CONTAINER" "$DYNAMODB_CONTAINER" > /dev/null 2>&1 || true docker network rm "$NETWORK" > /dev/null 2>&1 || true } trap cleanup EXIT @@ -367,15 +389,16 @@ start_firebird() { } wait_for_firebird() { - local waited=0 + local waited=0 started=$SECONDS until echo "SELECT COUNT(*) FROM FB_ITEMS;" | docker exec -i "$FIREBIRD_CONTAINER" timeout -s KILL "$PROBE_REQUEST_TIMEOUT" /opt/firebird/bin/isql -b -user "$FIREBIRD_USER" -password "$FIREBIRD_PASSWORD" "127.0.0.1:${FIREBIRD_DATABASE_PATH}" > /dev/null 2>&1; do + waited=$((SECONDS - started)) if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then docker logs --tail "$LOG_TAIL_LINES" "$FIREBIRD_CONTAINER" >&2 || true fail "the Firebird sidecar did not become ready within ${STARTUP_TIMEOUT}s" fi sleep "$POLL_INTERVAL" - waited=$((waited + POLL_INTERVAL)) done + waited=$((SECONDS - started)) log "Firebird sidecar ready after ${waited}s" } @@ -396,29 +419,38 @@ start_libsql() { # A real Hrana pipeline with the read-write token, posted to the sidecar's alias over the run network from the echo container (the image has no # curl and no shell tools of use): ready when it answers 200 with the integer 1 for `select 1`. wait_for_libsql() { - local waited=0 + local waited=0 started=$SECONDS local probe="fetch(process.env.LIBSQL_PROBE_URL + '/v2/pipeline', { signal: AbortSignal.timeout($((PROBE_REQUEST_TIMEOUT * 1000))), method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + process.env.LIBSQL_PROBE_TOKEN }, body: JSON.stringify({ requests: [{ type: 'execute', stmt: { sql: 'select 1' } }, { type: 'close' }] }) }).then((r) => r.text().then((t) => process.exit(r.ok && t.includes('\"value\":\"1\"') ? 0 : 1)), () => process.exit(1))" until docker exec -e LIBSQL_PROBE_URL="http://${LIBSQL_ALIAS}:${LIBSQL_PORT}" -e LIBSQL_PROBE_TOKEN="$LIBSQL_TOKEN" "$ECHO_CONTAINER" node -e "$probe" > /dev/null 2>&1; do + waited=$((SECONDS - started)) if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then docker logs --tail "$LOG_TAIL_LINES" "$LIBSQL_CONTAINER" >&2 || true fail "the libSQL sidecar did not become ready within ${STARTUP_TIMEOUT}s" fi sleep "$POLL_INTERVAL" - waited=$((waited + POLL_INTERVAL)) done + waited=$((SECONDS - started)) log "libSQL sidecar ready after ${waited}s" } # A fresh single-node CouchDB has an admin and no system databases. This probe is idempotent and runs inside the sidecar over 127.0.0.1 (the image has curl): # the server must answer `_up`, each system database is created through the real API (it counts only when the server answers 201 created or 412 already -# exists; any other answer, or none, is "not ready yet"), and `_all_dbs` must list all of them. Every curl carries a connect and a total time limit, so a -# stalled request ends the probe and the loop of wait_for_couchdb re-checks its deadline instead of blocking past STARTUP_TIMEOUT. +# exists; any other answer, or none, is "not ready yet"), and `_all_dbs` must list all of them. A stalled request ends the probe and the loop of wait_for_couchdb +# re-checks its deadline instead of blocking past STARTUP_TIMEOUT. +# The probe makes five requests, so the limit is on the WHOLE probe, not on each request: COUCHDB_PROBE_DEADLINE is the second (of the shell's SECONDS) at which the probe +# must be over, set by couchdb_probe; every request gets the time that is left of it as its total limit (and at most PROBE_CONNECT_TIMEOUT to connect), and a request that +# finds nothing left is not made and fails the probe. +COUCHDB_PROBE_DEADLINE=0 couchdb_curl() { - docker exec "$COUCHDB_CONTAINER" curl --connect-timeout "$PROBE_CONNECT_TIMEOUT" --max-time "$PROBE_REQUEST_TIMEOUT" -u "${COUCHDB_USER}:${COUCHDB_PASSWORD}" "$@" + local remaining=$((COUCHDB_PROBE_DEADLINE - SECONDS)) connect_limit="$PROBE_CONNECT_TIMEOUT" + [ "$remaining" -gt 0 ] || return 1 + [ "$remaining" -ge "$connect_limit" ] || connect_limit="$remaining" + docker exec "$COUCHDB_CONTAINER" curl --connect-timeout "$connect_limit" --max-time "$remaining" -u "${COUCHDB_USER}:${COUCHDB_PASSWORD}" "$@" } couchdb_probe() { local base="http://127.0.0.1:${COUCHDB_PORT}" database status listed + COUCHDB_PROBE_DEADLINE=$((SECONDS + PROBE_REQUEST_TIMEOUT)) couchdb_curl -sf "${base}/_up" > /dev/null || return 1 for database in "${COUCHDB_SYSTEM_DATABASES[@]}"; do status="$(couchdb_curl -s -o /dev/null -w '%{http_code}' -X PUT "${base}/${database}")" || return 1 @@ -451,18 +483,50 @@ start_couchdb() { } wait_for_couchdb() { - local waited=0 + local waited=0 started=$SECONDS until couchdb_probe > /dev/null 2>&1; do + waited=$((SECONDS - started)) if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then docker logs --tail "$LOG_TAIL_LINES" "$COUCHDB_CONTAINER" >&2 || true fail "the CouchDB sidecar did not become ready within ${STARTUP_TIMEOUT}s" fi sleep "$POLL_INTERVAL" - waited=$((waited + POLL_INTERVAL)) done + waited=$((SECONDS - started)) log "CouchDB sidecar ready after ${waited}s" } +# The image runs the JVM server as its entrypoint (`java -jar DynamoDBLocal.jar`); the flags are the image's own command line plus `-sharedDb`. +start_dynamodb() { + log "Starting $DYNAMODB_IMAGE as $DYNAMODB_CONTAINER (alias $DYNAMODB_ALIAS, port $DYNAMODB_PORT)" + docker run -d --name "$DYNAMODB_CONTAINER" --network "$NETWORK" --network-alias "$DYNAMODB_ALIAS" \ + "$DYNAMODB_IMAGE" -jar DynamoDBLocal.jar -inMemory -sharedDb -port "$DYNAMODB_PORT" > /dev/null + local dynamodb_ip + dynamodb_ip="$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$DYNAMODB_CONTAINER")" + [ -n "$dynamodb_ip" ] || fail "no IP address for $DYNAMODB_CONTAINER on $NETWORK" + SIDECAR_ADD_HOST+=(--add-host "${DYNAMODB_ALIAS}:${dynamodb_ip}") + SIDECAR_RUNNER_ENV+=(-e "E2E_DYNAMODB_HOST=${DYNAMODB_ALIAS}") + log "DynamoDB Local sidecar is $DYNAMODB_ALIAS = $dynamodb_ip" +} + +# A real ListTables call posted to the sidecar's alias over the run network from the echo container (the image has no curl and no shell tools of use). The server wants an +# Authorization header with a `Credential=` scope and does not verify the signature. Ready when it answers exactly DYNAMODB_HTTP_OK with a JSON body whose `TableNames` member is an array (a body that is not JSON, or any error, exits non-zero); the fetch aborts +# after the request limit, so a stalled request ends the attempt and the wait loop checks its deadline again. +wait_for_dynamodb() { + local waited=0 started=$SECONDS + local probe="fetch(process.env.DYNAMODB_PROBE_URL, { signal: AbortSignal.timeout($((PROBE_REQUEST_TIMEOUT * 1000))), method: 'POST', headers: { 'Content-Type': 'application/x-amz-json-1.0', 'X-Amz-Target': 'DynamoDB_20120810.ListTables', Authorization: 'AWS4-HMAC-SHA256 Credential=e2e/20260101/us-west-1/dynamodb/aws4_request, SignedHeaders=host, Signature=00' }, body: '{}' }).then((r) => r.text().then((t) => process.exit(r.status === $DYNAMODB_HTTP_OK && Array.isArray(JSON.parse(t).TableNames) ? 0 : 1))).catch(() => process.exit(1))" + until docker exec -e DYNAMODB_PROBE_URL="http://${DYNAMODB_ALIAS}:${DYNAMODB_PORT}/" "$ECHO_CONTAINER" node -e "$probe" > /dev/null 2>&1; do + waited=$((SECONDS - started)) + if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then + docker logs --tail "$LOG_TAIL_LINES" "$DYNAMODB_CONTAINER" >&2 || true + fail "the DynamoDB Local sidecar did not become ready within ${STARTUP_TIMEOUT}s" + fi + sleep "$POLL_INTERVAL" + done + waited=$((SECONDS - started)) + log "DynamoDB Local sidecar ready after ${waited}s" +} + wait_for_app() { local waited=0 log "Waiting for $READY_PATH (at most ${STARTUP_TIMEOUT}s)" @@ -529,6 +593,9 @@ fi if node_service_sidecars_enabled; then start_couchdb fi +if node_service_sidecars_enabled; then + start_dynamodb +fi start_app wait_for_postgres wait_for_echo @@ -541,5 +608,8 @@ fi if node_service_sidecars_enabled; then wait_for_couchdb fi +if node_service_sidecars_enabled; then + wait_for_dynamodb +fi wait_for_app run_tests "$@" diff --git a/e2e/src/constants.ts b/e2e/src/constants.ts index 65620d1ed9..e1f2ed3f46 100644 --- a/e2e/src/constants.ts +++ b/e2e/src/constants.ts @@ -222,7 +222,8 @@ export const TAGS = { /** * The node-service data source tests that need a real server of their own to be pointed at: the echo cannot serve the plugin's protocol (the Firebird tests, a * wire protocol, `tests/datasource/plugin-firebird.spec.ts`) or its canned answers say nothing about the real server's behaviour (the libSQL server tests, - * `tests/datasource/plugin-turso-libsql.spec.ts`, and the CouchDB server tests, `tests/datasource/plugin-couchdb.spec.ts`). Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of + * `tests/datasource/plugin-turso-libsql.spec.ts`, the CouchDB server tests, `tests/datasource/plugin-couchdb.spec.ts`, and the DynamoDB Local server tests, + * `tests/datasource/plugin-dynamodb-local.spec.ts`). Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of * the default run (neither listed nor run, and the run script starts no such sidecar), in only with * `E2E_INCLUDE_NODE_SERVICE_SIDECARS` (see src/run-selection.ts and scripts/run-in-docker.sh). */ @@ -237,7 +238,7 @@ export const RUN_FLAGS = { /** Enterprise profile only: run SEC-E05 (`@enterprise-takeover`) and nothing else. */ INCLUDE_ENTERPRISE_TAKEOVER: "E2E_INCLUDE_ENTERPRISE_TAKEOVER", /** - * Default stack only: also start the sidecars of the node-service data sources (Firebird, a libSQL server, a CouchDB server) and run + * Default stack only: also start the sidecars of the node-service data sources (Firebird, a libSQL server, a CouchDB server, a DynamoDB Local server) and run * their `@node-service-sidecar` tests. Without it the run starts none of them. */ INCLUDE_NODE_SERVICE_SIDECARS: "E2E_INCLUDE_NODE_SERVICE_SIDECARS", @@ -342,6 +343,20 @@ export const COUCHDB = { SYSTEM_DATABASES: ["_users", "_replicator", "_global_changes"], } as const; +/** + * The DynamoDB Local sidecar that scripts/run-in-docker.sh starts on the run's network ONLY when `E2E_INCLUDE_NODE_SERVICE_SIDECARS` is set. The run script + * passes the host name (the sidecar's network alias); the rest is fixed there and must equal the `DYNAMODB_*` values of the script. DynamoDB Local checks no + * credential: any access key is accepted and, started with `-sharedDb`, every key sees the same tables. `ACCESS_KEY` and `SECRET_KEY` are throw-away values + * (the container is removed when the run ends and holds no other data), never real secrets. + */ +export const DYNAMODB = { + HOST_ENV: "E2E_DYNAMODB_HOST", + PORT: 8000, + ACCESS_KEY: "e2eDynamoKey", + SECRET_KEY: "e2e-dynamodb-secret", + REGION: "us-west-1", +} as const; + export const SEEDED_ITEM_NAMES = ["alpha", "beta"] as const; /** Component type, panel search text, drop position and generated name of the button the editor tests drop. */ diff --git a/e2e/src/datasource/dynamodb.ts b/e2e/src/datasource/dynamodb.ts new file mode 100644 index 0000000000..23f66041d7 --- /dev/null +++ b/e2e/src/datasource/dynamodb.ts @@ -0,0 +1,79 @@ +import { DYNAMODB, RUN_FLAGS } from "../constants"; + +/** Where a DynamoDB data source connects: the DynamoDB Local sidecar of the run, as the app container reaches it (by the sidecar's network alias, over plain HTTP). */ +export interface DynamodbConnection { + /** `http://:`, no trailing slash: the data source's endpoint URL. */ + endpointUrl: string; + /** Any access key is accepted by the sidecar; this is the throw-away one of the suite. */ + accessKey: string; + secretKey: string; + region: string; +} + +/** The sidecar's host variable is not set: the run did not start the DynamoDB Local sidecar. */ +export class DynamodbSidecarMissingError extends Error { + constructor() { + super( + `${DYNAMODB.HOST_ENV} is not set: the DynamoDB Local sidecar was not started. Run the suite through e2e/scripts/run-in-docker.sh with ${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}=1.`, + ); + this.name = "DynamodbSidecarMissingError"; + } +} + +/** + * The connection to the run's DynamoDB Local sidecar from the environment. Throws `DynamodbSidecarMissingError` when the run script did not set the + * host variable (it does so only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`), so a test that was selected without its sidecar fails loudly + * instead of passing vacuously or connecting to a name that happens to resolve elsewhere. Reads only `env`. + */ +export function dynamodbConnection(env: NodeJS.ProcessEnv = process.env): DynamodbConnection { + const host = env[DYNAMODB.HOST_ENV]; + if (!host) throw new DynamodbSidecarMissingError(); + return { endpointUrl: `http://${host}:${DYNAMODB.PORT}`, accessKey: DYNAMODB.ACCESS_KEY, secretKey: DYNAMODB.SECRET_KEY, region: DYNAMODB.REGION }; +} + +/** How long a direct call to the sidecar may take before it is abandoned: a local server answers in milliseconds. */ +const DIRECT_CALL_TIMEOUT_MS = 10_000; + +/** The content type and target prefix of the DynamoDB JSON protocol (version 1.0). */ +export const DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0"; +export const DYNAMODB_TARGET_PREFIX = "DynamoDB_20120810."; + +/** + * The `Authorization` header of a direct call. DynamoDB Local requires a header with a `Credential=` scope but does not verify the signature + * (measured: a signature of zeros is accepted), so no SigV4 computation is needed; against a real AWS endpoint this header would be refused. + */ +const DIRECT_SIGNATURE = "0".repeat(64); +const DIRECT_DATE = "20260101"; + +/** The answer of a direct call: the HTTP status and the body parsed as JSON (or the text when it is not JSON). */ +export interface DynamodbDirectAnswer { + status: number; + body: unknown; +} + +/** + * One call of the DynamoDB JSON protocol from the TEST process to the sidecar: `operation` is the API operation (`PutItem`, `GetItem`, ...) and + * `input` its request body in the API's own TYPED form (`{ "id": { "N": "1" } }`, no wrapping by the plugin). It is the control that shows + * what the server itself holds and answers, next to what the plugin makes of it for the app, and the way a test makes and removes its own + * tables. The runner reaches the sidecar by the same alias the app container does. + */ +export async function dynamodbDirect(connection: Pick, operation: string, input: unknown): Promise { + const response = await fetch(`${connection.endpointUrl}/`, { + method: "POST", + headers: { + "Content-Type": DYNAMODB_CONTENT_TYPE, + "X-Amz-Target": `${DYNAMODB_TARGET_PREFIX}${operation}`, + Authorization: `AWS4-HMAC-SHA256 Credential=${connection.accessKey}/${DIRECT_DATE}/${connection.region}/dynamodb/aws4_request, SignedHeaders=host, Signature=${DIRECT_SIGNATURE}`, + }, + body: JSON.stringify(input), + signal: AbortSignal.timeout(DIRECT_CALL_TIMEOUT_MS), + }); + const text = await response.text(); + let body: unknown = text; + try { + body = JSON.parse(text); + } catch { + // not JSON: the text itself is the body + } + return { status: response.status, body }; +} diff --git a/e2e/src/run-selection.ts b/e2e/src/run-selection.ts index 7ce044cc6b..6f6a2a0804 100644 --- a/e2e/src/run-selection.ts +++ b/e2e/src/run-selection.ts @@ -9,7 +9,7 @@ export interface RunFlags { /** Tests tagged `@superadmin` (SEC-R16a to SEC-R16d: they break a stack that holds more than ~420 workspaces, D-47). */ includeSuperAdmin: boolean; /** - * Tests tagged `@node-service-sidecar` (the node-service data sources that need a real server of their own: Firebird, libSQL, CouchDB): they need the + * Tests tagged `@node-service-sidecar` (the node-service data sources that need a real server of their own: Firebird, libSQL, CouchDB, DynamoDB Local): they need the * run script to start that sidecar, which it does only for this flag. Default stack only: the other stacks select their own tags. */ includeNodeServiceSidecars: boolean; diff --git a/e2e/tests/datasource/plugin-dynamodb-local.spec.ts b/e2e/tests/datasource/plugin-dynamodb-local.spec.ts new file mode 100644 index 0000000000..1afef294ab --- /dev/null +++ b/e2e/tests/datasource/plugin-dynamodb-local.spec.ts @@ -0,0 +1,737 @@ +import { randomBytes } from "node:crypto"; +import { connect } from "node:net"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, DYNAMODB, TAGS } from "../../src/constants"; +import { appDsl, button, nodePluginQuery, stackItems } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { boundText, boundTextTestId, openSeededView } from "../../src/components/scenario"; +import { dynamodbConnection, dynamodbDirect, type DynamodbConnection } from "../../src/datasource/dynamodb"; +import { expect, test } from "../../src/fixtures"; + +/** + * D15: the DynamoDB plugin of node-service (`server/node-service/src/plugins/dynamodb/`, the plugin id `dynamodb`, AWS SDK for JavaScript v3) run + * against a REAL DynamoDB Local server, the sidecar of the run (`scripts/run-in-docker.sh` starts it only with + * `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`; image, flags and setup in the README, "DynamoDB Local sidecar"). D10a to D10f run the same plugin against the + * echo's canned answers; here the answers are the server's own. Every connection of these tests goes to the sidecar: the data source's endpoint is + * `http://:8000` from `E2E_DYNAMODB_HOST`, never a placeholder. The server runs with `-inMemory -sharedDb`: table names are global to the + * sidecar, so each test makes its own tables under a per-test marker, removes them in a `finally`, and shares no state with another test. + * + * "Direct" calls (`dynamodbDirect`) go from the test process to the sidecar in the API's own TYPED form. They are the controls that show what the + * server itself holds (`{ "N": "1" }` where the plugin shows `1`), next to what the plugin makes of it for the app, and the way a test sets up + * and removes what it needs. + * + * Measured on the images `3.0.0-e2e` and `3.0.1-e2e` against DynamoDB Local 3.3.2 (AWS SDK 3.668.0 in the plugin): + * - The form offers CreateTable, ListTables, Query, Scan, PutItem, GetItem, UpdateItem and DeleteItem (no DescribeTable and no DeleteTable): a table + * is described and removed by direct calls here. Every answer is the SDK's output without `$metadata`, as the query's data (`success: true`, `queryCode: "OK"`). + * - The plugin wraps `Key`, `Item` or `Items` of the parameters with `dynamodb-data-types` (plain JSON values become typed attributes) and unwraps `Item` + * and `Items` of the answer. Nothing else is wrapped or unwrapped: `ExpressionAttributeValues` and `ExclusiveStartKey` are sent as given (typed), and + * `LastEvaluatedKey` and `Attributes` (a `ReturnValues` answer) come back typed. + * - Type mapping, plain JSON to the server: string S, number N, boolean BOOL, null NULL, object M, an array of numbers NS, an array of strings SS, any + * other array L (an array of strings is never a list: order is lost, duplicates and an empty array are refused). Back: N is a JavaScript number (digits + * beyond a double are lost), sets are arrays, B is a byte array that the answer's JSON turns into an object with index keys. + * - A service error fails the query with the service's own message (`ResourceNotFoundException`, `ConditionalCheckFailedException`, `ValidationException`, + * `ResourceInUseException`: `success: false`, `queryCode: "FAILED"`, the message, no data). + * - DynamoDB Local checks no credential: any access key is accepted, and with `-sharedDb` every key sees the same tables. + * + * Not covered: a real DynamoDB service (no vendor host is reachable; DynamoDB Local differs from it in limits, capacity, throttling and consistency), + * indexes, transactions, batch operations, streams, TTL, and the signature (the server does not verify it; D10a to D10f assert the signed request). + */ +/** Candidate defect: the answer of `ReturnValues` (`Attributes`) and `LastEvaluatedKey` stay in the typed form while `Item` and `Items` are unwrapped. */ +const TYPED_ANSWER_DEFECT = { type: "defect", description: "NSD-17 candidate" } as const; +/** Candidate defect: an array of strings or numbers is always written as a set (SS or NS): never a list, duplicates and an empty array are refused. */ +const ARRAY_SETS_DEFECT = { type: "defect", description: "NSD-18 candidate" } as const; +/** Candidate defect: a binary attribute is read as a byte array, which the answer's JSON turns into an object with index keys; a number beyond a double loses digits. */ +const VALUE_FIDELITY_DEFECT = { type: "defect", description: "NSD-19 candidate" } as const; +/** Candidate defect: an `ExclusiveStartKey` in the plain form (as `Key` is written) fails with a JavaScript `TypeError` of the SDK instead of a validation message. */ +const PLAIN_START_KEY_DEFECT = { type: "defect", description: "NSD-20 candidate" } as const; + +const HTTP_OK = 200; +const HTTP_BAD_REQUEST = 400; +const QUERY_CODE_OK = "OK"; +const QUERY_CODE_FAILED = "FAILED"; +const MARKER_BYTES = 4; +const QUERY_ID = "q1"; +const QUERY_NAME = "q"; + +/** The recorded variants of the actions (`recordedPluginQuery("dynamodb", variant)`; `""` is the editor's default action, Query). */ +const VARIANT = { + QUERY: "", + SCAN: "Scan", + PUT_ITEM: "PutItem", + GET_ITEM: "GetItem", + UPDATE_ITEM: "UpdateItem", + DELETE_ITEM: "DeleteItem", + LIST_TABLES: "ListTables", + CREATE_TABLE: "CreateTable", +} as const; + +/** The server's own error types (`__type` of the answer, after the `#`), DynamoDB Local 3.3.2, and the message the plugin reports for each. */ +const SERVER_ERRORS = { + TABLE_MISSING: { type: "ResourceNotFoundException", message: "Cannot do operations on a non-existent table" }, + CONDITION_FAILED: { type: "ConditionalCheckFailedException", message: "The conditional request failed" }, + TABLE_EXISTS: { type: "ResourceInUseException", message: "Cannot create preexisting table" }, + KEY_MISSING: { type: "ValidationException", message: "One of the required keys was not given a value" }, + KEY_TYPE: { type: "ValidationException", message: "One or more parameter values were invalid: Type mismatch for key" }, + EMPTY_NUMBER_SET: { type: "ValidationException", message: "One or more parameter values were invalid: An number set may not be empty" }, + EMPTY_KEY: { type: "ValidationException", message: "The number of conditions on the keys is invalid" }, + NO_KEY_CONDITION: { type: "ValidationException", message: "Either the KeyConditions or KeyConditionExpression parameter must be specified in the request." }, + TABLE_NAME: { + type: "ValidationException", + message: "Invalid table/index name. Table/index names must be between 3 and 255 characters long, and may contain only the characters a-z, A-Z, 0-9, '_', '-', and '.'", + }, +} as const; +const DUPLICATE_SET_MESSAGE = "One or more parameter values were invalid: Input collection [a, a] contains duplicates"; +/** The SDK's own text for an `ExclusiveStartKey` it cannot serialise (measured). */ +const PLAIN_START_KEY_MESSAGE = "Cannot read properties of undefined (reading '0')"; + +/** The shapes of what the server generates for a table. */ +const TABLE_ARN = /^arn:aws:dynamodb:[a-z0-9-]+:\d{12}:table\/e2e_ddb_[0-9a-f]+/; +const ISO_DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; + +/** The limit of the paged scan of D15c, and the most requests it may take (a loop that never reaches a last page must end). */ +const SCAN_PAGE_SIZE = 2; +const MAX_SCAN_PAGES = 10; + +/** A port of the sidecar's host where nothing listens: the control that a refused connection is seen as one. */ +const CLOSED_PORT = 8001; +const CONNECT_TIMEOUT_MS = 5000; +const REFUSED_MESSAGE = /^connect ECONNREFUSED \d+\.\d+\.\d+\.\d+:8001$/; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +/** A table name of this test only (letters, digits, `_`). */ +function uniqueTable(suffix = ""): string { + return `e2e_ddb_${uniqueMarker()}${suffix}`; +} + +/** One saved query: the recording's variant and the action's fields over the recorded defaults. */ +interface DdbQuery { + variant: string; + action: Record; +} + +/** The form's action fields: the table (for the actions that have the field) and the JSON parameters. */ +const onTable = (variant: string, tableName: string, params: unknown): DdbQuery => ({ variant, action: { tableName, params: JSON.stringify(params) } }); +const withoutTable = (variant: string, params: unknown): DdbQuery => ({ variant, action: { params: JSON.stringify(params) } }); + +/** The key schema and attribute definitions of a table with a number hash key `id`, as the form's CreateTable default has. */ +const HASH_ONLY_SCHEMA = (table: string): Record => ({ + TableName: table, + AttributeDefinitions: [{ AttributeName: "id", AttributeType: "N" }], + KeySchema: [{ AttributeName: "id", KeyType: "HASH" }], + ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 }, + StreamSpecification: { StreamEnabled: false }, +}); +/** A table with a string hash key `pk` and a number range key `sk` (for Query: the items of one partition in key order). */ +const HASH_RANGE_SCHEMA = (table: string): Record => ({ + TableName: table, + AttributeDefinitions: [ + { AttributeName: "pk", AttributeType: "S" }, + { AttributeName: "sk", AttributeType: "N" }, + ], + KeySchema: [ + { AttributeName: "pk", KeyType: "HASH" }, + { AttributeName: "sk", KeyType: "RANGE" }, + ], + ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 }, +}); + +/** The credentials a data source holds when they are not the suite's. */ +interface Credentials { + accessKey?: string; + secretKey?: string; + endpointUrl?: string; +} + +/** The data source fields of the sidecar over the recorded form body. */ +function sidecarConfig(overrides: Credentials = {}): Record { + const sidecar = dynamodbConnection(); + return { + accessKey: overrides.accessKey ?? sidecar.accessKey, + secretKey: overrides.secretKey ?? sidecar.secretKey, + endpointUrl: overrides.endpointUrl ?? sidecar.endpointUrl, + region: sidecar.region, + }; +} + +async function ddbDatasource(page: Page, apiUser: RegisteredUser, overrides: Credentials = {}): Promise { + return createNodePluginDatasource(page.request, { orgId: apiUser.orgId, recorded: recordedPluginDatasource("dynamodb"), config: sidecarConfig(overrides) }); +} + +function savedQueries(datasourceId: string, queries: Record): ReturnType[] { + return Object.entries(queries).map(([id, query]) => nodePluginQuery({ id, name: id, datasourceId, recorded: recordedPluginQuery("dynamodb", query.variant), action: query.action })); +} + +/** A saved app with one manual DynamoDB query per entry of `queries` on one data source (not published: the draft runs with `viewMode: false`). */ +async function ddbApp(page: Page, apiUser: RegisteredUser, queries: Record, overrides: Credentials = {}): Promise { + const datasourceId = await ddbDatasource(page, apiUser, overrides); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: "e2e-dynamodb-local", dsl: appDsl([], { queries: savedQueries(datasourceId, queries) }) }); + return appId; +} + +async function runDraft(page: Page, appId: string, queryId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +function expectSucceeded(answer: RawAnswer): void { + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); +} + +function expectFailed(answer: RawAnswer, message: string): void { + expectRan(answer); + expect( + { success: envelopeOf(answer).success, queryCode: envelopeOf(answer).queryCode, message: envelopeOf(answer).message, data: envelopeOf(answer).data }, + "the query failed with the measured message", + ).toEqual({ success: false, queryCode: QUERY_CODE_FAILED, message, data: null }); +} + +/** Runs a query whose answer the test asserts as data: the success state first, then the data. */ +async function runForData(page: Page, appId: string, queryId: string): Promise { + const answer = await runDraft(page, appId, queryId); + expectSucceeded(answer); + return envelopeOf(answer).data; +} + +/** The sidecar's answer to a direct call: the status and the body. */ +async function direct(operation: string, input: unknown): Promise<{ status: number; body: unknown }> { + return dynamodbDirect(dynamodbConnection(), operation, input); +} + +/** The server's own error: the HTTP status, the type after the `#` of `__type` and the message. */ +async function directError(operation: string, input: unknown): Promise<{ status: number; type: string; message: string }> { + const answer = await direct(operation, input); + const body = answer.body as { __type?: string; message?: string; Message?: string }; + return { status: answer.status, type: String(body.__type).split("#")[1] ?? "", message: body.message ?? body.Message ?? "" }; +} + +/** Makes a table straight on the sidecar and waits until the server says it is active. */ +async function createDirect(schema: Record): Promise { + const answer = await direct("CreateTable", schema); + expect(answer.status, `the server created ${String(schema.TableName)}`).toBe(HTTP_OK); + expect((answer.body as { TableDescription: { TableStatus: string } }).TableDescription.TableStatus, "the table is active").toBe("ACTIVE"); +} + +/** Removes a test's table whatever state the test ended in (400 `ResourceNotFoundException` when it is already gone is fine). */ +async function removeDirect(table: string): Promise { + const answer = await direct("DeleteTable", { TableName: table }); + expect([HTTP_OK, HTTP_BAD_REQUEST], `removing ${table}`).toContain(answer.status); +} + +/** The item the server holds, in its own typed form (`undefined` when there is none). */ +async function directItem(table: string, key: Record): Promise { + const answer = await direct("GetItem", { TableName: table, Key: key, ConsistentRead: true }); + expect(answer.status, `the server answered the read of ${table}`).toBe(HTTP_OK); + return (answer.body as { Item?: unknown }).Item; +} + +/** How a TCP connection to `host:port` ended: `connected`, or the error code Node reports (`ECONNREFUSED`, ...). */ +async function tcpOutcome(host: string, port: number): Promise { + return new Promise((resolve) => { + const socket = connect({ host, port }); + socket.setTimeout(CONNECT_TIMEOUT_MS, () => { + socket.destroy(); + resolve("timeout"); + }); + socket.once("connect", () => { + socket.destroy(); + resolve("connected"); + }); + socket.once("error", (error: NodeJS.ErrnoException) => resolve(error.code ?? error.message)); + }); +} + +/** An item of every attribute type the plugin can write from plain JSON (the numbers and strings are NOT arrays). */ +const ALL_TYPES_ITEM = { + id: 1, + text: "Alice", + emptyText: "", + integer: 42, + negative: -7, + fraction: 3.5, + yes: true, + no: false, + nothing: null, + object: { a: 1, nested: { b: "two" } }, + numberSet: [2, 1.5], + stringSet: ["b", "a"], + mixedList: [1, "a", true], + listOfObjects: [{ x: 1 }, { y: "z" }], +} as const; + +/** The same item as the server holds it (DynamoDB's typed form). `numberSet` and `stringSet` are sets, which the server sorts. */ +const ALL_TYPES_TYPED = { + id: { N: "1" }, + text: { S: "Alice" }, + emptyText: { S: "" }, + integer: { N: "42" }, + negative: { N: "-7" }, + fraction: { N: "3.5" }, + yes: { BOOL: true }, + no: { BOOL: false }, + nothing: { NULL: true }, + object: { M: { a: { N: "1" }, nested: { M: { b: { S: "two" } } } } }, + numberSet: { NS: ["1.5", "2"] }, + stringSet: { SS: ["a", "b"] }, + mixedList: { L: [{ N: "1" }, { S: "a" }, { BOOL: true }] }, + listOfObjects: { L: [{ M: { x: { N: "1" } } }, { M: { y: { S: "z" } } }] }, +} as const; + +/** What the plugin answers for that item: the sets come back as arrays, in the server's order. */ +const ALL_TYPES_PLAIN = { ...ALL_TYPES_ITEM, numberSet: [1.5, 2], stringSet: ["a", "b"] } as const; + +test.describe("DynamoDB data source against a real DynamoDB Local server", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { + test("D15a: a table is created, listed, described and removed, and the server agrees at each step", async ({ page, apiUser }) => { + const table = uniqueTable(); + const second = `${table}_b`; + const third = `${table}_c`; + try { + const appId = await ddbApp(page, apiUser, { + create: withoutTable(VARIANT.CREATE_TABLE, HASH_ONLY_SCHEMA(table)), + createAgain: withoutTable(VARIANT.CREATE_TABLE, HASH_ONLY_SCHEMA(table)), + createSecond: withoutTable(VARIANT.CREATE_TABLE, HASH_RANGE_SCHEMA(second)), + listAll: withoutTable(VARIANT.LIST_TABLES, { Limit: 100 }), + firstOfTwo: withoutTable(VARIANT.LIST_TABLES, { ExclusiveStartTableName: `${table}`, Limit: 1 }), + afterFirst: withoutTable(VARIANT.LIST_TABLES, { ExclusiveStartTableName: table, Limit: 5 }), + }); + + expect((await directError("DescribeTable", { TableName: table })).type, "before the create the server has no such table").toBe(SERVER_ERRORS.TABLE_MISSING.type); + const before = (await runForData(page, appId, "listAll")) as { TableNames: string[] }; + expect(before.TableNames, "before the create the table is not listed").not.toContain(table); + + const created = (await runForData(page, appId, "create")) as { TableDescription: Record }; + expect(created, "the create answers the table's description, without `$metadata`").toEqual({ + TableDescription: { + AttributeDefinitions: [{ AttributeName: "id", AttributeType: "N" }], + CreationDateTime: expect.stringMatching(ISO_DATE), + DeletionProtectionEnabled: false, + ItemCount: 0, + KeySchema: [{ AttributeName: "id", KeyType: "HASH" }], + ProvisionedThroughput: { + LastDecreaseDateTime: expect.stringMatching(ISO_DATE), + LastIncreaseDateTime: expect.stringMatching(ISO_DATE), + NumberOfDecreasesToday: 0, + ReadCapacityUnits: 1, + WriteCapacityUnits: 1, + }, + TableArn: expect.stringMatching(TABLE_ARN), + TableName: table, + TableSizeBytes: 0, + TableStatus: "ACTIVE", + }, + }); + const described = await direct("DescribeTable", { TableName: table }); + expect({ status: described.status, name: (described.body as { Table: { TableName: string; TableStatus: string } }).Table.TableName }, "the server's own view").toEqual({ status: HTTP_OK, name: table }); + const listed = (await runForData(page, appId, "listAll")) as { TableNames: string[] }; + expect(listed.TableNames, "the new table is listed").toContain(table); + expect(listed.TableNames, "in name order").toEqual([...listed.TableNames].sort()); + + // a second create of the same name is the server's refusal, with its message + expectFailed(await runDraft(page, appId, "createAgain"), SERVER_ERRORS.TABLE_EXISTS.message); + expect(await directError("CreateTable", HASH_ONLY_SCHEMA(table)), "the server's own refusal").toEqual({ status: HTTP_BAD_REQUEST, ...SERVER_ERRORS.TABLE_EXISTS }); + + // paging through the names: the name after `table` is the second table of this test (its name sorts right after: the same marker, a longer name) + await runForData(page, appId, "createSecond"); + // a third table, so that a name follows the second whatever other tests have made: the server returns the continuation key only when more names follow + await createDirect(HASH_ONLY_SCHEMA(third)); + expect(await runForData(page, appId, "firstOfTwo"), "a page of one name: the table after the start name, and the key to continue (a name follows)").toEqual({ TableNames: [second], LastEvaluatedTableName: second }); + const after = (await runForData(page, appId, "afterFirst")) as { TableNames: string[]; LastEvaluatedTableName?: string }; + expect(after.TableNames[0], "the page that starts after the first table begins with the second").toBe(second); + expect(after.TableNames, "in name order").toEqual([...after.TableNames].sort()); + expect(after.TableNames.every((name) => name > table), "every name after the start name").toBe(true); + } finally { + await removeDirect(table); + await removeDirect(second); + await removeDirect(third); + } + }); + + test("D15b: an item of every type the plugin writes is stored in the typed form and read back as plain values", async ({ page, apiUser }) => { + const table = uniqueTable(); + try { + await createDirect(HASH_ONLY_SCHEMA(table)); + const appId = await ddbApp(page, apiUser, { + put: onTable(VARIANT.PUT_ITEM, table, { Item: ALL_TYPES_ITEM }), + get: onTable(VARIANT.GET_ITEM, table, { Key: { id: 1 } }), + getMissing: onTable(VARIANT.GET_ITEM, table, { Key: { id: 2 } }), + }); + + expect(await runForData(page, appId, "getMissing"), "before the put there is no item: the answer is an empty object").toEqual({}); + expect(await directItem(table, { id: { N: "1" } }), "the server holds no item before the put").toBeUndefined(); + expect(await runForData(page, appId, "put"), "a put answers an empty object").toEqual({}); + expect(await directItem(table, { id: { N: "1" } }), "the server's own copy: the typed form of every attribute").toEqual(ALL_TYPES_TYPED); + expect(await runForData(page, appId, "get"), "the plugin's read: plain values, the sets as arrays").toEqual({ Item: ALL_TYPES_PLAIN }); + } finally { + await removeDirect(table); + } + }); + + test("D15c: Query and Scan read items, and the plugin unwraps Items but leaves LastEvaluatedKey typed and takes the next page's ExclusiveStartKey typed", async ({ page, apiUser }) => { + const table = uniqueTable(); + const partition = `p-${uniqueMarker()}`; + const rows = [1, 2, 3, 4, 5].map((sk) => ({ pk: partition, sk, label: `row-${sk}` })); + try { + await createDirect(HASH_RANGE_SCHEMA(table)); + for (const row of rows) { + const put = await direct("PutItem", { TableName: table, Item: { pk: { S: row.pk }, sk: { N: String(row.sk) }, label: { S: row.label } } }); + expect(put.status, `the server stored ${row.label}`).toBe(HTTP_OK); + } + const key = (sk: number): Record => ({ pk: { S: partition }, sk: { N: String(sk) } }); + const partitionValues = { ":p": { S: partition } }; + const appId = await ddbApp(page, apiUser, { + all: onTable(VARIANT.QUERY, table, { KeyConditionExpression: "pk = :p", ExpressionAttributeValues: partitionValues }), + range: onTable(VARIANT.QUERY, table, { KeyConditionExpression: "pk = :p AND sk > :m", ExpressionAttributeValues: { ...partitionValues, ":m": { N: "3" } }, ProjectionExpression: "sk" }), + descending: onTable(VARIANT.QUERY, table, { KeyConditionExpression: "pk = :p", ExpressionAttributeValues: partitionValues, ScanIndexForward: false, Limit: 1 }), + pageOne: onTable(VARIANT.QUERY, table, { KeyConditionExpression: "pk = :p", ExpressionAttributeValues: partitionValues, Limit: 2 }), + pageTwo: onTable(VARIANT.QUERY, table, { KeyConditionExpression: "pk = :p", ExpressionAttributeValues: partitionValues, Limit: 2, ExclusiveStartKey: key(2) }), + pageLast: onTable(VARIANT.QUERY, table, { KeyConditionExpression: "pk = :p", ExpressionAttributeValues: partitionValues, Limit: 2, ExclusiveStartKey: key(4) }), + scanFiltered: onTable(VARIANT.SCAN, table, { FilterExpression: "sk >= :m", ExpressionAttributeValues: { ":m": { N: "4" } } }), + scanCount: onTable(VARIANT.SCAN, table, { Select: "COUNT" }), + noCondition: onTable(VARIANT.QUERY, table, {}), + }); + + expect(await runForData(page, appId, "all"), "every item of the partition, unwrapped, with the counts").toEqual({ Count: 5, Items: rows, ScannedCount: 5 }); + expect(await runForData(page, appId, "range"), "a range condition with a projection").toEqual({ Count: 2, Items: [{ sk: 4 }, { sk: 5 }], ScannedCount: 2 }); + expect(await runForData(page, appId, "descending"), "descending order, the first item, and the key to continue (typed)").toEqual({ + Count: 1, + Items: [rows[4]], + LastEvaluatedKey: key(5), + ScannedCount: 1, + }); + expect(await runForData(page, appId, "pageOne"), "the first page: two items and the typed LastEvaluatedKey").toEqual({ Count: 2, Items: [rows[0], rows[1]], LastEvaluatedKey: key(2), ScannedCount: 2 }); + expect(await runForData(page, appId, "pageTwo"), "the typed key of the first page continues after its last item").toEqual({ Count: 2, Items: [rows[2], rows[3]], LastEvaluatedKey: key(4), ScannedCount: 2 }); + expect(await runForData(page, appId, "pageLast"), "the last page has no LastEvaluatedKey").toEqual({ Count: 1, Items: [rows[4]], ScannedCount: 1 }); + const scanned = (await runForData(page, appId, "scanFiltered")) as { Count: number; Items: unknown[]; ScannedCount: number }; + expect(scanned.ScannedCount, "the scan reads every item and filters afterwards").toBe(5); + expect({ count: scanned.Count, items: [...scanned.Items].sort((a, b) => (a as { sk: number }).sk - (b as { sk: number }).sk) }, "the filtered items").toEqual({ count: 2, items: [rows[3], rows[4]] }); + expect(await runForData(page, appId, "scanCount"), "a count-only scan has no Items").toEqual({ Count: 5, ScannedCount: 5 }); + // a scan does not promise an order, nor where the server cuts a page: feed each returned (typed) LastEvaluatedKey into the next request until none is returned + type ScanPage = { Count: number; Items: typeof rows; LastEvaluatedKey?: Record; ScannedCount: number }; + const sentStartKeys: (Record | undefined)[] = []; + const pages: ScanPage[] = []; + for (let request = 0; request < MAX_SCAN_PAGES; request++) { + const startKey = pages[request - 1]?.LastEvaluatedKey; + sentStartKeys.push(startKey); + const pageApp = await ddbApp(page, apiUser, { scan: onTable(VARIANT.SCAN, table, startKey === undefined ? { Limit: SCAN_PAGE_SIZE } : { Limit: SCAN_PAGE_SIZE, ExclusiveStartKey: startKey }) }); + pages.push((await runForData(page, pageApp, "scan")) as ScanPage); + if (pages[request]?.LastEvaluatedKey === undefined) break; + } + const allItems = pages.flatMap((scanned) => scanned.Items); + const bySortKey = (a: { sk: number }, b: { sk: number }): number => a.sk - b.sk; + expect([...allItems].sort(bySortKey), "the pages together hold every item of the test exactly once: none missing, none twice").toEqual(rows); + expect( + pages.every((scanned) => scanned.Items.length <= SCAN_PAGE_SIZE && scanned.Count === scanned.Items.length && scanned.ScannedCount === scanned.Items.length), + "every page holds at most the limit, and its counts are its items", + ).toBe(true); + expect(pages[pages.length - 1]?.LastEvaluatedKey, "the last page has no key").toBeUndefined(); + expect(pages.slice(0, -1).every((scanned) => scanned.LastEvaluatedKey !== undefined), "every page before the last has a typed key").toBe(true); + expect(pages.length, "the five items needed at least three requests at a limit of two: paging really happened").toBeGreaterThanOrEqual(Math.ceil(rows.length / SCAN_PAGE_SIZE)); + expect(sentStartKeys, "the first request had no start key, each later one started from the key the page before returned").toEqual([undefined, ...pages.slice(0, -1).map((scanned) => scanned.LastEvaluatedKey)]); + expectFailed(await runDraft(page, appId, "noCondition"), SERVER_ERRORS.NO_KEY_CONDITION.message); + } finally { + await removeDirect(table); + } + }); + + test("D15d: UpdateItem changes attributes and a conditional update that does not hold changes nothing", { annotation: TYPED_ANSWER_DEFECT }, async ({ page, apiUser }) => { + const table = uniqueTable(); + try { + await createDirect(HASH_ONLY_SCHEMA(table)); + const put = await direct("PutItem", { TableName: table, Item: { id: { N: "1" }, name: { S: "Alice" }, age: { N: "17" } } }); + expect(put.status, "the server stored the item").toBe(HTTP_OK); + const appId = await ddbApp(page, apiUser, { + update: onTable(VARIANT.UPDATE_ITEM, table, { Key: { id: 1 }, UpdateExpression: "set age = :n, tags = :t", ExpressionAttributeValues: { ":n": { N: "18" }, ":t": { SS: ["x", "y"] } } }), + updateNew: onTable(VARIANT.UPDATE_ITEM, table, { Key: { id: 1 }, UpdateExpression: "set age = :n", ExpressionAttributeValues: { ":n": { N: "19" } }, ReturnValues: "ALL_NEW" }), + conditionFails: onTable(VARIANT.UPDATE_ITEM, table, { + Key: { id: 1 }, + UpdateExpression: "set age = :n", + ConditionExpression: "age = :old", + ExpressionAttributeValues: { ":n": { N: "99" }, ":old": { N: "1" } }, + }), + conditionHolds: onTable(VARIANT.UPDATE_ITEM, table, { + Key: { id: 1 }, + UpdateExpression: "set age = :n", + ConditionExpression: "age = :old", + ExpressionAttributeValues: { ":n": { N: "20" }, ":old": { N: "19" } }, + }), + get: onTable(VARIANT.GET_ITEM, table, { Key: { id: 1 } }), + }); + + expect(await runForData(page, appId, "update"), "an update answers an empty object").toEqual({}); + expect(await runForData(page, appId, "get"), "the item as the plugin reads it after the update").toEqual({ Item: { id: 1, name: "Alice", age: 18, tags: ["x", "y"] } }); + expect(await directItem(table, { id: { N: "1" } }), "the server's own copy").toEqual({ id: { N: "1" }, name: { S: "Alice" }, age: { N: "18" }, tags: { SS: ["x", "y"] } }); + // NSD-17 candidate: Attributes of ReturnValues stays typed while Item is unwrapped + expect(await runForData(page, appId, "updateNew"), "ALL_NEW: the attributes are NOT unwrapped").toEqual({ + Attributes: { id: { N: "1" }, name: { S: "Alice" }, age: { N: "19" }, tags: { SS: ["x", "y"] } }, + }); + expectFailed(await runDraft(page, appId, "conditionFails"), SERVER_ERRORS.CONDITION_FAILED.message); + expect((await directItem(table, { id: { N: "1" } }) as { age: unknown }).age, "the failed condition changed nothing").toEqual({ N: "19" }); + expect(await directError("UpdateItem", { TableName: table, Key: { id: { N: "1" } }, UpdateExpression: "set age = :n", ConditionExpression: "age = :old", ExpressionAttributeValues: { ":n": { N: "99" }, ":old": { N: "1" } } }), "the server's own refusal").toEqual({ + status: HTTP_BAD_REQUEST, + ...SERVER_ERRORS.CONDITION_FAILED, + }); + expect(await runForData(page, appId, "conditionHolds"), "positive control: the same query with a condition that holds updates").toEqual({}); + expect((await directItem(table, { id: { N: "1" } }) as { age: unknown }).age, "the update with the true condition was applied").toEqual({ N: "20" }); + } finally { + await removeDirect(table); + } + }); + + test("D15e: DeleteItem removes an item, an absent item is not an error (the server reports the capacity), and a condition that does not hold keeps the item", { annotation: TYPED_ANSWER_DEFECT }, async ({ page, apiUser }) => { + const table = uniqueTable(); + try { + await createDirect(HASH_ONLY_SCHEMA(table)); + for (const id of [1, 2, 3, 4]) { + const put = await direct("PutItem", { TableName: table, Item: { id: { N: String(id) }, name: { S: `item-${id}` } } }); + expect(put.status, `the server stored item ${id}`).toBe(HTTP_OK); + } + const appId = await ddbApp(page, apiUser, { + remove: onTable(VARIANT.DELETE_ITEM, table, { Key: { id: 1 } }), + removeOld: onTable(VARIANT.DELETE_ITEM, table, { Key: { id: 2 }, ReturnValues: "ALL_OLD" }), + removeAbsent: onTable(VARIANT.DELETE_ITEM, table, { Key: { id: 99 } }), + conditionFails: onTable(VARIANT.DELETE_ITEM, table, { Key: { id: 3 }, ConditionExpression: "attribute_not_exists(id)" }), + conditionHolds: onTable(VARIANT.DELETE_ITEM, table, { Key: { id: 4 }, ConditionExpression: "attribute_exists(id)" }), + }); + + expect(await directItem(table, { id: { N: "1" } }), "before the delete the server holds the item").toEqual({ id: { N: "1" }, name: { S: "item-1" } }); + expect(await runForData(page, appId, "remove"), "a delete answers an empty object").toEqual({}); + expect(await directItem(table, { id: { N: "1" } }), "the server no longer holds the item").toBeUndefined(); + // NSD-17 candidate: Attributes of ReturnValues stays typed + expect(await runForData(page, appId, "removeOld"), "ALL_OLD: the deleted item's attributes, NOT unwrapped").toEqual({ Attributes: { id: { N: "2" }, name: { S: "item-2" } } }); + expect(await directItem(table, { id: { N: "2" } }), "the item with ALL_OLD is gone too").toBeUndefined(); + expect(await runForData(page, appId, "removeAbsent"), "an item that was never there: success, and the server reports the capacity it used (the delete of an existing item above reports none)").toEqual({ + ConsumedCapacity: { CapacityUnits: 1, TableName: table }, + }); + expectFailed(await runDraft(page, appId, "conditionFails"), SERVER_ERRORS.CONDITION_FAILED.message); + expect(await directItem(table, { id: { N: "3" } }), "the failed condition kept the item").toEqual({ id: { N: "3" }, name: { S: "item-3" } }); + expect(await directItem(table, { id: { N: "4" } }), "before the conditional delete that holds, the server holds the item").toEqual({ id: { N: "4" }, name: { S: "item-4" } }); + expect(await runForData(page, appId, "conditionHolds"), "positive control: a conditional delete whose condition holds succeeds").toEqual({}); + expect(await directItem(table, { id: { N: "4" } }), "and the item is gone").toBeUndefined(); + } finally { + await removeDirect(table); + } + }); + + test("D15f: a missing table, a failed condition and a validation error fail the query with the server's message, and the same actions succeed on a table that exists", async ({ page, apiUser }) => { + const table = uniqueTable(); + const missing = uniqueTable("_missing"); + try { + await createDirect(HASH_ONLY_SCHEMA(table)); + const appId = await ddbApp(page, apiUser, { + getMissingTable: onTable(VARIANT.GET_ITEM, missing, { Key: { id: 1 } }), + putMissingTable: onTable(VARIANT.PUT_ITEM, missing, { Item: { id: 1 } }), + getOk: onTable(VARIANT.GET_ITEM, table, { Key: { id: 1 } }), + putOk: onTable(VARIANT.PUT_ITEM, table, { Item: { id: 1, name: "Alice" } }), + putIfAbsent: onTable(VARIANT.PUT_ITEM, table, { Item: { id: 1, name: "Bob" }, ConditionExpression: "attribute_not_exists(id)" }), + putIfAbsentNew: onTable(VARIANT.PUT_ITEM, table, { Item: { id: 2, name: "Carol" }, ConditionExpression: "attribute_not_exists(id)" }), + putWithoutKey: onTable(VARIANT.PUT_ITEM, table, { Item: { name: "no key" } }), + putWrongKeyType: onTable(VARIANT.PUT_ITEM, table, { Item: { id: "one" } }), + getEmptyKey: onTable(VARIANT.GET_ITEM, table, { Key: {} }), + getEmptyTableName: onTable(VARIANT.GET_ITEM, "", { Key: { id: 1 } }), + createBadName: withoutTable(VARIANT.CREATE_TABLE, { TableName: "ab" }), + }); + + expect(await directError("GetItem", { TableName: missing, Key: { id: { N: "1" } } }), "the server's own error for a missing table").toEqual({ status: HTTP_BAD_REQUEST, ...SERVER_ERRORS.TABLE_MISSING }); + expectFailed(await runDraft(page, appId, "getMissingTable"), SERVER_ERRORS.TABLE_MISSING.message); + expectFailed(await runDraft(page, appId, "putMissingTable"), SERVER_ERRORS.TABLE_MISSING.message); + expect(await runForData(page, appId, "getOk"), "positive control: the same read of a table that exists is an empty object before the put").toEqual({}); + + expect(await runForData(page, appId, "putOk"), "positive control: a put without a condition succeeds").toEqual({}); + expectFailed(await runDraft(page, appId, "putIfAbsent"), SERVER_ERRORS.CONDITION_FAILED.message); + expect(await directItem(table, { id: { N: "1" } }), "the refused put left the first item").toEqual({ id: { N: "1" }, name: { S: "Alice" } }); + expect(await runForData(page, appId, "putIfAbsentNew"), "positive control: the same conditional put of an id that is absent succeeds").toEqual({}); + expect(await directItem(table, { id: { N: "2" } }), "and the item is stored").toEqual({ id: { N: "2" }, name: { S: "Carol" } }); + + expectFailed(await runDraft(page, appId, "putWithoutKey"), SERVER_ERRORS.KEY_MISSING.message); + expectFailed(await runDraft(page, appId, "putWrongKeyType"), SERVER_ERRORS.KEY_TYPE.message); + expectFailed(await runDraft(page, appId, "getEmptyKey"), SERVER_ERRORS.EMPTY_KEY.message); + expect(await directError("GetItem", { TableName: table, Key: {} }), "the server's own validation error for an empty key").toEqual({ status: HTTP_BAD_REQUEST, ...SERVER_ERRORS.EMPTY_KEY }); + expectFailed(await runDraft(page, appId, "getEmptyTableName"), SERVER_ERRORS.TABLE_NAME.message); + expectFailed(await runDraft(page, appId, "createBadName"), SERVER_ERRORS.TABLE_NAME.message); + } finally { + await removeDirect(table); + } + }); + + test("D15g: an array of strings or numbers is written as a set, never a list: order is lost, duplicates and an empty array are refused", { annotation: ARRAY_SETS_DEFECT }, async ({ page, apiUser }) => { + const table = uniqueTable(); + try { + await createDirect(HASH_ONLY_SCHEMA(table)); + const appId = await ddbApp(page, apiUser, { + putStrings: onTable(VARIANT.PUT_ITEM, table, { Item: { id: 1, names: ["zeta", "alpha", "mid"] } }), + putNumbers: onTable(VARIANT.PUT_ITEM, table, { Item: { id: 2, numbers: [30, 10, 20] } }), + putMixed: onTable(VARIANT.PUT_ITEM, table, { Item: { id: 3, mixed: ["zeta", 1, "alpha"] } }), + putDuplicates: onTable(VARIANT.PUT_ITEM, table, { Item: { id: 4, names: ["a", "a"] } }), + putEmpty: onTable(VARIANT.PUT_ITEM, table, { Item: { id: 5, none: [] } }), + getStrings: onTable(VARIANT.GET_ITEM, table, { Key: { id: 1 } }), + getNumbers: onTable(VARIANT.GET_ITEM, table, { Key: { id: 2 } }), + }); + + expect(await runForData(page, appId, "putStrings")).toEqual({}); + expect(await runForData(page, appId, "putNumbers")).toEqual({}); + expect(await runForData(page, appId, "putMixed"), "positive control: an array of mixed values is a list, in order").toEqual({}); + expect(await directItem(table, { id: { N: "1" } }), "the server holds the strings as a string set").toEqual({ id: { N: "1" }, names: { SS: ["alpha", "mid", "zeta"] } }); + expect(await directItem(table, { id: { N: "2" } }), "the server holds the numbers as a number set").toEqual({ id: { N: "2" }, numbers: { NS: ["10", "20", "30"] } }); + expect(await directItem(table, { id: { N: "3" } }), "positive control: the mixed array is a list").toEqual({ id: { N: "3" }, mixed: { L: [{ S: "zeta" }, { N: "1" }, { S: "alpha" }] } }); + expect(await runForData(page, appId, "getStrings"), "the written order is lost").toEqual({ Item: { id: 1, names: ["alpha", "mid", "zeta"] } }); + expect(await runForData(page, appId, "getNumbers"), "the numbers come back sorted").toEqual({ Item: { id: 2, numbers: [10, 20, 30] } }); + expectFailed(await runDraft(page, appId, "putDuplicates"), DUPLICATE_SET_MESSAGE); + expectFailed(await runDraft(page, appId, "putEmpty"), SERVER_ERRORS.EMPTY_NUMBER_SET.message); + expect(await directItem(table, { id: { N: "4" } }), "the refused puts stored nothing").toBeUndefined(); + expect(await directItem(table, { id: { N: "5" } }), "the refused empty array stored nothing").toBeUndefined(); + } finally { + await removeDirect(table); + } + }); + + test("D15h: a binary attribute is read as an object with index keys, a number beyond a double loses digits, and a typed value in an Item is written as a map", { annotation: VALUE_FIDELITY_DEFECT }, async ({ page, apiUser }) => { + const table = uniqueTable(); + const hello = Buffer.from("hello"); + const bigNumber = "12345678901234567890"; + try { + await createDirect(HASH_ONLY_SCHEMA(table)); + const put = await direct("PutItem", { TableName: table, Item: { id: { N: "1" }, blob: { B: hello.toString("base64") }, blobs: { BS: [hello.toString("base64")] }, big: { N: bigNumber } } }); + expect(put.status, "the server stored the binary and the big number").toBe(HTTP_OK); + const appId = await ddbApp(page, apiUser, { + get: onTable(VARIANT.GET_ITEM, table, { Key: { id: 1 } }), + putTyped: onTable(VARIANT.PUT_ITEM, table, { Item: { id: 2, blob: { B: hello.toString("base64") } } }), + getTyped: onTable(VARIANT.GET_ITEM, table, { Key: { id: 2 } }), + }); + + expect(await directItem(table, { id: { N: "1" } }), "the server's own copy: a binary, a binary set and the exact number").toEqual({ + id: { N: "1" }, + blob: { B: hello.toString("base64") }, + blobs: { BS: [hello.toString("base64")] }, + big: { N: bigNumber }, + }); + const indexed = Object.fromEntries([...hello].map((byte, index) => [String(index), byte])); + expect(await runForData(page, appId, "get"), "the plugin's read: the binary is an object with index keys, the number is a double").toEqual({ + Item: { id: 1, blob: indexed, blobs: [indexed], big: 12345678901234567000 }, + }); + // a typed value inside `Item` is wrapped like any object: the plugin cannot write a binary + expect(await runForData(page, appId, "putTyped")).toEqual({}); + expect(await directItem(table, { id: { N: "2" } }), "the server holds a map whose `B` member is a string").toEqual({ id: { N: "2" }, blob: { M: { B: { S: hello.toString("base64") } } } }); + expect(await runForData(page, appId, "getTyped"), "positive control: a plain map reads back as the object that was written").toEqual({ Item: { id: 2, blob: { B: hello.toString("base64") } } }); + } finally { + await removeDirect(table); + } + }); + + test("D15i: an ExclusiveStartKey in the plain form fails with a TypeError of the SDK, and the typed form of the same key continues the read", { annotation: PLAIN_START_KEY_DEFECT }, async ({ page, apiUser }) => { + const table = uniqueTable(); + try { + await createDirect(HASH_ONLY_SCHEMA(table)); + for (const id of [1, 2, 3]) { + const put = await direct("PutItem", { TableName: table, Item: { id: { N: String(id) } } }); + expect(put.status, `the server stored item ${id}`).toBe(HTTP_OK); + } + const appId = await ddbApp(page, apiUser, { + plain: onTable(VARIANT.SCAN, table, { Limit: 1, ExclusiveStartKey: { id: 1 } }), + typed: onTable(VARIANT.SCAN, table, { Limit: 1, ExclusiveStartKey: { id: { N: "1" } } }), + }); + + expectFailed(await runDraft(page, appId, "plain"), PLAIN_START_KEY_MESSAGE); + const typed = (await runForData(page, appId, "typed")) as { Count: number; Items: { id: number }[]; ScannedCount: number }; + expect({ count: typed.Count, scanned: typed.ScannedCount, items: typed.Items.length }, "positive control: the typed key continues the read").toEqual({ count: 1, scanned: 1, items: 1 }); + } finally { + await removeDirect(table); + } + }); + + test("D15j: any access key reaches the same tables, and a data source on a closed port of the sidecar's host fails with the connection error", async ({ page, apiUser }) => { + const table = uniqueTable(); + const sidecar: DynamodbConnection = dynamodbConnection(); + const otherKey = `other${uniqueMarker()}`; + const closedUrl = `http://${new URL(sidecar.endpointUrl).hostname}:${CLOSED_PORT}`; + try { + await createDirect(HASH_ONLY_SCHEMA(table)); + const queries = { get: onTable(VARIANT.GET_ITEM, table, { Key: { id: 1 } }), put: onTable(VARIANT.PUT_ITEM, table, { Item: { id: 1, owner: otherKey } }) }; + const otherApp = await ddbApp(page, apiUser, queries, { accessKey: otherKey, secretKey: `secret-${otherKey}` }); + const closedApp = await ddbApp(page, apiUser, { get: queries.get }, { endpointUrl: closedUrl }); + const suiteApp = await ddbApp(page, apiUser, { get: queries.get }); + + expect(await runForData(page, otherApp, "put"), "another access key writes to the table the suite's key made").toEqual({}); + expect(await directItem(table, { id: { N: "1" } }), "the server holds the item").toEqual({ id: { N: "1" }, owner: { S: otherKey } }); + expect(await runForData(page, suiteApp, "get"), "the suite's own key reads what the other key wrote (a shared database)").toEqual({ Item: { id: 1, owner: otherKey } }); + expectFailed(await runDraft(page, closedApp, "get"), expect.stringMatching(REFUSED_MESSAGE) as unknown as string); + } finally { + await removeDirect(table); + } + }); + + test("D15k: the published view shows an item of the server after a click", async ({ page, apiUser }) => { + const table = uniqueTable(); + const name = `name-${uniqueMarker()}`; + try { + await createDirect(HASH_ONLY_SCHEMA(table)); + const put = await direct("PutItem", { TableName: table, Item: { id: { N: "1" }, name: { S: name } } }); + expect(put.status, "the server stored the item").toBe(HTTP_OK); + const datasourceId = await ddbDatasource(page, apiUser); + // before the first run `q.data` is not an object + const expression = `{{${QUERY_NAME}.data ? ${QUERY_NAME}.data.Item.name : ""}}`; + const view = await openSeededView( + page, + apiUser.orgId, + "e2e-dynamodb-local-view", + stackItems([ + button({ id: "b1", name: "button1", text: "Run", testId: "e2e-dynamodb-run", onClickQuery: QUERY_NAME }), + boundText({ id: "t1", name: "label", expression }), + // `success` also reads `true` before the first run (measured, D5e), so only the state after the click proves anything + boundText({ id: "t2", name: "succeeded", expression: `{{String(${QUERY_NAME}.success)}}` }), + ]), + { + queries: [ + nodePluginQuery({ + id: QUERY_ID, + name: QUERY_NAME, + datasourceId, + recorded: recordedPluginQuery("dynamodb", VARIANT.GET_ITEM), + action: onTable(VARIANT.GET_ITEM, table, { Key: { id: 1 } }).action, + }), + ], + }, + ); + + await expect(view.byTestId(boundTextTestId("label")), "before the click the text is empty").toHaveText(""); + await view.buttonByTestId("e2e-dynamodb-run").click(); + await expect(view.byTestId(boundTextTestId("succeeded")), "after the click the query succeeded").toHaveText("true"); + await expect(view.byTestId(boundTextTestId("label")), "after the click the text shows the server's item").toHaveText(name); + } finally { + await removeDirect(table); + } + }); + + test("D15l: the runner reaches the sidecar over HTTP and TCP, and a closed port of the same host is refused", async () => { + const sidecar: DynamodbConnection = dynamodbConnection(); + const host = new URL(sidecar.endpointUrl).hostname; + + const listed = await dynamodbDirect(sidecar, "ListTables", {}); + + expect(listed.status, "the server answers a signed ListTables").toBe(HTTP_OK); + expect(Object.keys(listed.body as object), "the answer lists tables").toContain("TableNames"); + const withoutCredentials = await fetch(`${sidecar.endpointUrl}/`, { method: "POST", headers: { "X-Amz-Target": "DynamoDB_20120810.ListTables", "Content-Type": "application/x-amz-json-1.0" }, body: "{}" }); + expect(withoutCredentials.status, "positive control: without a credential scope the server refuses").toBe(HTTP_BAD_REQUEST); + expect(await tcpOutcome(host, DYNAMODB.PORT), "the sidecar's HTTP port").toBe("connected"); + expect(await tcpOutcome(host, CLOSED_PORT), "positive control: a port nothing listens on is refused").toBe("ECONNREFUSED"); + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index 86c4607d07..7426cc19c3 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -5,7 +5,7 @@ import type { AddressInfo } from "node:net"; import { join } from "node:path"; import { expect, test } from "@playwright/test"; import { createNodePluginDatasource, LowcoderApiError, nodePluginDatasourceBody, pluginDynamicConfigRaw, testDatasourceRaw } from "../../src/api/client"; -import { API_OK, API_PATHS, COUCHDB, FIREBIRD, LIBSQL, orgDatasourceTypesPath, RUN_FLAGS, TAGS } from "../../src/constants"; +import { API_OK, API_PATHS, COUCHDB, DYNAMODB, FIREBIRD, LIBSQL, orgDatasourceTypesPath, RUN_FLAGS, TAGS } from "../../src/constants"; import { nodePluginQuery } from "../../src/dsl/builders"; import { parsePluginRecording, @@ -17,6 +17,7 @@ import { type RecordedPluginQuery, } from "../../src/dsl/recorded"; import { couchdbAdmin, couchdbConnection, couchdbDirect, CouchdbSidecarMissingError } from "../../src/datasource/couchdb"; +import { DYNAMODB_CONTENT_TYPE, DYNAMODB_TARGET_PREFIX, dynamodbConnection, dynamodbDirect, DynamodbSidecarMissingError } from "../../src/datasource/dynamodb"; import { FIREBIRD_ITEMS, firebirdConnection, FirebirdSidecarMissingError } from "../../src/datasource/firebird"; import { LIBSQL_PIPELINE_PATH, libsqlConnection, libsqlDirect, LibsqlSidecarMissingError } from "../../src/datasource/libsql"; import { @@ -592,6 +593,8 @@ const FIREBIRD_ALIAS = "e2e-firebird"; const LIBSQL_ALIAS = "e2e-libsql"; /** The alias the run script gives the CouchDB sidecar. */ const COUCHDB_ALIAS = "e2e-couchdb"; +/** The alias the run script gives the DynamoDB Local sidecar. */ +const DYNAMODB_ALIAS = "e2e-dynamodb"; /** The text of `scripts/run-in-docker.sh` and of `fixtures/firebird/init.sql`. */ const RUN_SCRIPT = readFileSync(join(__dirname, "..", "..", "scripts", "run-in-docker.sh"), "utf8"); @@ -835,8 +838,14 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = const curlBody = functionBody("couchdb_curl"); const probeBody = functionBody("couchdb_probe"); expect(curlBody, "couchdb_curl exists and runs curl in the sidecar").toContain('docker exec "$COUCHDB_CONTAINER" curl'); - expect(curlBody, "a connect limit on every CouchDB readiness curl").toContain('--connect-timeout "$PROBE_CONNECT_TIMEOUT"'); - expect(curlBody, "a total limit on every CouchDB readiness curl").toContain('--max-time "$PROBE_REQUEST_TIMEOUT"'); + expect(curlBody, "a connect limit on every CouchDB readiness curl, never longer than the time left of the probe").toContain('--connect-timeout "$connect_limit"'); + expect(curlBody, "a total limit on every CouchDB readiness curl: the time left of the whole probe, not a fresh PROBE_REQUEST_TIMEOUT per request").toContain('--max-time "$remaining"'); + expect(curlBody, "no request gets a fresh per-request budget").not.toContain('--max-time "$PROBE_REQUEST_TIMEOUT"'); + expect(curlBody, "the time left is taken from the probe's deadline and the shell's SECONDS").toContain("local remaining=$((COUCHDB_PROBE_DEADLINE - SECONDS))"); + expect(curlBody, "a request that finds nothing left is not made").toContain('[ "$remaining" -gt 0 ] || return 1'); + expect(probeBody, "the probe sets its own deadline, one PROBE_REQUEST_TIMEOUT from its start, before its first request").toMatch( + /COUCHDB_PROBE_DEADLINE=\$\(\(SECONDS \+ PROBE_REQUEST_TIMEOUT\)\)\n\s+couchdb_curl /, + ); // structurally: the probe reaches curl only through couchdb_curl, which is the one place that carries the limits expect(probeBody.match(/\bcurl\b/g), "the probe names curl nowhere itself").toBeNull(); expect(probeBody.match(/\bcouchdb_curl\b/g), "the probe's requests: _up, one PUT per system database (in a loop), the listing").toHaveLength(3); @@ -967,4 +976,165 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = await new Promise((resolve) => server.close(() => resolve())); } }); + + test("dynamodbConnection reads the host from the environment and builds a plain-HTTP endpoint with the suite's throw-away key", () => { + expect(dynamodbConnection({ [DYNAMODB.HOST_ENV]: DYNAMODB_ALIAS })).toEqual({ + endpointUrl: `http://${DYNAMODB_ALIAS}:${DYNAMODB.PORT}`, + accessKey: DYNAMODB.ACCESS_KEY, + secretKey: DYNAMODB.SECRET_KEY, + region: DYNAMODB.REGION, + }); + }); + + test("dynamodbConnection throws a named error that names the variable and the flag when the host is unset or empty", () => { + for (const env of [{}, { [DYNAMODB.HOST_ENV]: "" }]) { + expect(() => dynamodbConnection(env), `env ${JSON.stringify(env)}`).toThrow(DynamodbSidecarMissingError); + expect(() => dynamodbConnection(env)).toThrow(DYNAMODB.HOST_ENV); + expect(() => dynamodbConnection(env)).toThrow(`${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}=1`); + } + }); + + test("the run script's DynamoDB Local values equal DYNAMODB in the constants, and the server runs in memory", () => { + expect(scriptConstant("DYNAMODB_ALIAS"), "alias").toBe(DYNAMODB_ALIAS); + expect(Number(RUN_SCRIPT.match(/^readonly DYNAMODB_PORT=(\d+)$/m)?.[1]), "port").toBe(DYNAMODB.PORT); + expect(scriptConstant("DEFAULT_DYNAMODB_IMAGE"), "the image is pinned by tag and digest").toMatch(/^amazon\/dynamodb-local:\d+\.\d+\.\d+@sha256:[0-9a-f]{64}$/); + const startBody = /start_dynamodb\(\) \{[\s\S]*?\n\}/.exec(RUN_SCRIPT)?.[0] ?? ""; + expect(startBody, "the server keeps its tables in memory, so no file or volume is written").toContain("-inMemory"); + expect(startBody, "one database for every access key").toContain("-sharedDb"); + }); + + test("the run script starts, waits for and passes the DynamoDB Local sidecar only under the flag, next to the other three", () => { + const lines = RUN_SCRIPT.split("\n"); + for (const fn of ["start_dynamodb", "wait_for_dynamodb"]) { + const calls = lines.map((line, index) => ({ line, index })).filter(({ line }) => line.trim() === fn); + expect(calls, `${fn} is called exactly once`).toHaveLength(1); + const call = calls[0] as { index: number }; + expect(lines[call.index - 1]?.trim(), `${fn} is the first line of an if node_service_sidecars_enabled block`).toBe("if node_service_sidecars_enabled; then"); + expect(lines[call.index + 1]?.trim(), `${fn} is the only line of that block`).toBe("fi"); + } + const startBody = /start_dynamodb\(\) \{[\s\S]*?\n\}/.exec(RUN_SCRIPT)?.[0] ?? ""; + // `+=`, so that the entries set before stay: all four sidecars are passed to the app container and the runner + expect(startBody, "start_dynamodb appends the runner's host variable").toContain(`SIDECAR_RUNNER_ENV+=(-e "${DYNAMODB.HOST_ENV}=`); + expect(startBody, "start_dynamodb appends the --add-host entry").toContain("SIDECAR_ADD_HOST+=(--add-host"); + const codeLines = lines.filter((line) => !line.trim().startsWith("#")).join("\n"); + expect(codeLines.match(new RegExp(DYNAMODB.HOST_ENV, "g")), "the host variable is named once in the script's code, in start_dynamodb").toHaveLength(1); + expect(RUN_SCRIPT, "the cleanup trap removes the container").toMatch(/docker rm -f [^\n]*"\$DYNAMODB_CONTAINER"/); + expect(RUN_SCRIPT, "the readiness step shows the server's log on failure").toMatch(/wait_for_dynamodb\(\) \{[\s\S]*?docker logs --tail "\$LOG_TAIL_LINES" "\$DYNAMODB_CONTAINER"[\s\S]*?\n\}/); + }); + + test("the four sidecar readiness loops measure real elapsed time against STARTUP_TIMEOUT, so the time a probe takes counts (a loop that adds up its sleeps only fails here)", () => { + for (const fn of ["wait_for_firebird", "wait_for_libsql", "wait_for_couchdb", "wait_for_dynamodb"]) { + const body = new RegExp(`${fn}\\(\\) \\{[\\s\\S]*?\\n\\}`).exec(RUN_SCRIPT)?.[0] ?? ""; + expect(body, `${fn} exists`).not.toBe(""); + expect(body, `${fn}: the start is recorded from the shell's SECONDS`).toContain("local waited=0 started=$SECONDS"); + expect(body, `${fn}: after every failed probe the elapsed time is taken from SECONDS and compared with STARTUP_TIMEOUT, before the sleep`).toMatch( + /until [^\n]*; do\n\s+waited=\$\(\(SECONDS - started\)\)\n\s+if \[ "\$waited" -ge "\$STARTUP_TIMEOUT" \]; then\n[\s\S]*?\n\s+fi\n\s+sleep "\$POLL_INTERVAL"\n\s+done\n/, + ); + expect(body, `${fn}: no counter that adds up the sleeps only`).not.toContain("waited + POLL_INTERVAL"); + expect(body, `${fn}: the elapsed time is taken again once the probe succeeded, for the log line`).toMatch(/done\n\s+waited=\$\(\(SECONDS - started\)\)\n\s+log /); + } + const poll = Number(RUN_SCRIPT.match(/^readonly POLL_INTERVAL=(\d+)$/m)?.[1]); + const request = Number(RUN_SCRIPT.match(/^readonly PROBE_REQUEST_TIMEOUT=(\d+)$/m)?.[1]); + expect(poll + request, "the worst overshoot past STARTUP_TIMEOUT (one sleep and one probe) is small against it").toBeLessThanOrEqual(Number(RUN_SCRIPT.match(/^readonly STARTUP_TIMEOUT=(\d+)$/m)?.[1]) / 10); + // the overshoot above holds only if one probe is bounded as a whole: the Firebird, libSQL and DynamoDB probes are one request, the CouchDB probe shares one budget + const functionOf = (name: string): string => new RegExp(`${name}\\(\\) \\{[\\s\\S]*?\\n\\}`).exec(RUN_SCRIPT)?.[0] ?? ""; + for (const fn of ["wait_for_firebird", "wait_for_libsql", "wait_for_dynamodb"]) { + expect(functionOf(fn).match(/docker exec/g), `${fn}: the probe is exactly one docker exec`).toHaveLength(1); + } + expect(functionOf("wait_for_firebird").match(/isql/g), "wait_for_firebird: one isql run, under the container's own timeout").toHaveLength(1); + expect(functionOf("wait_for_firebird"), "the isql run is killed after PROBE_REQUEST_TIMEOUT").toContain('timeout -s KILL "$PROBE_REQUEST_TIMEOUT" /opt/firebird/bin/isql'); + for (const fn of ["wait_for_libsql", "wait_for_dynamodb"]) { + expect(functionOf(fn).match(/fetch\(/g), `${fn}: the probe is exactly one fetch`).toHaveLength(1); + expect(functionOf(fn).match(/AbortSignal\.timeout\(/g), `${fn}: that fetch aborts after the request limit`).toHaveLength(1); + } + const couchdbProbe = functionOf("couchdb_probe"); + expect(couchdbProbe.match(/\bcouchdb_curl\b/g), "couchdb_probe: three call sites (_up, the PUT in a loop, the listing): five requests, which share one budget").toHaveLength(3); + expect(couchdbProbe.match(/COUCHDB_PROBE_DEADLINE=/g), "couchdb_probe sets the probe's deadline exactly once").toHaveLength(1); + expect(functionOf("couchdb_curl"), "every CouchDB request takes its limit from the probe's deadline").toContain('--max-time "$remaining"'); + }); + + test("the DynamoDB Local readiness call has a request limit, accepts exactly one status and needs the answer's table list", () => { + const body = /wait_for_dynamodb\(\) \{[\s\S]*?\n\}/.exec(RUN_SCRIPT)?.[0] ?? ""; + expect(body, "the fetch aborts after the request limit").toContain("AbortSignal.timeout($((PROBE_REQUEST_TIMEOUT * 1000)))"); + expect(body, "a real ListTables call").toContain("DynamoDB_20120810.ListTables"); + expect(body, "ready only on the one accepted status (a named constant), not on any answer").toContain("r.status === $DYNAMODB_HTTP_OK"); + expect(Number(RUN_SCRIPT.match(/^readonly DYNAMODB_HTTP_OK=(\d+)$/m)?.[1]), "the accepted status is 200").toBe(200); + expect(body, "the answer's body is parsed as JSON and its `TableNames` member must be an array (a substring of the text is not enough)").toContain("Array.isArray(JSON.parse(t).TableNames)"); + expect(body, "a body that is not JSON, or any failure, ends the probe non-zero").toContain(".catch(() => process.exit(1))"); + expect(body, "no substring test of the body is left").not.toContain("t.includes("); + expect(body, "the probe runs in the echo container, over the run network").toContain('"$ECHO_CONTAINER" node -e'); + expect(body, "no secret: the probe's key is a fixed throw-away scope").not.toContain("PASSWORD"); + const request = Number(RUN_SCRIPT.match(/^readonly PROBE_REQUEST_TIMEOUT=(\d+)$/m)?.[1]); + const startupTimeout = Number(RUN_SCRIPT.match(/^readonly STARTUP_TIMEOUT=(\d+)$/m)?.[1]); + expect(request, "a positive request limit small against the startup timeout").toBeGreaterThan(0); + expect(request).toBeLessThanOrEqual(startupTimeout / 10); + }); + + test("the DynamoDB recordings are the editor's saved query per action, with no value of the recording session", () => { + const expectations: { variant: string; action: string; keys: string[] }[] = [ + { variant: "", action: "Query", keys: ["tableName", "params"] }, + { variant: "Scan", action: "Scan", keys: ["tableName", "params"] }, + { variant: "PutItem", action: "PutItem", keys: ["tableName", "params"] }, + { variant: "GetItem", action: "GetItem", keys: ["tableName", "params"] }, + { variant: "UpdateItem", action: "UpdateItem", keys: ["tableName", "params"] }, + { variant: "DeleteItem", action: "DeleteItem", keys: ["tableName", "params"] }, + { variant: "ListTables", action: "ListTables", keys: ["params"] }, + { variant: "CreateTable", action: "CreateTable", keys: ["params"] }, + ]; + for (const { variant, action, keys } of expectations) { + const query = recordedPluginQuery("dynamodb", variant); + expect(query.compType, `${variant || "default"}: the query type`).toBe("dynamodb"); + expect(query.comp.actionName, `${variant || "default"}: the recorded action`).toBe(action); + expect(Object.keys(query), `${variant || "default"}: only what the builder keeps`).toEqual(["compType", "comp"]); + expect(Object.keys(query.comp.action), `${variant || "default"}: the form's fields`).toEqual(keys); + expect(JSON.parse(String(query.comp.action.params)), `${variant || "default"}: the editor's default parameters are JSON`).toBeInstanceOf(Object); + if ("tableName" in query.comp.action) expect(query.comp.action.tableName, `${variant || "default"}: the table name is the editor's empty default`).toBe(""); + expect(query.comp.headers, `${variant || "default"}: the editor's empty header row`).toEqual([{ key: "", value: "" }]); + const text = readFileSync(join(RECORDED_PLUGINS_DIR, "dynamodb", `dynamodb${variant}Query.json`), "utf8"); + expect(text, `${variant || "default"}: a 24-hex id`).not.toMatch(/\b[0-9a-f]{24}\b/); + expect(text, `${variant || "default"}: a sidecar address`).not.toContain(DYNAMODB_ALIAS); + expect(text, `${variant || "default"}: an epoch of 10 digits or more`).not.toMatch(/\b\d{10,}\b/); + } + }); + + test("dynamodbDirect posts the operation's typed JSON body with the target header and a credential scope with the key, and parses a JSON or a text answer", async () => { + const received: { method?: string; url?: string; target?: string; contentType?: string; authorization?: string; body: string }[] = []; + const server: Server = createServer((request: IncomingMessage, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + const body = Buffer.concat(chunks).toString("utf8"); + received.push({ + method: request.method, + url: request.url, + target: request.headers["x-amz-target"] as string | undefined, + contentType: request.headers["content-type"], + authorization: request.headers.authorization, + body, + }); + if (request.headers["x-amz-target"] === `${DYNAMODB_TARGET_PREFIX}Broken`) { + response.writeHead(500).end("plain text, not JSON"); + } else { + response.writeHead(400, { "Content-Type": DYNAMODB_CONTENT_TYPE }).end(JSON.stringify({ __type: "e2e#Refused", message: "refused" })); + } + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const endpointUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + const connection = { endpointUrl, accessKey: "e2eKey", region: "eu-test-1" }; + try { + const json = await dynamodbDirect(connection, "GetItem", { TableName: "t", Key: { id: { N: "1" } } }); + const text = await dynamodbDirect(connection, "Broken", {}); + + expect(json, "a JSON answer is parsed, with its status").toEqual({ status: 400, body: { __type: "e2e#Refused", message: "refused" } }); + expect(text, "an answer that is not JSON stays text").toEqual({ status: 500, body: "plain text, not JSON" }); + expect(received.map(({ method, url, target, contentType, body }) => ({ method, url, target, contentType, body })), "method, path, target, type and typed body of the two calls").toEqual([ + { method: "POST", url: "/", target: `${DYNAMODB_TARGET_PREFIX}GetItem`, contentType: DYNAMODB_CONTENT_TYPE, body: JSON.stringify({ TableName: "t", Key: { id: { N: "1" } } }) }, + { method: "POST", url: "/", target: `${DYNAMODB_TARGET_PREFIX}Broken`, contentType: DYNAMODB_CONTENT_TYPE, body: "{}" }, + ]); + expect(received[0]?.authorization, "the credential scope names the key, the region and the service").toMatch(/^AWS4-HMAC-SHA256 Credential=e2eKey\/\d{8}\/eu-test-1\/dynamodb\/aws4_request, SignedHeaders=host, Signature=0{64}$/); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }); }); diff --git a/e2e/tests/foundation/run-selection.spec.ts b/e2e/tests/foundation/run-selection.spec.ts index 35c709dc1c..3b96496cae 100644 --- a/e2e/tests/foundation/run-selection.spec.ts +++ b/e2e/tests/foundation/run-selection.spec.ts @@ -566,8 +566,8 @@ test.describe("run selection: the node-service sidecar tests are opt-in", () => }); }); -/** The names of the helpers whose use makes a spec need a sidecar (Firebird, libSQL, CouchDB), and the tag every test of such a spec must wear. */ -const SIDECAR_HELPERS = ["firebirdConnection", "libsqlConnection", "couchdbConnection"] as const; +/** The names of the helpers whose use makes a spec need a sidecar (Firebird, libSQL, CouchDB, DynamoDB Local), and the tag every test of such a spec must wear. */ +const SIDECAR_HELPERS = ["firebirdConnection", "libsqlConnection", "couchdbConnection", "dynamodbConnection"] as const; const SIDECAR_HELPER = SIDECAR_HELPERS[0]; const SIDECAR_TAG_KEY = "NODE_SERVICE_SIDECAR"; @@ -589,7 +589,7 @@ function detailsTagWithSidecar(details: ts.Expression): boolean { } /** - * The tests of a spec source that does not wear `TAGS.NODE_SERVICE_SIDECAR`, when the source uses a sidecar helper (`firebirdConnection`, `libsqlConnection` or `couchdbConnection`; a spec that needs the + * The tests of a spec source that does not wear `TAGS.NODE_SERVICE_SIDECAR`, when the source uses a sidecar helper (`firebirdConnection`, `libsqlConnection`, `couchdbConnection` or `dynamodbConnection`; a spec that needs the * sidecar: untagged, its tests would run in the default run, where the sidecar is not started). A source that does not use the helper * reports nothing. A tag on an enclosing `test.describe*(title, details, body)` counts for every test inside. Each result is `line `. * Limits: the same as `untaggedSuperAdminTests` (a `test` passed through a parameter is not recognised, a tag through a variable is not followed). @@ -624,7 +624,7 @@ function untaggedSidecarTests(source: string, fileName = "synthetic.spec.ts"): s } test.describe("run selection: every test that needs a sidecar carries the opt-in tag", () => { - test("every spec that uses a sidecar helper tags all its tests with TAGS.NODE_SERVICE_SIDECAR, and the Firebird, libSQL and CouchDB specs do use one", () => { + test("every spec that uses a sidecar helper tags all its tests with TAGS.NODE_SERVICE_SIDECAR, and the Firebird, libSQL, CouchDB and DynamoDB Local specs do use one", () => { const untagged: string[] = []; const users: string[] = []; for (const file of specFilesUnder(join(__dirname, ".."))) { @@ -634,8 +634,9 @@ test.describe("run selection: every test that needs a sidecar carries the opt-in untagged.push(...untaggedSidecarTests(source, file).map((entry) => `${file}: ${entry}`)); } - expect(users.map((file) => file.split("tests/")[1]), "the specs that use the helper (a positive control that the guard looks at the CouchDB, the Firebird and the libSQL spec)").toEqual([ + expect(users.map((file) => file.split("tests/")[1]), "the specs that use the helper (a positive control that the guard looks at the CouchDB, the DynamoDB Local, the Firebird and the libSQL spec)").toEqual([ "datasource/plugin-couchdb.spec.ts", + "datasource/plugin-dynamodb-local.spec.ts", "datasource/plugin-firebird.spec.ts", "datasource/plugin-turso-libsql.spec.ts", ]); @@ -655,5 +656,7 @@ test.describe("run selection: every test that needs a sidecar carries the opt-in expect(untaggedSidecarTests(`const c = libsqlConnection();\ntest.describe("g", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { test("a", async () => {}); });`), "and accepts its describe tag").toEqual([]); expect(untaggedSidecarTests(`const c = couchdbConnection();\ntest("a", async () => {});`), "the CouchDB helper is asked too").toEqual(["line 2"]); expect(untaggedSidecarTests(`const c = couchdbConnection();\ntest.describe("g", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { test("a", async () => {}); });`), "and accepts its describe tag").toEqual([]); + expect(untaggedSidecarTests(`const c = dynamodbConnection();\ntest("a", async () => {});`), "the DynamoDB Local helper is asked too").toEqual(["line 2"]); + expect(untaggedSidecarTests(`const c = dynamodbConnection();\ntest.describe("g", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { test("a", async () => {}); });`), "and accepts its describe tag").toEqual([]); }); }); From 721a61f761eca8579282c8aa949daa4f850ca4c3 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Wed, 25 Nov 2026 07:40:21 +0100 Subject: [PATCH 18/20] test: stop the run script leaking anonymous Docker volumes The PostgreSQL sidecar left one anonymous volume behind on every run and the Firebird sidecar, with the opt-in flag, one more, because their images declare a data volume that the script did not mount. Both now get a tmpfs over the declared data directory, as the libSQL and CouchDB sidecars already had. The data is throw-away per run. A structural test needs no Docker: it finds every container the script starts (joining continued lines and detecting the detach flag wherever it sits), checks each against a table of the volumes its image declares, and requires a tmpfs over every declared path, so a new unlisted container or a lost tmpfs fails. The README records the measured before and after volume counts, with a control that shows the method does detect a leak. Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/README.md | 18 ++-- e2e/scripts/run-in-docker.sh | 10 +- e2e/tests/foundation/node-plugins.spec.ts | 107 +++++++++++++++++++++- 3 files changed, 122 insertions(+), 13 deletions(-) diff --git a/e2e/README.md b/e2e/README.md index 123c39e2fc..8d6522b9d7 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -36,11 +36,11 @@ lifecycle (insert, save, publish, load) is covered by S1 when `@insert-all` runs the images) even when `@npm` tests are excluded. There is no offline mode. - **PostgreSQL sidecar:** `postgres:17-alpine` (pinned by digest) with `fixtures/sql/init.sql`: `items` (2 rows), `products` (25 shared read-only rows), `notes` (writes, owner-scoped). Host name in `E2E_POSTGRES_HOST`; connection - constants are `POSTGRES` in `src/constants.ts`. + constants are `POSTGRES` in `src/constants.ts`. The image declares `/var/lib/postgresql/data` a volume (`docker inspect` shows `{"/var/lib/postgresql/data":{}}`), so the script mounts a tmpfs there: the database is in memory (it is thrown away with the run anyway; the init scripts come from the read-only mount at `/docker-entrypoint-initdb.d`, not from that path) and no anonymous volume outlives the run. - **Firebird sidecar (opt-in):** the Firebird plugin of node-service speaks the Firebird wire protocol over TCP, which the HTTP echo cannot stand in for, so its tests (D12, `tests/datasource/plugin-firebird.spec.ts`) run against a real Firebird server. It is OPT-IN: - **Flag and tag:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` (`RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS`) and the tag `@node-service-sidecar` (`TAGS.NODE_SERVICE_SIDECAR`), worn next to `@node-service`. The default selection leaves the tag out (`excludedTags` in `src/run-selection.ts`), exactly like `@superadmin`. - **A default run** (no flag) starts no Firebird container, pulls no Firebird image, passes no `E2E_FIREBIRD_HOST` to the runner, and neither lists nor runs the D12 tests (`--list` shows 0 for `--grep @node-service-sidecar`). **A run with the flag** starts the sidecar after the echo, waits until a SELECT of the seeded table through the image's own `isql` answers over TCP, gives the app container and the runner the entry `--add-host e2e-firebird:` (the same reason as the echo's: the name must not fall back to an outside resolver), passes `E2E_FIREBIRD_HOST=e2e-firebird` to the runner, and removes the container in the cleanup trap however the run ends. The flag is refused on another stack profile (those runs select no sidecar test). A test selected without the sidecar fails with a named error (`firebirdConnection()` throws when the host variable is unset). - - **Image:** `firebirdsql/firebird:3.0.12`, pinned by tag and digest (`sha256:e45c9bc4fdacaaddc1980a05b7bb8b297f09fe019eadefb059006efe4dafe875`; `FIREBIRD_IMAGE` overrides it), data from `fixtures/firebird/init.sql` (`FB_ITEMS`, 3 read-only rows; `FB_NOTES`, writes scoped by owner), throw-away user and password in `FIREBIRD` of `src/constants.ts` and in the script. Why this one, measured with node-firebird 1.1.9 (the version node-service installs) from the runner: 3.0.12, 4.0.5 and 5.0.4 all refuse the attach with the image's defaults (3.0.12 and 5.0.4: "Incompatible wire encryption levels requested on client and server", WireCrypt `Required`; 4.0.5: "Error occurred during login"). 4.0.5 and 5.0.4 attached with `FIREBIRD_CONF_AuthServer=Srp,Legacy_Auth` plus `FIREBIRD_CONF_WireCrypt=Disabled` (one attempt each). 3.0.12 attached with `FIREBIRD_CONF_WireCrypt=Enabled` or `FIREBIRD_USE_LEGACY_AUTH=true`, but with its default Srp login 12 of 100 attaches failed with "Your user name and password are not defined" (node-firebird's client-side Srp; also seen through the app: 4 of 14 queries of one probe), while with `FIREBIRD_USE_LEGACY_AUTH=true` 100 of 100 attached. The sidecar therefore runs 3.0.12 with `FIREBIRD_USE_LEGACY_AUTH=true` (Legacy_Auth first, WireCrypt `Enabled`). Limit of that choice: Legacy_Auth compares only the first eight characters of a password (measured: a wrong password that shares them attached), so the wrong password of D12b differs within them; the sidecar is not evidence about the Srp login of Firebird 3, 4 or 5, which node-firebird 1.1.9 fails at random. + - **Image:** `firebirdsql/firebird:3.0.12`, pinned by tag and digest (`sha256:e45c9bc4fdacaaddc1980a05b7bb8b297f09fe019eadefb059006efe4dafe875`; `FIREBIRD_IMAGE` overrides it), data from `fixtures/firebird/init.sql` (`FB_ITEMS`, 3 read-only rows; `FB_NOTES`, writes scoped by owner), throw-away user and password in `FIREBIRD` of `src/constants.ts` and in the script. The image declares `/var/lib/firebird/data` a volume, so the script mounts a tmpfs there (the database file `e2e.fdb` lives in it, stays writable and is in memory: the D12 insert and error scenarios pass, 110 of 110 in the gate) and no anonymous volume outlives the run. Why this one, measured with node-firebird 1.1.9 (the version node-service installs) from the runner: 3.0.12, 4.0.5 and 5.0.4 all refuse the attach with the image's defaults (3.0.12 and 5.0.4: "Incompatible wire encryption levels requested on client and server", WireCrypt `Required`; 4.0.5: "Error occurred during login"). 4.0.5 and 5.0.4 attached with `FIREBIRD_CONF_AuthServer=Srp,Legacy_Auth` plus `FIREBIRD_CONF_WireCrypt=Disabled` (one attempt each). 3.0.12 attached with `FIREBIRD_CONF_WireCrypt=Enabled` or `FIREBIRD_USE_LEGACY_AUTH=true`, but with its default Srp login 12 of 100 attaches failed with "Your user name and password are not defined" (node-firebird's client-side Srp; also seen through the app: 4 of 14 queries of one probe), while with `FIREBIRD_USE_LEGACY_AUTH=true` 100 of 100 attached. The sidecar therefore runs 3.0.12 with `FIREBIRD_USE_LEGACY_AUTH=true` (Legacy_Auth first, WireCrypt `Enabled`). Limit of that choice: Legacy_Auth compares only the first eight characters of a password (measured: a wrong password that shares them attached), so the wrong password of D12b differs within them; the sidecar is not evidence about the Srp login of Firebird 3, 4 or 5, which node-firebird 1.1.9 fails at random. - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar` (or name the spec file). - **Cost, measured here:** image 156 MB (`docker image inspect`), a cold pull of the pinned digest took 3 s (a fast link and a warm registry mirror: expect more elsewhere), the container accepted the readiness SELECT within about 3 s of starting (the script logged `Firebird sidecar ready after 0s`: the wait ran after the PostgreSQL wait of 2 s), and a gate of 110 tests ran in about 23 s. Runs without the flag pay nothing. - **libSQL sidecar (opt-in):** the Turso plugin of node-service posts Hrana pipelines to `/v2/pipeline` over HTTP, so the echo can stand in for it (D5, canned answers); a real server adds what canned answers cannot: the real column types and cells, real SQL errors, real authentication (D13, `tests/datasource/plugin-turso-libsql.spec.ts`). It is OPT-IN under the same flag and tag as the Firebird sidecar and the sidecars start together: @@ -51,14 +51,14 @@ lifecycle (insert, save, publish, load) is covered by S1 when `@insert-all` runs - **Cost, measured here:** the image is 153 MB (`docker image inspect`, uncompressed) and a cold pull of the pinned digest took 9 s (a fast link: expect more elsewhere); the container started with the Firebird one and answered the readiness call within about a second (the script logged `libSQL sidecar ready after 0s`, the wait running after the PostgreSQL, echo and Firebird waits), so the two sidecars together add no waiting of their own beyond the slower one; a gate of 110 tests (`--repeat-each=10 --workers=4`) ran in about 27 s. Runs without the flag pay nothing. The readiness bound is described under the DynamoDB Local sidecar. - **CouchDB sidecar (opt-in):** the CouchDB plugin of node-service is an OpenAPI wrapper that sends HTTP, so the echo can stand in for it (D8a to D8i, canned answers); a real server adds what canned answers cannot: the server's own status codes and error bodies, stored documents and revisions, key ranges, real authentication and its lockout (D14, `tests/datasource/plugin-couchdb.spec.ts`). It is OPT-IN under the same flag and tag as the other sidecars and all three start together: - **A default run** starts no CouchDB container, pulls no CouchDB image, passes no `E2E_COUCHDB_HOST` to the runner, and neither lists nor runs the D14 tests (`--list --grep @node-service-sidecar` shows 0). Measured: the containers a default run created (`docker events`) were the app, the echo, PostgreSQL and the runner. **A run with the flag** starts the sidecar right after the libSQL one, waits (`STARTUP_TIMEOUT`, 300 s of real elapsed time, polled every 2 s; the whole probe of five requests has one 5 s budget and each request a 2 s connect limit; see "Readiness bound" under the DynamoDB Local sidecar) until the server answers `_up`, creates the system databases (a `PUT` counts only on 201 or 412) and lists them, gives the app container and the runner `--add-host e2e-couchdb:` (appended to the entries of the other sidecars), passes `E2E_COUCHDB_HOST=e2e-couchdb` to the runner, and removes the container in the cleanup trap however the run ends. The data source URL is `http://e2e-couchdb:5984` (`couchdbConnection()` throws a named error when the host variable is unset). Reached from both sides: the plugin's requests come from the app container, and D14i and the direct calls come from the runner. - - **Image:** `couchdb:3.5.1`, Apache CouchDB 3.5.1 (the official image; the plugin bundles the 3.1.1 API document), pinned by tag and digest (`sha256:ccea1e8035bf7afd68336e24056a1ca9c1c46d7abe42da686322c0ac7218e5c2`; `COUCHDB_IMAGE` overrides it). The image declares `/opt/couchdb/data` a volume, so the script mounts a tmpfs there: the data is in memory and this sidecar leaves no anonymous volume (measured: `docker inspect` of the running container shows `Mounts` empty and the tmpfs; a default run left one dangling volume, PostgreSQL's, and a run with the flag two, PostgreSQL's and Firebird's, so the CouchDB sidecar adds none). + - **Image:** `couchdb:3.5.1`, Apache CouchDB 3.5.1 (the official image; the plugin bundles the 3.1.1 API document), pinned by tag and digest (`sha256:ccea1e8035bf7afd68336e24056a1ca9c1c46d7abe42da686322c0ac7218e5c2`; `COUCHDB_IMAGE` overrides it). The image declares `/opt/couchdb/data` a volume, so the script mounts a tmpfs there: the data is in memory and this sidecar leaves no anonymous volume (measured: `docker inspect` of the running container shows `Mounts` empty and the tmpfs; see the dangling-volumes evidence in the counts paragraph below). - **Admin setup:** the image makes one server admin from `COUCHDB_USER` and `COUCHDB_PASSWORD` (`COUCHDB` in `src/constants.ts` and the script: `e2eadmin` and a throw-away password, never a real secret). A fresh single node has no system databases (`_all_dbs` answers `[]`), so the readiness step creates `_users`, `_replicator` and `_global_changes` with `PUT` through the real HTTP API (201, or 412 when they exist) and is ready when `_all_dbs` lists all three; it runs inside the container (the image has curl), is idempotent, and is repeated until it succeeds. The tests make their own databases (`e2e_couch_`) and remove them. - **Lockout (measured, CouchDB 3.5.1):** after five failed logins of a real account the server answers 403 `Account is temporarily locked due to multiple authentication failures` to that account, from that client address, even with the right password (the message says "temporarily"; how long it lasts was not measured). A test that sends a wrong password therefore does it as a second admin it makes for the purpose (D14e, D14j) and never as the sidecar's admin, which every other test uses; failures for a name that does not exist are not counted. A freshly made config admin cannot log in until the server has hashed its password (a moment after the `PUT`), so the helper waits for the hash before the first login. - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-couchdb.spec.ts` (all three sidecars start; `--grep @node-service-sidecar` runs D12 and D13 as well). - **Cost, measured here:** the image is 276 MB (`docker image inspect`, uncompressed); CouchDB answered the readiness probe on its first try, about a second after it started (the script logged `CouchDB sidecar ready after 0s`: the wait runs after the PostgreSQL, echo, Firebird and libSQL waits, and the server's log shows it started in about half a second), so all three sidecars together added no waiting of their own beyond the slowest. A cold pull of the pinned digest took 6.4 s (a fast link: expect more elsewhere). The readiness bound is described under the DynamoDB Local sidecar. A test that fails still ends with every container and the network removed (measured with a deliberately failing test under the flag: seven containers created, none left, no network left). - **DynamoDB Local sidecar (opt-in):** the DynamoDB plugin of node-service uses the AWS SDK v3 with a configurable endpoint, so the echo can stand in for it (D10a to D10f, canned answers and the signed request); a real server adds what canned answers cannot: real tables and items, the typed attribute form on the wire, pagination keys, and the server's own errors (D15, `tests/datasource/plugin-dynamodb-local.spec.ts`). It is OPT-IN under the same flag and tag as the other sidecars and all four start together: - **A default run** starts no DynamoDB Local container, pulls no DynamoDB Local image, passes no `E2E_DYNAMODB_HOST` to the runner, and neither lists nor runs the D15 tests (`--list --grep @node-service-sidecar` shows 0). **A run with the flag** starts the sidecar right after the CouchDB one, waits (`STARTUP_TIMEOUT`, 300 s of real elapsed time, polled every 2 s; every readiness request is aborted after 5 s; see "Readiness bound" below) until one real `ListTables` call, posted from the echo container to `http://e2e-dynamodb:8000/` over the run network, answers exactly 200 with a JSON body whose `TableNames` member is an array, gives the app container and the runner `--add-host e2e-dynamodb:` (appended to the entries of the other sidecars), passes `E2E_DYNAMODB_HOST=e2e-dynamodb` to the runner, and removes the container in the cleanup trap however the run ends. The data source's endpoint is `http://e2e-dynamodb:8000` (`dynamodbConnection()` throws a named error when the host variable is unset). Reached from both sides: the plugin's requests come from the app container, and the direct calls and D15l come from the runner. - - **Image:** `amazon/dynamodb-local:3.3.2` (AWS's own image, DynamoDB Local 3.3.2, Java 17), pinned by tag and digest (`sha256:6ada631ec7aa5fc83446855eb17233e3dad184fec47477e8140c6c569cfe0c86`, the digest of `3.3.2` and `latest` on Docker Hub when it was pulled; `DYNAMODB_IMAGE` overrides it). It runs `-jar DynamoDBLocal.jar -inMemory -sharedDb -port 8000`: every table is in memory (nothing is written to a file) and one database serves every access key, so table names are global to the sidecar and each test names its tables with a per-test marker (`e2e_ddb_`) and removes them in a `finally`. The image declares no volume (`docker image inspect` shows no `Volumes`), so no `--tmpfs` is needed: measured, the running container's `Mounts` is empty and a flagged run left two dangling volumes, PostgreSQL's and Firebird's, the same two the CouchDB sidecar's run left (before and after counts in the Docker evidence of the counts paragraph below). + - **Image:** `amazon/dynamodb-local:3.3.2` (AWS's own image, DynamoDB Local 3.3.2, Java 17), pinned by tag and digest (`sha256:6ada631ec7aa5fc83446855eb17233e3dad184fec47477e8140c6c569cfe0c86`, the digest of `3.3.2` and `latest` on Docker Hub when it was pulled; `DYNAMODB_IMAGE` overrides it). It runs `-jar DynamoDBLocal.jar -inMemory -sharedDb -port 8000`: every table is in memory (nothing is written to a file) and one database serves every access key, so table names are global to the sidecar and each test names its tables with a per-test marker (`e2e_ddb_`) and removes them in a `finally`. The image declares no volume (`docker image inspect` shows no `Volumes`), so no `--tmpfs` is needed: measured, the running container's `Mounts` is empty. - **Credentials:** the server checks none: it wants an `Authorization` header with a `Credential=` scope and accepts any access key and any signature (measured: a signature of zeros is accepted; a request without the header is refused with `MissingAuthenticationToken`). `DYNAMODB` in `src/constants.ts` holds a throw-away key, secret and region, never a real secret; the direct calls of the tests send the same header form with a signature of zeros. - **Readiness bound (the Firebird, libSQL, CouchDB and DynamoDB Local waits):** each loop takes the shell's `SECONDS` at its start and, after every failed probe, compares the elapsed seconds with `STARTUP_TIMEOUT` before it sleeps and probes again, so the time a probe takes counts (an earlier version added up its sleeps only: with probes that take 5 s each it ran several times past the limit). The check comes before the sleep and the next probe, and one probe is bounded as a WHOLE: the Firebird probe is one `isql` run under `timeout -s KILL 5`, the libSQL and DynamoDB probes are one fetch aborted after 5 s, and the CouchDB probe, which makes five requests (`_up`, three `PUT`s, `_all_dbs`), shares one 5 s budget (`couchdb_curl` gives each request the time left of the probe's deadline as its `--max-time`, and a request that finds nothing left is not made). So for each of the four the worst case is `STARTUP_TIMEOUT` + `POLL_INTERVAL` (2 s) + `PROBE_REQUEST_TIMEOUT` (5 s), that is 7 s past the limit, plus up to one second of clock granularity (`SECONDS` counts whole seconds) and the start-up time of the `docker exec` calls, which has no limit of its own; not an unbounded multiple. A foundation test fails for any of the four loops that goes back to the sleep-only counter. The PostgreSQL, echo and app waits were not changed: they still add up their sleeps only and their probes have no time limit. Measured by hand on one machine, no artifacts committed, with temporary copies of the script (`STARTUP_TIMEOUT=6`): the sidecar's probe was made unable to succeed (DynamoDB: another accepted status; libSQL: a token the server refuses; CouchDB: other accepted statuses; Firebird: a table that does not exist) so that it failed fast, and 4 s after the container appeared the server was frozen (`docker pause` for DynamoDB and libSQL, whose probe runs in the echo container; SIGSTOP of the server processes for CouchDB and Firebird, whose probe runs inside the container), so that the probes were accepted by the kernel and never answered and each ended at its 5 s limit. Each run ended with `the sidecar did not become ready within 6s` and no container or network left. Total duration of the script, start of the stack included (about 2 s): with the sleep-only counter 20 s for DynamoDB Local, 19 s for libSQL, 19 s for CouchDB and 19 s for Firebird; with the elapsed-time deadline 12 s for each of the four (the stack takes about 2 s, so the wait ended about 10 s after it began, inside the worst case of 6 + 2 + 5 = 13 s). CouchDB was measured again after its probe got the shared budget, three runs of the same method: 12 s, 13 s and 12 s. A frozen server stalls only the first request of its probe, so this method does not show the budget; the budget was shown with a stub `docker` that answers each of the five requests correctly but takes 3 s for it: the probe of the earlier form took 15 s and succeeded, the probe with the shared budget stopped after 5 s and failed, and a foundation test fails for the earlier form (the structural assertions of the probe's deadline). An earlier measurement of 10 s with a paused DynamoDB container did not exercise a stalled probe: the container was frozen before the server listened, so the connection was refused at once. - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-dynamodb-local.spec.ts` (all four sidecars start; `--grep @node-service-sidecar` runs D12, D13 and D14 as well). @@ -301,11 +301,11 @@ Test titles carry these ids. ## Test catalogue -Counts (re-measured 2026-11-24 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 847-test suite after the DynamoDB Local sidecar scenarios (D15) landed (measured before the readiness loops of the four sidecars got their elapsed-time deadline and before one more unit test and the extra controls of D15c, D15e and D15f were added; it was not repeated after them, only the gates below were), `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (no variable set): 43 failed, 804 passed (6.7 min). It started no Firebird, libSQL, CouchDB or DynamoDB Local container (a separate default run measured with `docker events` created the PostgreSQL, echo, app and runner containers only) and ran no D12 to D15 test (they are not in the listing). The baseline from a clean worktree of the previous commit (840 tests, same command and image): 44 failed, 796 passed. The failing sets are identical except one test (compared by test name): 24 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`; `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag, not analysed one by one). The one difference is `SEC-R09d`, which failed in the baseline and passed in this run (it is intermittent: it passed here and in an earlier full run, and failed in both baselines); the periodic trigger test of `logic/triggers.spec.ts` failed in neither. The eight extra passes are the seven new unit tests of `foundation/node-plugins.spec.ts` and the one more test that passed here instead of failing. No node-service scenario failed. The D12, D13 and D14 evidence is a separate gate each, `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 `: for `tests/datasource/plugin-firebird.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D12 landed), for `tests/datasource/plugin-turso-libsql.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D13 landed), for `tests/datasource/plugin-couchdb.spec.ts` 100 passed on `3.0.0-e2e` and 100 passed on `3.0.1-e2e`, and after the readiness probes got their time limits 110 passed for the Firebird spec and 110 for the libSQL spec on `3.0.0-e2e` (all three sidecars start; the app was ready 15 s after the first container started with the flag against 14 s without it). For `tests/datasource/plugin-dynamodb-local.spec.ts` (D15) 120 passed on `3.0.0-e2e` and 120 passed on `3.0.1-e2e`, run after the last change of the spec (all four sidecars start; `docker events` showed the PostgreSQL, echo, Firebird, libSQL, CouchDB and DynamoDB Local containers created within one second, and the script logged every readiness wait as `ready after 0s`, the last one three seconds after the first container was created; the readiness waits run after the app container is started, so they do not delay it). A flagged run left two dangling volumes (PostgreSQL's and Firebird's) and so did the same run before this sidecar existed, and a default run left one (PostgreSQL's): the DynamoDB Local sidecar adds none (`docker volume ls -f dangling=true | wc -l` before and after: 134 to 136 for a flagged run, 133 to 134 for a default run). With the flag, `--grep @node-service-sidecar` ran all the sidecar tests (D12, D13, D14) in one run when D14 landed: 32 passed; D15 was run through its own gate above, not in that combined run. After the four readiness loops got their elapsed-time deadline, `tests/datasource/plugin-firebird.spec.ts` (11), `plugin-turso-libsql.spec.ts` (11) and `plugin-couchdb.spec.ts` (10) each ran once on `3.0.0-e2e` with the flag and passed, and the D15 gate above was repeated (120 passed on both images). These Docker results were measured by hand on one machine; no result files are committed, so re-run the commands named here to reproduce them.): -default **848 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **862 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **853 in 114**; with both of those **867 in 115**; -with `E2E_INCLUDE_INSERT_ALL=1` **960 in 115**; with all three opt-in variables **979 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **892 in 118** (the 11 D12 tests of the Firebird sidecar, the 11 D13 tests of the libSQL sidecar, the 10 D14 tests of the CouchDB sidecar and the 12 D15 tests of the DynamoDB Local sidecar, which no other variable lists), and **1023 in 120** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: +Counts (re-measured 2026-11-25 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 847-test suite after the DynamoDB Local sidecar scenarios (D15) landed (measured before the readiness loops of the four sidecars got their elapsed-time deadline and before one more unit test and the extra controls of D15c, D15e and D15f were added; it was not repeated after them, only the gates below were), `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (no variable set): 43 failed, 804 passed (6.7 min). It started no Firebird, libSQL, CouchDB or DynamoDB Local container (a separate default run measured with `docker events` created the PostgreSQL, echo, app and runner containers only) and ran no D12 to D15 test (they are not in the listing). The baseline from a clean worktree of the previous commit (840 tests, same command and image): 44 failed, 796 passed. The failing sets are identical except one test (compared by test name): 24 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`; `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag, not analysed one by one). The one difference is `SEC-R09d`, which failed in the baseline and passed in this run (it is intermittent: it passed here and in an earlier full run, and failed in both baselines); the periodic trigger test of `logic/triggers.spec.ts` failed in neither. The eight extra passes are the seven new unit tests of `foundation/node-plugins.spec.ts` and the one more test that passed here instead of failing. No node-service scenario failed. The D12, D13 and D14 evidence is a separate gate each, `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 `: for `tests/datasource/plugin-firebird.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D12 landed), for `tests/datasource/plugin-turso-libsql.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D13 landed), for `tests/datasource/plugin-couchdb.spec.ts` 100 passed on `3.0.0-e2e` and 100 passed on `3.0.1-e2e`, and after the readiness probes got their time limits 110 passed for the Firebird spec and 110 for the libSQL spec on `3.0.0-e2e` (all three sidecars start; the app was ready 15 s after the first container started with the flag against 14 s without it). For `tests/datasource/plugin-dynamodb-local.spec.ts` (D15) 120 passed on `3.0.0-e2e` and 120 passed on `3.0.1-e2e`, run after the last change of the spec (all four sidecars start; `docker events` showed the PostgreSQL, echo, Firebird, libSQL, CouchDB and DynamoDB Local containers created within one second, and the script logged every readiness wait as `ready after 0s`, the last one three seconds after the first container was created; the readiness waits run after the app container is started, so they do not delay it). Dangling volumes, measured by hand on one machine (no artifact is committed): before the PostgreSQL and Firebird sidecars got a tmpfs over their declared data volumes (`/var/lib/postgresql/data`, `/var/lib/firebird/data`), a default run left one anonymous volume (PostgreSQL's) and a flagged run two (PostgreSQL's and Firebird's); the libSQL and CouchDB sidecars already mounted a tmpfs over theirs, and the images of DynamoDB Local, the echo and the app declare none. Method: `docker volume ls -q -f dangling=true` sorted and diffed before and after each run, and `docker events --since --until --filter type=volume --filter event=create` over the run. Results (count before to after, volume-create events, 0 in every row but the control): the default `tests/smoke` run 222 to 222; the flagged single-spec runs of Firebird, libSQL, CouchDB and DynamoDB Local 222 to 222 each; a deliberately failing flagged run (one assertion of the Firebird spec inverted, then restored; the run exited 1) 222 to 222; the five gates (`--repeat-each=10 --workers=4` of the four sidecar specs with the flag, and of `tests/smoke` without it) 223 to 223 each, and the Firebird gate on `lowcoderorg/lowcoder-ce:3.0.1-e2e` 223 to 223; in none of them did the list gain a name. A control, the pinned PostgreSQL image started without the tmpfs and then removed, logged exactly one create event and took the count from 222 to 223 (the new name was in the diff), so the method does see a leak. The count of the machine drifted between sessions (222, then 223) because of unrelated Docker activity, so only before/after pairs taken close together are evidence, not the absolute numbers. The 130 or more dangling volumes of earlier runs were not touched; `docker volume ls -q -f dangling=true` lists them, and it may list other projects' volumes, so delete them only knowing whose they are. With the flag, `--grep @node-service-sidecar` ran all the sidecar tests (D12, D13, D14) in one run when D14 landed: 32 passed; D15 was run through its own gate above, not in that combined run. After the four readiness loops got their elapsed-time deadline, `tests/datasource/plugin-firebird.spec.ts` (11), `plugin-turso-libsql.spec.ts` (11) and `plugin-couchdb.spec.ts` (10) each ran once on `3.0.0-e2e` with the flag and passed, and the D15 gate above was repeated (120 passed on both images). These Docker results were measured by hand on one machine; no result files are committed, so re-run the commands named here to reproduce them.): +default **850 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **864 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **855 in 114**; with both of those **869 in 115**; +with `E2E_INCLUDE_INSERT_ALL=1` **962 in 115**; with all three opt-in variables **981 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **894 in 118** (the 11 D12 tests of the Firebird sidecar, the 11 D13 tests of the libSQL sidecar, the 10 D14 tests of the CouchDB sidecar and the 12 D15 tests of the DynamoDB Local sidecar, which no other variable lists), and **1025 in 120** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 143 in 10 files (the 52 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **187 in 14 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests, the 11 D13 tests, the 10 D14 tests and the 12 D15 tests); `@node-service-sidecar` 0 (**44 in 4 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests, D13a to D13k, the libSQL sidecar tests, D14a to D14j, the CouchDB sidecar tests, and D15a to D15l, the DynamoDB Local sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 145 in 10 files (the 54 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **189 in 14 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests, the 11 D13 tests, the 10 D14 tests and the 12 D15 tests); `@node-service-sidecar` 0 (**44 in 4 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests, D13a to D13k, the libSQL sidecar tests, D14a to D14j, the CouchDB sidecar tests, and D15a to D15l, the DynamoDB Local sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -524,7 +524,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization`, and the Firebird sidecar helpers: `firebirdConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the firebird recordings (form fields with the sidecar's values, one query, no session value), `fixtures/firebird/init.sql` equals `FIREBIRD_ITEMS`, the script's Firebird constants equal `FIREBIRD`, and the run script starts, waits for and passes the sidecar only inside `if node_service_sidecars_enabled`; and the libSQL sidecar helpers: `libsqlConnection` (reads the host variable, builds the plain-HTTP URL, throws a named error when it is unset or empty), the script's libSQL values equal `LIBSQL` (alias, port, public key, token, an image pinned by tag and digest, the tmpfs data directory), the three tokens are JWTs with the claims they are named for and only the two sidecar ones verify under the sidecar's key (the foreign one is well-formed and does not), the script starts and waits for the libSQL sidecar only under the flag and appends its `--add-host` and host variable to the Firebird ones, and `libsqlDirect` against a local server (the pipeline body, the bearer header or none, a JSON or a text body); and the CouchDB sidecar helpers: `couchdbConnection` (reads the host variable, builds the plain-HTTP URL with the admin, throws a named error when it is unset or empty), the script's CouchDB values equal `COUCHDB` (alias, port, admin, the system databases, an image pinned by tag and digest, the tmpfs data directory), the script starts and waits for the CouchDB sidecar only under the flag, appends its `--add-host` and host variable to the others, bounds the wait by `STARTUP_TIMEOUT` and removes the container in the trap, the CouchDB recordings (one per operation: action name, the form's fields in order, every value the editor's empty default, no session value, no sidecar address), and `couchdbDirect` and `couchdbAdmin` against a local server (method, path, JSON body, extra headers, Basic credentials or none, a JSON or a text body), and the readiness steps of the script (every CouchDB readiness curl carries a connect and a total time limit, the system-database PUT counts only on 201 or 412, the libSQL fetch and the Firebird isql are bounded too), and the DynamoDB Local sidecar helpers: `dynamodbConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the script's DynamoDB values equal `DYNAMODB` (alias, port, image pinned by tag and digest, `-inMemory -sharedDb`), the start and wait steps run only under the flag and the host variable is named once, the readiness call has the abort limit, accepts exactly status 200 and needs a `TableNames` member, the eight dynamodb query recordings (one per action, no session value), the readiness loops of all four sidecars (elapsed-time deadline from `SECONDS`, compared with `STARTUP_TIMEOUT` after every failed probe; a loop that adds up its sleeps only fails), the DynamoDB probe parses the body as JSON and needs a `TableNames` array, and `dynamodbDirect` against a local server (method, path, target header, content type, typed body, credential scope, a JSON or a text answer) | @node-service | 52 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization`, and the Firebird sidecar helpers: `firebirdConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the firebird recordings (form fields with the sidecar's values, one query, no session value), `fixtures/firebird/init.sql` equals `FIREBIRD_ITEMS`, the script's Firebird constants equal `FIREBIRD`, and the run script starts, waits for and passes the sidecar only inside `if node_service_sidecars_enabled`; and the libSQL sidecar helpers: `libsqlConnection` (reads the host variable, builds the plain-HTTP URL, throws a named error when it is unset or empty), the script's libSQL values equal `LIBSQL` (alias, port, public key, token, an image pinned by tag and digest, the tmpfs data directory), the three tokens are JWTs with the claims they are named for and only the two sidecar ones verify under the sidecar's key (the foreign one is well-formed and does not), the script starts and waits for the libSQL sidecar only under the flag and appends its `--add-host` and host variable to the Firebird ones, and `libsqlDirect` against a local server (the pipeline body, the bearer header or none, a JSON or a text body); and the CouchDB sidecar helpers: `couchdbConnection` (reads the host variable, builds the plain-HTTP URL with the admin, throws a named error when it is unset or empty), the script's CouchDB values equal `COUCHDB` (alias, port, admin, the system databases, an image pinned by tag and digest, the tmpfs data directory), the script starts and waits for the CouchDB sidecar only under the flag, appends its `--add-host` and host variable to the others, bounds the wait by `STARTUP_TIMEOUT` and removes the container in the trap, the CouchDB recordings (one per operation: action name, the form's fields in order, every value the editor's empty default, no session value, no sidecar address), and `couchdbDirect` and `couchdbAdmin` against a local server (method, path, JSON body, extra headers, Basic credentials or none, a JSON or a text body), and the readiness steps of the script (every CouchDB readiness curl carries a connect and a total time limit, the system-database PUT counts only on 201 or 412, the libSQL fetch and the Firebird isql are bounded too), and the DynamoDB Local sidecar helpers: `dynamodbConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the script's DynamoDB values equal `DYNAMODB` (alias, port, image pinned by tag and digest, `-inMemory -sharedDb`), the start and wait steps run only under the flag and the host variable is named once, the readiness call has the abort limit, accepts exactly status 200 and needs a `TableNames` member, the eight dynamodb query recordings (one per action, no session value), the readiness loops of all four sidecars (elapsed-time deadline from `SECONDS`, compared with `STARTUP_TIMEOUT` after every failed probe; a loop that adds up its sleeps only fails), the DynamoDB probe parses the body as JSON and needs a `TableNames` array, and every `docker run` or `docker create` of the script, found whatever its flag order or line continuation, mounts a tmpfs over each volume its image declares, or is the foreground runner started with `--rm` (the discovery itself is tested on awkward forms; the facts are constants of the test, measured with `docker inspect`; PostgreSQL and Firebird lose their mount: it fails), and `dynamodbDirect` against a local server (method, path, target header, content type, typed body, credential scope, a JSON or a text answer) | @node-service | 54 | | foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources), `@node-service-sidecar` (excluded by default, included by `E2E_INCLUDE_NODE_SERVICE_SIDECARS`, independent of the other flags, never selected on the enterprise and signup-disabled stacks), and the guard that every test of a spec that calls `firebirdConnection`, `libsqlConnection`, `couchdbConnection` or `dynamodbConnection` carries `@node-service-sidecar` (same parsing; synthetic sources; the specs that use a helper are the CouchDB, DynamoDB Local, Firebird and libSQL ones) | none | 32 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | diff --git a/e2e/scripts/run-in-docker.sh b/e2e/scripts/run-in-docker.sh index 276b86f551..1fc99a6b8d 100755 --- a/e2e/scripts/run-in-docker.sh +++ b/e2e/scripts/run-in-docker.sh @@ -121,6 +121,8 @@ readonly POSTGRES_IMAGE="${POSTGRES_IMAGE:-$DEFAULT_POSTGRES_IMAGE}" readonly POSTGRES_DATABASE="shop" readonly POSTGRES_USER="postgres" readonly POSTGRES_PASSWORD="e2e-postgres-password" +# The image's data directory (it declares it a volume), mounted as a tmpfs so that no anonymous volume outlives the run +readonly POSTGRES_DATA_DIR="/var/lib/postgresql/data" # Firebird sidecar of the @node-service-sidecar tests, started only with E2E_INCLUDE_NODE_SERVICE_SIDECARS. Tag and digest of the image: # 3.0.12 with Legacy_Auth first (below): node-firebird 1.1.9 attached 100 of 100 times; with the image's default Srp, 12 of 100 attaches failed # with "Your user name and password are not defined" (README, "Firebird sidecar"). The values below must equal FIREBIRD in e2e/src/constants.ts; @@ -128,7 +130,9 @@ readonly POSTGRES_PASSWORD="e2e-postgres-password" readonly DEFAULT_FIREBIRD_IMAGE="firebirdsql/firebird:3.0.12@sha256:e45c9bc4fdacaaddc1980a05b7bb8b297f09fe019eadefb059006efe4dafe875" readonly FIREBIRD_IMAGE="${FIREBIRD_IMAGE:-$DEFAULT_FIREBIRD_IMAGE}" readonly FIREBIRD_DATABASE_FILE="e2e.fdb" -readonly FIREBIRD_DATABASE_PATH="/var/lib/firebird/data/$FIREBIRD_DATABASE_FILE" +# The image's data directory (it declares it a volume), mounted as a tmpfs so that no anonymous volume outlives the run +readonly FIREBIRD_DATA_DIR="/var/lib/firebird/data" +readonly FIREBIRD_DATABASE_PATH="$FIREBIRD_DATA_DIR/$FIREBIRD_DATABASE_FILE" readonly FIREBIRD_USER="e2euser" readonly FIREBIRD_PASSWORD="e2e-firebird-password" readonly FIREBIRD_ROOT_PASSWORD="e2e-firebird-root-password" @@ -326,7 +330,7 @@ start_postgres() { log "Starting $POSTGRES_IMAGE as $POSTGRES_CONTAINER" docker run -d --name "$POSTGRES_CONTAINER" --network "$NETWORK" \ -e POSTGRES_DB="$POSTGRES_DATABASE" -e POSTGRES_USER="$POSTGRES_USER" -e POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \ - -v "$E2E_DIR/fixtures/sql":/docker-entrypoint-initdb.d:ro \ + --tmpfs "$POSTGRES_DATA_DIR" -v "$E2E_DIR/fixtures/sql":/docker-entrypoint-initdb.d:ro \ "$POSTGRES_IMAGE" > /dev/null } @@ -378,7 +382,7 @@ start_firebird() { docker run -d --name "$FIREBIRD_CONTAINER" --network "$NETWORK" --network-alias "$FIREBIRD_ALIAS" \ -e FIREBIRD_ROOT_PASSWORD="$FIREBIRD_ROOT_PASSWORD" -e FIREBIRD_USER="$FIREBIRD_USER" -e FIREBIRD_PASSWORD="$FIREBIRD_PASSWORD" \ -e FIREBIRD_DATABASE="$FIREBIRD_DATABASE_FILE" -e FIREBIRD_USE_LEGACY_AUTH="$FIREBIRD_USE_LEGACY_AUTH" \ - -v "$E2E_DIR/fixtures/firebird":/docker-entrypoint-initdb.d:ro \ + --tmpfs "$FIREBIRD_DATA_DIR" -v "$E2E_DIR/fixtures/firebird":/docker-entrypoint-initdb.d:ro \ "$FIREBIRD_IMAGE" > /dev/null local firebird_ip firebird_ip="$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$FIREBIRD_CONTAINER")" diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index 7426cc19c3..25ab930226 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -605,6 +605,38 @@ function scriptConstant(name: string): string | undefined { return new RegExp(`^readonly ${name}="([^"]*)"$`, "m").exec(RUN_SCRIPT)?.[1]; } +/** One `docker run` or `docker create` command of a shell script: the function it is in (TOP_LEVEL outside any), its text with continuation lines joined, and how it runs. */ +interface ContainerInvocation { + fn: string; + command: string; + verb: "run" | "create"; + detached: boolean; +} +/** The `fn` of an invocation that is not inside any function. */ +const TOP_LEVEL = ""; + +/** + * Every `docker run` and `docker create` command of a shell script, wherever it is written: backslash-continued lines are joined first, comment lines are + * dropped, and the detach flag counts in any position (`-d`, `--detach`, or inside a cluster such as `-itd`). A function that holds one is a "starter". + * Limit: it reads the script's text, so a command built from a variable (`$DOCKER run`) or a `docker` call through `eval` is not seen. + */ +function containerInvocations(script: string): ContainerInvocation[] { + const joined = script.replace(/\\\n[ \t]*/g, " "); + const found: ContainerInvocation[] = []; + let fn = TOP_LEVEL; + for (const line of joined.split("\n")) { + const opened = /^(\w+)\(\) \{$/.exec(line); + if (opened) fn = opened[1] as string; + else if (line === "}") fn = TOP_LEVEL; + if (line.trim().startsWith("#")) continue; + for (const match of line.matchAll(/\bdocker (run|create)\b(.*)$/g)) { + const detached = /(^| )--detach( |$)/.test(match[2] as string) || /(^| )-[A-Za-z]*d[A-Za-z]*( |$)/.test(match[2] as string); + found.push({ fn, command: match[0], verb: match[1] as "run" | "create", detached }); + } + } + return found; +} + /** The lines of `RUN_SCRIPT` that call `fn` as a command (not its definition, not a comment). */ function callLinesOf(fn: string): string[] { return RUN_SCRIPT.split("\n").filter((line) => line.trim() === fn); @@ -671,7 +703,8 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = expect(scriptConstant("FIREBIRD_PASSWORD"), "password").toBe(FIREBIRD.PASSWORD); expect(scriptConstant("FIREBIRD_ALIAS"), "alias").toBe(FIREBIRD_ALIAS); expect(Number(RUN_SCRIPT.match(/^readonly FIREBIRD_PORT=(\d+)$/m)?.[1]), "port").toBe(FIREBIRD.PORT); - expect(scriptConstant("FIREBIRD_DATABASE_PATH"), "database path is the image's data directory plus the file").toBe("/var/lib/firebird/data/$FIREBIRD_DATABASE_FILE"); + expect(scriptConstant("FIREBIRD_DATABASE_PATH"), "database path is the image's data directory plus the file").toBe("$FIREBIRD_DATA_DIR/$FIREBIRD_DATABASE_FILE"); + expect(scriptConstant("FIREBIRD_DATA_DIR"), "the data directory the database path is built from").toBe("/var/lib/firebird/data"); expect(`/var/lib/firebird/data/${scriptConstant("FIREBIRD_DATABASE_FILE")}`, "database file").toBe(FIREBIRD.DATABASE); expect(scriptConstant("DEFAULT_FIREBIRD_IMAGE"), "the image is pinned by tag and digest").toMatch(/^firebirdsql\/firebird:\d+\.\d+\.\d+@sha256:[0-9a-f]{64}$/); }); @@ -1053,6 +1086,78 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = expect(functionOf("couchdb_curl"), "every CouchDB request takes its limit from the probe's deadline").toContain('--max-time "$remaining"'); }); + test("every container the run script starts with `docker run -d` mounts a tmpfs over each volume its image declares, so the cleanup leaves no anonymous volume behind", () => { + // Measured by hand with `docker inspect --format '{{json .Config.Volumes}}'` on the images the script pins (the default APP_IMAGE, PLAYWRIGHT_IMAGE, + // POSTGRES_IMAGE, FIREBIRD_IMAGE, LIBSQL_IMAGE, COUCHDB_IMAGE and DYNAMODB_IMAGE). An empty list is an image whose answer was `null`: it declares no volume. + // Without a mount over a declared path Docker creates an anonymous volume per container, and the trap's container removal does not remove it. + // The test needs no docker: when an image pin changes, measure again and change the facts below. + // `run_tests` is the one foreground container: the runner (PLAYWRIGHT_IMAGE, no declared volume) runs with `docker run --rm`, which removes the container + // together with any anonymous volume, so it needs no tmpfs; the test requires that `--rm`. + const DECLARED_VOLUMES: Record = { + start_app: { constants: [], paths: [], detached: true }, + start_echo: { constants: [], paths: [], detached: true }, + start_postgres: { constants: ["POSTGRES_DATA_DIR"], paths: ["/var/lib/postgresql/data"], detached: true }, + start_firebird: { constants: ["FIREBIRD_DATA_DIR"], paths: ["/var/lib/firebird/data"], detached: true }, + start_libsql: { constants: ["LIBSQL_DATA_DIR"], paths: ["/var/lib/sqld"], detached: true }, + start_couchdb: { constants: ["COUCHDB_DATA_DIR"], paths: ["/opt/couchdb/data"], detached: true }, + start_dynamodb: { constants: [], paths: [], detached: true }, + run_tests: { constants: [], paths: [], detached: false }, + }; + const invocations = containerInvocations(RUN_SCRIPT); + expect(invocations.filter((invocation) => invocation.fn === TOP_LEVEL), "no container is created outside a function").toEqual([]); + expect( + invocations.map((invocation) => invocation.fn).sort(), + "the facts above cover exactly the functions that run or create a container, one command each (a new sidecar must add its image's volumes)", + ).toEqual(Object.keys(DECLARED_VOLUMES).sort()); + for (const [fn, facts] of Object.entries(DECLARED_VOLUMES)) { + const invocation = invocations.find((candidate) => candidate.fn === fn) as ContainerInvocation; + expect(invocation.verb, `${fn}: a docker run`).toBe("run"); + expect(invocation.detached, `${fn}: detached as the facts say`).toBe(facts.detached); + expect(facts.constants, `${fn}: one constant per declared path`).toHaveLength(facts.paths.length); + facts.constants.forEach((constant, index) => { + expect(scriptConstant(constant), `${constant} holds the path its image declares`).toBe(facts.paths[index]); + expect(invocation.command, `${fn}: a tmpfs over ${facts.paths[index]}`).toContain(`--tmpfs "$${constant}"`); + }); + if (facts.paths.length === 0) { + expect(invocation.command, `${fn}: its image declares no volume, so it mounts no tmpfs`).not.toContain("--tmpfs"); + } + if (!facts.detached) { + expect(invocation.command, `${fn}: a foreground container is removed with its volumes`).toContain(" --rm "); + } + } + }); + + test("the container discovery of the run script finds a docker run or create written in any form (flag position, continuation lines, clusters, create)", () => { + const script = [ + "# docker run in a comment is not a command", + "start_a() {", + " docker run --name x -d image", + "}", + "start_b() {", + " docker run --name x \\", + " -e A=b \\", + " -d \\", + " image", + "}", + "start_c() {", + " docker create --name x image", + "}", + "start_d() {", + " docker run --name x image", + " docker run -itd image", + "}", + "docker run --detach image", + ].join("\n"); + expect(containerInvocations(script).map(({ fn, verb, detached }) => ({ fn, verb, detached }))).toEqual([ + { fn: "start_a", verb: "run", detached: true }, + { fn: "start_b", verb: "run", detached: true }, + { fn: "start_c", verb: "create", detached: false }, + { fn: "start_d", verb: "run", detached: false }, + { fn: "start_d", verb: "run", detached: true }, + { fn: TOP_LEVEL, verb: "run", detached: true }, + ]); + }); + test("the DynamoDB Local readiness call has a request limit, accepts exactly one status and needs the answer's table list", () => { const body = /wait_for_dynamodb\(\) \{[\s\S]*?\n\}/.exec(RUN_SCRIPT)?.[0] ?? ""; expect(body, "the fetch aborts after the request limit").toContain("AbortSignal.timeout($((PROBE_REQUEST_TIMEOUT * 1000)))"); From b285b2c271485c224b94715799f254ba51763a13 Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Wed, 25 Nov 2026 08:32:38 +0100 Subject: [PATCH 19/20] test: add an opt-in S3-compatible server sidecar and S3 scenarios against it Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/AGENTS.md | 20 +- e2e/README.md | 41 +- e2e/scripts/run-in-docker.sh | 73 +- e2e/src/constants.ts | 19 +- e2e/src/datasource/s3.ts | 218 ++++++ e2e/src/run-selection.ts | 2 +- e2e/src/security/echo.ts | 2 +- e2e/tests/datasource/plugin-s3-server.spec.ts | 675 ++++++++++++++++++ e2e/tests/foundation/node-plugins.spec.ts | 254 ++++++- e2e/tests/foundation/run-selection.spec.ts | 13 +- 10 files changed, 1273 insertions(+), 44 deletions(-) create mode 100644 e2e/src/datasource/s3.ts create mode 100644 e2e/tests/datasource/plugin-s3-server.spec.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index 4e4be0766b..ea064607b4 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -129,8 +129,8 @@ Coordinates, DSL item ids, test ids and labels used by one spec only may be loca - `@slow`: the test needs noticeably longer (PostgreSQL, npm, many editor steps). - `@npm`: the test needs the app container to reach the npm registry. - `@quarantine` and `@insert-all`: see section 7 and the README. -- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `tests/datasource/plugin-supabase-storage.spec.ts`, D11; `tests/datasource/plugin-firebird.spec.ts`, D12, `tests/datasource/plugin-turso-libsql.spec.ts`, D13, `tests/datasource/plugin-couchdb.spec.ts`, D14, and `tests/datasource/plugin-dynamodb-local.spec.ts`, D15, which also wear the opt-in tag of the next bullet; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. -- `@node-service-sidecar`: a node-service data source test that needs a real server of its own to be pointed at: either the echo cannot serve the plugin's protocol (Firebird, a wire protocol, `tests/datasource/plugin-firebird.spec.ts`, D12) or the echo's canned answers say nothing about the real server's behaviour (a libSQL server for the Turso plugin, `tests/datasource/plugin-turso-libsql.spec.ts`, D13, a CouchDB server for the CouchDB plugin, `tests/datasource/plugin-couchdb.spec.ts`, D14, and a DynamoDB Local server for the DynamoDB plugin, `tests/datasource/plugin-dynamodb-local.spec.ts`, D15); `TAGS.NODE_SERVICE_SIDECAR`. Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of the default run (neither listed nor run, and `run-in-docker.sh` starts no such container), in only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` (default stack only). A spec that calls `firebirdConnection()`, `libsqlConnection()`, `couchdbConnection()` or `dynamodbConnection()` must tag every test with it (a guard in `foundation/run-selection.spec.ts` parses the spec: write `{ tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }` on the describe or the test, not through a variable). Never put the tag text in a test title: the default `grepInvert` matches titles too and would drop the test. The helper that reads a sidecar's host variable throws when it is unset, so a test selected without its sidecar fails loudly. All four sidecars start together under the one flag; later sidecars add their container under it too. +- `@node-service`: the node-service data source tests (`tests/datasource/node-plugins-catalogue.spec.ts`, D3; `tests/datasource/plugin-duckdb.spec.ts`, D4; `tests/datasource/plugin-turso-slack.spec.ts`, D5; `tests/datasource/plugin-graphql.spec.ts`, D6; `tests/datasource/plugin-openapi.spec.ts`, D7; `tests/datasource/plugin-openapi-wrappers-data.spec.ts`, D8; `tests/datasource/plugin-openapi-wrappers-apps.spec.ts`, D9; `tests/datasource/plugin-aws-sdk.spec.ts`, D10; `tests/datasource/plugin-supabase-storage.spec.ts`, D11; `tests/datasource/plugin-firebird.spec.ts`, D12, `tests/datasource/plugin-turso-libsql.spec.ts`, D13, `tests/datasource/plugin-couchdb.spec.ts`, D14, and `tests/datasource/plugin-dynamodb-local.spec.ts`, D15, and `tests/datasource/plugin-s3-server.spec.ts`, D16, which also wear the opt-in tag of the next bullet; `TAGS.NODE_SERVICE`). A selection tag (`--grep @node-service`), not an opt-in one: the tests stay in the default run, and `excludedTags` does not list it. The stack-free unit spec `tests/foundation/node-plugins.spec.ts` carries it too: the one exception to the next bullet. +- `@node-service-sidecar`: a node-service data source test that needs a real server of its own to be pointed at: either the echo cannot serve the plugin's protocol (Firebird, a wire protocol, `tests/datasource/plugin-firebird.spec.ts`, D12) or the echo's canned answers say nothing about the real server's behaviour (a libSQL server for the Turso plugin, `tests/datasource/plugin-turso-libsql.spec.ts`, D13, a CouchDB server for the CouchDB plugin, `tests/datasource/plugin-couchdb.spec.ts`, D14, a DynamoDB Local server for the DynamoDB plugin, `tests/datasource/plugin-dynamodb-local.spec.ts`, D15, and an S3-compatible server for the S3 plugin, `tests/datasource/plugin-s3-server.spec.ts`, D16); `TAGS.NODE_SERVICE_SIDECAR`. Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of the default run (neither listed nor run, and `run-in-docker.sh` starts no such container), in only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` (default stack only). A spec that calls `firebirdConnection()`, `libsqlConnection()`, `couchdbConnection()`, `dynamodbConnection()` or `s3Connection()` must tag every test with it (a guard in `foundation/run-selection.spec.ts` parses the spec: write `{ tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }` on the describe or the test, not through a variable). Never put the tag text in a test title: the default `grepInvert` matches titles too and would drop the test. The helper that reads a sidecar's host variable throws when it is unset, so a test selected without its sidecar fails loudly. All five sidecars start together under the one flag; later sidecars add their container under it too. - Untagged is normal: component scenarios (S2 to S20), unit, helper and foundation tests carry no tag (exception: `foundation/node-plugins.spec.ts`, `@node-service`). - Always use `TAGS.*`. A test with a tag string in its title only as test data stays untagged (`foundation/run-selection.spec.ts`). @@ -171,9 +171,9 @@ MUST NOT: `test-results`, `playwright-report`), and do not run `playwright test` directly while a stack of this checkout runs. - Edit anything in `e2e/evidence/` (git-ignored, local). Do not cite it as if it were in git. - Reach a real external host, switch the guard off, or add a route that allows another origin. Only `@npm` tests need - the app container to reach the npm registry. The places the backend may be pointed at are the run's own echo sidecar (`echo` fixture, `src/security/echo.ts`) and, only in a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, the opt-in node-service sidecars: the Firebird sidecar (`firebirdConnection()`, `src/datasource/firebird.ts`), the libSQL server sidecar (`libsqlConnection()`, `src/datasource/libsql.ts`), the CouchDB sidecar (`couchdbConnection()`, `src/datasource/couchdb.ts`) and the DynamoDB Local sidecar (`dynamodbConnection()`, `src/datasource/dynamodb.ts`). Later opt-in sidecars add their names to this sentence. Never give a data source or a registry entry any other URL, and never rely on a placeholder host failing to resolve: every connection of a sidecar test goes to the sidecar. + the app container to reach the npm registry. The places the backend may be pointed at are the run's own echo sidecar (`echo` fixture, `src/security/echo.ts`) and, only in a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, the opt-in node-service sidecars: the Firebird sidecar (`firebirdConnection()`, `src/datasource/firebird.ts`), the libSQL server sidecar (`libsqlConnection()`, `src/datasource/libsql.ts`), the CouchDB sidecar (`couchdbConnection()`, `src/datasource/couchdb.ts`) the DynamoDB Local sidecar (`dynamodbConnection()`, `src/datasource/dynamodb.ts`) and the S3-compatible sidecar (`s3Connection()`, `src/datasource/s3.ts`: reached by IP address only, it has no name). Later opt-in sidecars add their names to this sentence. Never give a data source or a registry entry any other URL, and never rely on a placeholder host failing to resolve: every connection of a sidecar test goes to the sidecar. - Import `test` from `@playwright/test` in a spec that opens a page or uses the stack: the network guard exists only in the `test` of `src/fixtures.ts` (accepted exception for stack-free unit specs below). -- Commit secrets. The PostgreSQL password in `src/constants.ts` is the throw-away one of the sidecar. The Firebird password in `src/constants.ts` is likewise the throw-away one of its own sidecar, and so are the libSQL tokens (`LIBSQL`): signed with a key pair generated once, whose private half was thrown away, the CouchDB admin of its sidecar (`COUCHDB`), and the access key of the DynamoDB Local sidecar (`DYNAMODB`: the server checks no credential). +- Commit secrets. The PostgreSQL password in `src/constants.ts` is the throw-away one of the sidecar. The Firebird password in `src/constants.ts` is likewise the throw-away one of its own sidecar, and so are the libSQL tokens (`LIBSQL`): signed with a key pair generated once, whose private half was thrown away, the CouchDB admin of its sidecar (`COUCHDB`), the access key of the DynamoDB Local sidecar (`DYNAMODB`: the server checks no credential), and the root key pair of the S3 sidecar (`S3`: the server verifies the signature against it). - Let the super admin's password (`E2E_SUPERUSER_PASSWORD`, new every run, set by `run-in-docker.sh`) reach a command line, log, trace, report, test title, annotation or error message; keep `set -x` off in the script. Never give the password to a matcher as the expected or received value (`expect(text).not.toContain(password)` prints it when it fails): assert `text.includes(password)` is `false`. The sign-in lives in an automatic worker fixture (`superAdminState`) because a request context created inside a test lands in its trace; do not sign the super admin in from a test or a helper, and create no request context in a helper. Every test that uses the `superAdmin` fixture carries `TAGS.SUPERADMIN` (a guard in `foundation/run-selection.spec.ts` checks it by parsing the spec with the TypeScript compiler: write the tag as `TAGS.SUPERADMIN` in the test's or its describe's details, a mention in a comment or title does not count). The super admin is ONE account shared by all workers: never switch its workspace or change its password. It hangs once the stack holds more than about 420 workspaces (README, security section): the SEC-R16 tests therefore carry `@superadmin` and run only on request (`E2E_INCLUDE_SUPERADMIN=1`); keep such runs short. - Duplicate a helper that exists: @@ -196,6 +196,7 @@ MUST NOT: | Firebird sidecar connection (opt-in sidecar: throws `FirebirdSidecarMissingError` when `E2E_FIREBIRD_HOST` is unset), the rows of `fixtures/firebird/init.sql` | `firebirdConnection`, `FirebirdSidecarMissingError`, `FIREBIRD_ITEMS` | `src/datasource/firebird.ts` | | libSQL sidecar connection (opt-in sidecar: throws `LibsqlSidecarMissingError` when `E2E_LIBSQL_HOST` is unset) and a direct pipeline call to it from the test process (the control that shows the server's own answer) | `libsqlConnection`, `libsqlDirect`, `LibsqlSidecarMissingError`, `LIBSQL_PIPELINE_PATH` | `src/datasource/libsql.ts` | | CouchDB sidecar connection (opt-in sidecar: throws `CouchdbSidecarMissingError` when `E2E_COUCHDB_HOST` is unset) and a direct HTTP call to it from the test process, plain or as the sidecar's admin (the control that shows the server's own status and body, and the way a test makes and removes its own database) | `couchdbConnection`, `couchdbDirect`, `couchdbAdmin`, `CouchdbSidecarMissingError` | `src/datasource/couchdb.ts` | +| S3 sidecar connection (opt-in sidecar, reached by IP address only: throws `S3SidecarMissingError` when `E2E_S3_IP` is unset and `S3SidecarAddressError` when it is not an IPv4 address) and a signed direct call to it from the test process (the control that shows the server's own status, headers and bytes, and the way a test makes and removes its own buckets and objects: `s3Direct`, `s3CreateBucket`, `s3DirectKeys`, `s3RemoveBucket`, `signS3Request`, `s3Path`, `s3Query`, `xmlValues`) | `s3Connection`, `s3Direct`, `s3CreateBucket`, `s3DirectKeys`, `s3RemoveBucket`, `signS3Request`, `S3SidecarMissingError`, `S3SidecarAddressError` | `src/datasource/s3.ts` | | DynamoDB Local sidecar connection (opt-in sidecar: throws `DynamodbSidecarMissingError` when `E2E_DYNAMODB_HOST` is unset) and a direct call of the DynamoDB JSON protocol to it from the test process in the API's typed form (the control that shows what the server holds, and the way a test makes and removes its own tables) | `dynamodbConnection`, `dynamodbDirect`, `DynamodbSidecarMissingError`, `DYNAMODB_CONTENT_TYPE`, `DYNAMODB_TARGET_PREFIX` | `src/datasource/dynamodb.ts` | | pages | `EditorPage`, `AppViewPage`, `PropertyPanel`, `QueryPanel`, `TableView`, `ExtensionsPanel`, `AppListPage`, `AuthPage`, `LoginPage`, `UserMenu`, `SettingPage`, `DatasourcePage` | `src/pages/` | @@ -272,10 +273,11 @@ e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 # gene E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --grep @quarantine E2E_INCLUDE_INSERT_ALL=1 e2e/scripts/run-in-docker.sh --grep @insert-all --workers=4 # S1 gate, once E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin # SEC-R16a, R16b (R16c, R16d also need E2E_INCLUDE_QUARANTINE=1) -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-firebird.spec.ts # D12 gate: starts the Firebird sidecar (image pull, a few seconds) -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-turso-libsql.spec.ts # D13 gate: starts both sidecars (Firebird and libSQL) -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-couchdb.spec.ts # D14 gate: starts all four sidecars (Firebird, libSQL, CouchDB and DynamoDB Local) -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-dynamodb-local.spec.ts # D15 gate: starts all four sidecars +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-firebird.spec.ts # D12 gate: the flag starts all five sidecars (image pulls on a cold machine, a few seconds) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-turso-libsql.spec.ts # D13 gate: starts all five sidecars +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-couchdb.spec.ts # D14 gate: starts all five sidecars (Firebird, libSQL, CouchDB, DynamoDB Local and S3) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-dynamodb-local.spec.ts # D15 gate: starts all five sidecars +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-s3-server.spec.ts # D16 gate: starts all five sidecars E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # only the tests that need a sidecar e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/modules/module-editor-host.spec.ts # M3 gate E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/security/enterprise.spec.ts # ENTERPRISE stack gate (its own stack; never at the same time as another run) @@ -290,7 +292,7 @@ Directory `e2e/` (no stack; `--reporter=list` is required so no report files are LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_INCLUDE_QUARANTINE=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_INCLUDE_SUPERADMIN=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # adds the D12, D13, D14 and D15 tests +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # adds the D12, D13, D14, D15 and D16 tests E2E_INCLUDE_INSERT_ALL=1 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_SUPERADMIN=1 LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list E2E_STACK_PROFILE=enterprise LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list # the SEC-E tests only ``` diff --git a/e2e/README.md b/e2e/README.md index 8d6522b9d7..33da475a5a 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; Firebird (node-firebird over TCP, D12) runs against a Firebird sidecar of its own that only a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` starts, and a default run neither starts it nor lists or runs those tests, and Turso also runs against a real libSQL server (sqld, D13) the same way, where the `libsql://` to `https://` rewrite of the URL is not covered because the sidecar speaks plain HTTP, and CouchDB also runs against a real Apache CouchDB server (D14) the same way, where the JWT credential and cookie sessions are not covered because the image's default configuration has no JWT authentication handler and the plugin sends the `Authorization` header only, and DynamoDB also runs against a real DynamoDB Local server (D15) the same way, where indexes, transactions, batch operations, streams and the request signature (the server verifies none) are not covered; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; Firebird (node-firebird over TCP, D12) runs against a Firebird sidecar of its own that only a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` starts, and a default run neither starts it nor lists or runs those tests, and Turso also runs against a real libSQL server (sqld, D13) the same way, where the `libsql://` to `https://` rewrite of the URL is not covered because the sidecar speaks plain HTTP, and CouchDB also runs against a real Apache CouchDB server (D14) the same way, where the JWT credential and cookie sessions are not covered because the image's default configuration has no JWT authentication handler and the plugin sends the `Authorization` header only, and DynamoDB also runs against a real DynamoDB Local server (D15) the same way, where indexes, transactions, batch operations, streams and the request signature (the server verifies none) are not covered, and S3 also runs against a real S3-compatible server (versitygw, D16) the same way, reached by its IP address only (it has no name), where a real AWS S3, multipart upload, an expired presigned URL, versioning and ACLs are not covered; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -54,15 +54,22 @@ lifecycle (insert, save, publish, load) is covered by S1 when `@insert-all` runs - **Image:** `couchdb:3.5.1`, Apache CouchDB 3.5.1 (the official image; the plugin bundles the 3.1.1 API document), pinned by tag and digest (`sha256:ccea1e8035bf7afd68336e24056a1ca9c1c46d7abe42da686322c0ac7218e5c2`; `COUCHDB_IMAGE` overrides it). The image declares `/opt/couchdb/data` a volume, so the script mounts a tmpfs there: the data is in memory and this sidecar leaves no anonymous volume (measured: `docker inspect` of the running container shows `Mounts` empty and the tmpfs; see the dangling-volumes evidence in the counts paragraph below). - **Admin setup:** the image makes one server admin from `COUCHDB_USER` and `COUCHDB_PASSWORD` (`COUCHDB` in `src/constants.ts` and the script: `e2eadmin` and a throw-away password, never a real secret). A fresh single node has no system databases (`_all_dbs` answers `[]`), so the readiness step creates `_users`, `_replicator` and `_global_changes` with `PUT` through the real HTTP API (201, or 412 when they exist) and is ready when `_all_dbs` lists all three; it runs inside the container (the image has curl), is idempotent, and is repeated until it succeeds. The tests make their own databases (`e2e_couch_`) and remove them. - **Lockout (measured, CouchDB 3.5.1):** after five failed logins of a real account the server answers 403 `Account is temporarily locked due to multiple authentication failures` to that account, from that client address, even with the right password (the message says "temporarily"; how long it lasts was not measured). A test that sends a wrong password therefore does it as a second admin it makes for the purpose (D14e, D14j) and never as the sidecar's admin, which every other test uses; failures for a name that does not exist are not counted. A freshly made config admin cannot log in until the server has hashed its password (a moment after the `PUT`), so the helper waits for the hash before the first login. - - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-couchdb.spec.ts` (all three sidecars start; `--grep @node-service-sidecar` runs D12 and D13 as well). + - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-couchdb.spec.ts` (every sidecar starts under the flag, five today; `--grep @node-service-sidecar` runs the other sidecar tests as well). - **Cost, measured here:** the image is 276 MB (`docker image inspect`, uncompressed); CouchDB answered the readiness probe on its first try, about a second after it started (the script logged `CouchDB sidecar ready after 0s`: the wait runs after the PostgreSQL, echo, Firebird and libSQL waits, and the server's log shows it started in about half a second), so all three sidecars together added no waiting of their own beyond the slowest. A cold pull of the pinned digest took 6.4 s (a fast link: expect more elsewhere). The readiness bound is described under the DynamoDB Local sidecar. A test that fails still ends with every container and the network removed (measured with a deliberately failing test under the flag: seven containers created, none left, no network left). - **DynamoDB Local sidecar (opt-in):** the DynamoDB plugin of node-service uses the AWS SDK v3 with a configurable endpoint, so the echo can stand in for it (D10a to D10f, canned answers and the signed request); a real server adds what canned answers cannot: real tables and items, the typed attribute form on the wire, pagination keys, and the server's own errors (D15, `tests/datasource/plugin-dynamodb-local.spec.ts`). It is OPT-IN under the same flag and tag as the other sidecars and all four start together: - **A default run** starts no DynamoDB Local container, pulls no DynamoDB Local image, passes no `E2E_DYNAMODB_HOST` to the runner, and neither lists nor runs the D15 tests (`--list --grep @node-service-sidecar` shows 0). **A run with the flag** starts the sidecar right after the CouchDB one, waits (`STARTUP_TIMEOUT`, 300 s of real elapsed time, polled every 2 s; every readiness request is aborted after 5 s; see "Readiness bound" below) until one real `ListTables` call, posted from the echo container to `http://e2e-dynamodb:8000/` over the run network, answers exactly 200 with a JSON body whose `TableNames` member is an array, gives the app container and the runner `--add-host e2e-dynamodb:` (appended to the entries of the other sidecars), passes `E2E_DYNAMODB_HOST=e2e-dynamodb` to the runner, and removes the container in the cleanup trap however the run ends. The data source's endpoint is `http://e2e-dynamodb:8000` (`dynamodbConnection()` throws a named error when the host variable is unset). Reached from both sides: the plugin's requests come from the app container, and the direct calls and D15l come from the runner. - **Image:** `amazon/dynamodb-local:3.3.2` (AWS's own image, DynamoDB Local 3.3.2, Java 17), pinned by tag and digest (`sha256:6ada631ec7aa5fc83446855eb17233e3dad184fec47477e8140c6c569cfe0c86`, the digest of `3.3.2` and `latest` on Docker Hub when it was pulled; `DYNAMODB_IMAGE` overrides it). It runs `-jar DynamoDBLocal.jar -inMemory -sharedDb -port 8000`: every table is in memory (nothing is written to a file) and one database serves every access key, so table names are global to the sidecar and each test names its tables with a per-test marker (`e2e_ddb_`) and removes them in a `finally`. The image declares no volume (`docker image inspect` shows no `Volumes`), so no `--tmpfs` is needed: measured, the running container's `Mounts` is empty. - **Credentials:** the server checks none: it wants an `Authorization` header with a `Credential=` scope and accepts any access key and any signature (measured: a signature of zeros is accepted; a request without the header is refused with `MissingAuthenticationToken`). `DYNAMODB` in `src/constants.ts` holds a throw-away key, secret and region, never a real secret; the direct calls of the tests send the same header form with a signature of zeros. - - **Readiness bound (the Firebird, libSQL, CouchDB and DynamoDB Local waits):** each loop takes the shell's `SECONDS` at its start and, after every failed probe, compares the elapsed seconds with `STARTUP_TIMEOUT` before it sleeps and probes again, so the time a probe takes counts (an earlier version added up its sleeps only: with probes that take 5 s each it ran several times past the limit). The check comes before the sleep and the next probe, and one probe is bounded as a WHOLE: the Firebird probe is one `isql` run under `timeout -s KILL 5`, the libSQL and DynamoDB probes are one fetch aborted after 5 s, and the CouchDB probe, which makes five requests (`_up`, three `PUT`s, `_all_dbs`), shares one 5 s budget (`couchdb_curl` gives each request the time left of the probe's deadline as its `--max-time`, and a request that finds nothing left is not made). So for each of the four the worst case is `STARTUP_TIMEOUT` + `POLL_INTERVAL` (2 s) + `PROBE_REQUEST_TIMEOUT` (5 s), that is 7 s past the limit, plus up to one second of clock granularity (`SECONDS` counts whole seconds) and the start-up time of the `docker exec` calls, which has no limit of its own; not an unbounded multiple. A foundation test fails for any of the four loops that goes back to the sleep-only counter. The PostgreSQL, echo and app waits were not changed: they still add up their sleeps only and their probes have no time limit. Measured by hand on one machine, no artifacts committed, with temporary copies of the script (`STARTUP_TIMEOUT=6`): the sidecar's probe was made unable to succeed (DynamoDB: another accepted status; libSQL: a token the server refuses; CouchDB: other accepted statuses; Firebird: a table that does not exist) so that it failed fast, and 4 s after the container appeared the server was frozen (`docker pause` for DynamoDB and libSQL, whose probe runs in the echo container; SIGSTOP of the server processes for CouchDB and Firebird, whose probe runs inside the container), so that the probes were accepted by the kernel and never answered and each ended at its 5 s limit. Each run ended with `the sidecar did not become ready within 6s` and no container or network left. Total duration of the script, start of the stack included (about 2 s): with the sleep-only counter 20 s for DynamoDB Local, 19 s for libSQL, 19 s for CouchDB and 19 s for Firebird; with the elapsed-time deadline 12 s for each of the four (the stack takes about 2 s, so the wait ended about 10 s after it began, inside the worst case of 6 + 2 + 5 = 13 s). CouchDB was measured again after its probe got the shared budget, three runs of the same method: 12 s, 13 s and 12 s. A frozen server stalls only the first request of its probe, so this method does not show the budget; the budget was shown with a stub `docker` that answers each of the five requests correctly but takes 3 s for it: the probe of the earlier form took 15 s and succeeded, the probe with the shared budget stopped after 5 s and failed, and a foundation test fails for the earlier form (the structural assertions of the probe's deadline). An earlier measurement of 10 s with a paused DynamoDB container did not exercise a stalled probe: the container was frozen before the server listened, so the connection was refused at once. - - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-dynamodb-local.spec.ts` (all four sidecars start; `--grep @node-service-sidecar` runs D12, D13 and D14 as well). + - **Readiness bound (the Firebird, libSQL, CouchDB, DynamoDB Local and S3 waits):** each loop takes the shell's `SECONDS` at its start and, after every failed probe, compares the elapsed seconds with `STARTUP_TIMEOUT` before it sleeps and probes again, so the time a probe takes counts (an earlier version added up its sleeps only: with probes that take 5 s each it ran several times past the limit). The check comes before the sleep and the next probe, and one probe is bounded as a WHOLE: the Firebird probe is one `isql` run under `timeout -s KILL 5`, the libSQL, DynamoDB and S3 probes are one fetch aborted after 5 s, and the CouchDB probe, which makes five requests (`_up`, three `PUT`s, `_all_dbs`), shares one 5 s budget (`couchdb_curl` gives each request the time left of the probe's deadline as its `--max-time`, and a request that finds nothing left is not made). So for each of the five the worst case is `STARTUP_TIMEOUT` + `POLL_INTERVAL` (2 s) + `PROBE_REQUEST_TIMEOUT` (5 s), that is 7 s past the limit, plus up to one second of clock granularity (`SECONDS` counts whole seconds) and the start-up time of the `docker exec` calls, which has no limit of its own; not an unbounded multiple. A foundation test fails for any of the five loops that goes back to the sleep-only counter (measured: with the S3 loop changed back to the sleep-only counter, together with five other changes to the script, five structural tests failed and the restored script passed them). The PostgreSQL, echo and app waits were not changed: they still add up their sleeps only and their probes have no time limit. Measured by hand on one machine, no artifacts committed, with temporary copies of the script (`STARTUP_TIMEOUT=6`): the sidecar's probe was made unable to succeed (DynamoDB: another accepted status; libSQL: a token the server refuses; CouchDB: other accepted statuses; Firebird: a table that does not exist) so that it failed fast, and 4 s after the container appeared the server was frozen (`docker pause` for DynamoDB and libSQL, whose probe runs in the echo container; SIGSTOP of the server processes for CouchDB and Firebird, whose probe runs inside the container), so that the probes were accepted by the kernel and never answered and each ended at its 5 s limit. Each run ended with `the sidecar did not become ready within 6s` and no container or network left. Total duration of the script, start of the stack included (about 2 s): with the sleep-only counter 20 s for DynamoDB Local, 19 s for libSQL, 19 s for CouchDB and 19 s for Firebird; with the elapsed-time deadline 12 s for each of the four (the stack takes about 2 s, so the wait ended about 10 s after it began, inside the worst case of 6 + 2 + 5 = 13 s). CouchDB was measured again after its probe got the shared budget, three runs of the same method: 12 s, 13 s and 12 s. A frozen server stalls only the first request of its probe, so this method does not show the budget; the budget was shown with a stub `docker` that answers each of the five requests correctly but takes 3 s for it: the probe of the earlier form took 15 s and succeeded, the probe with the shared budget stopped after 5 s and failed, and a foundation test fails for the earlier form (the structural assertions of the probe's deadline). An earlier measurement of 10 s with a paused DynamoDB container did not exercise a stalled probe: the container was frozen before the server listened, so the connection was refused at once. The S3 loop was measured the same way (a temporary copy of the script with `STARTUP_TIMEOUT=6` and another accepted status, so that the probe could not succeed; the S3 container paused 4 s after it appeared, so the kernel accepted the connections and nothing answered): the script ended with `the S3 sidecar did not become ready within 6s` after 13 s in total (the stack takes about 2 s, so the wait ended inside the worst case of 6 + 2 + 5 = 13 s), and no container or network was left; the copy was deleted. + - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-dynamodb-local.spec.ts` (every sidecar starts under the flag, five today; `--grep @node-service-sidecar` runs the other sidecar tests as well). - **Cost, measured here:** the image is 512 MB (`docker image inspect`, uncompressed); the JVM server answered the readiness call on its first try, within a second or two of starting (the script logged `DynamoDB Local sidecar ready after 0s`: the wait runs after the PostgreSQL, echo, Firebird, libSQL and CouchDB waits), so the sidecars were all ready about three seconds after the first container of the run was created, while the app needs 10 to 12 s (measured: `Application ready after 10s` and `after 12s` in flagged runs; the readiness waits run after the app container is started). A cold pull of the pinned digest took 10 s (a fast link: expect more elsewhere). A test that fails still ends with every container and the network removed (measured with twelve deliberately inverted assertions under the flag: none left, no network left). These results were measured by hand on one machine; no artifacts are committed. A gate of 120 tests (`--repeat-each=10 --workers=4`) ran in about 31 s. Runs without the flag pay nothing. +- **S3 sidecar (opt-in):** the S3 plugin of node-service uses the AWS SDK v3 with a configurable endpoint, so the echo can stand in for it (D10g to D10q, canned answers and the signed request); a real server adds what canned answers cannot: real buckets and objects, the bytes and content types that come back, listing behaviour, presigned URLs that can be fetched, the server's own errors and its verification of the signature (D16, `tests/datasource/plugin-s3-server.spec.ts`). It is OPT-IN under the same flag and tag as the other sidecars and all five start together: + - **A default run** starts no S3 container, pulls no S3 image, passes no `E2E_S3_IP` to the runner, and neither lists nor runs the D16 tests (`--list --grep @node-service-sidecar` shows 0). **A run with the flag** starts the sidecar right after the DynamoDB Local one, waits (`STARTUP_TIMEOUT`, 300 s of real elapsed time, polled every 2 s; every readiness request is aborted after 5 s; see "Readiness bound" under the DynamoDB Local sidecar) until one real, SIGNED ListBuckets request, posted from the echo container to `http://:7070/` over the run network, answers exactly 200 with a `ListAllMyBucketsResult`, and removes the container in the cleanup trap however the run ends. + - **Addressing (why this sidecar has an IP and no name):** the AWS SDK addresses a bucket of an endpoint that is a host NAME as `.` (virtual-host style), a name that no `--add-host` entry covers and that may resolve outside the run network; for an endpoint that is an IP address it uses path-style (`//`) (measured in D10, and again against this server). So, unlike the other sidecars, this one has no network alias and no `--add-host` entry: the script reads the container's IP address on the run network when it starts it (`docker inspect`, like the echo's), passes it to the runner as `E2E_S3_IP` (`S3.IP_ENV` in `src/constants.ts`), and the data source's endpoint is `http://:7070`. `s3Connection()` (`src/datasource/s3.ts`) reads it and throws a named error when it is unset (`S3SidecarMissingError`) or is not an IPv4 address (`S3SidecarAddressError`), like `echoUrlByIp` for `E2E_ECHO_IP`; the foundation tests check both and that the script names the variable once, adds no alias and no `--add-host`. Measured by hand (one machine, no artifacts committed): from inside the app container the sidecar answers by IP (an unsigned request: 403 `AccessDenied`, an S3 XML error), the name `e2e-s3` does not resolve there (`HTTP 000`), and a presigned URL made with the SDK for an object with a space in its key downloaded the object from the app container (HTTP 200, the content) and from the host. Reached from both sides in the tests: the plugin's requests come from the app container; the direct calls (`s3Direct`) and the presigned URLs of D16i come from the runner. + - **Image:** `versity/versitygw:v1.11.0` (Versity S3 Gateway, Go, one static binary, started with its POSIX backend), pinned by tag and digest (`sha256:8319a530d08d537426e2f855bae5280709795dc73a3f0c347973ef915d6343c5`, the digest of `v1.11.0` and `latest` on Docker Hub when it was pulled; `S3_IMAGE` overrides it). It runs `--port :7070 --quiet posix --sidecar /meta /data` with two tmpfs mounts (`/data` the objects, `/meta` the metadata sidecar directory, so the server needs no extended attributes on the data directory): everything is in memory and nothing outlives the container. The image declares no volume (`docker image inspect` shows `Volumes: null`; measured: the running container's `Mounts` is empty and its `HostConfig.Tmpfs` is `/data` and `/meta`), so the two tmpfs mounts are directories the script chose, not volumes the image forced on it; the foundation test table of declared volumes lists them. The server is started in region `us-west-1` (`VGW_REGION`, the plugin form's default region); a bucket made in that region needs the location constraint in the create request (without it the server answers 400 `IllegalLocationConstraintException`, as AWS does), which the helper `s3CreateBucket` sends. Why this one, measured on this machine (2026-11-25): MinIO (`minio/minio` on Docker Hub: `denied: requested access to the resource is denied`; `quay.io/minio/minio:latest` and a 2025 release tag: `no such manifest`; `bitnami/minio:latest`: no such manifest) has no pullable community image. `adobe/s3mock:5.2.3` pulls (84 MB compressed, 134 MB on disk, a JVM; answered about 2 s after it started) but VERIFIES NOTHING: ListBuckets with a wrong access key and with a wrong secret both succeeded (measured with the AWS SDK), so no wrong-credential scenario could be written against it. `chrislusf/seaweedfs`, `zenko/cloudserver`, `dxflrs/garage` and `localstack/localstack` have manifests on Docker Hub but are multi-process or configuration-heavy servers (not run here). versitygw: 37 MB compressed (Docker Hub), 82 MB on disk, one process, in memory on tmpfs, path-style and virtual-host support, verifies AWS Signature Version 4 for every request. + - **Auth setup:** one root user from the image's own variables `ROOT_ACCESS_KEY_ID` and `ROOT_SECRET_ACCESS_KEY` (`S3` in `src/constants.ts` and `S3_ACCESS_KEY`, `S3_SECRET_KEY` in the script: `e2eS3Key` and a throw-away secret, never real secrets; no key on the server's command line). The server VERIFIES the signature: measured with the SDK and again in D16a, D16b and D16k, a wrong access key is refused with 403 `InvalidAccessKeyId` ("The AWS Access Key Id you provided does not exist in our records."), a wrong secret with 403 `SignatureDoesNotMatch`, a request signed for another region with the authorization-header-malformed text naming the region it expects, and a request without a signature with 403 `AccessDenied`. So wrong-credential scenarios are real, unlike DynamoDB Local, which checks nothing. + - **Run only these:** `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh tests/datasource/plugin-s3-server.spec.ts` (all five sidecars start; `--grep @node-service-sidecar` runs D12 to D15 as well). + - **Cost, measured here:** the image is 82 MB on disk (`docker image inspect`) and a cold pull of the pinned tag took 2.9 s (a fast link: expect more elsewhere); the sidecar answered the readiness request within a second of starting (the script logged `S3 sidecar ready after 0s` or `1s`: the wait runs after the PostgreSQL, echo, Firebird, libSQL, CouchDB and DynamoDB Local waits). With all five sidecars the script logged the first `Starting` line at 08:07:56 and the last sidecar ready at 08:07:58, and `Application ready after 10s` (12 s after the first container; the sidecar waits run after the app container is started, so they delay nothing). A gate of 150 tests (`--repeat-each=10 --workers=4`) ran in about 35 s. Runs without the flag pay nothing. The readiness bound is described under the DynamoDB Local sidecar. These results were measured by hand on one machine; no artifacts are committed. - **HTTP echo sidecar** (`scripts/echo-server.js`, started by `run-in-docker.sh` on the already pinned runner image, so no extra image or download; network alias `e2e-echo`, port 8080; the runner gets `E2E_ECHO_URL` and the sidecar's IP address on the run network as `E2E_ECHO_IP`): the target of the requests the SERVER makes inside the app container (node-service's npm registry proxy, the n8n plugin). It records `{ method, path, headers, body }` of every request in @@ -152,7 +159,7 @@ e2e/scripts/run-in-docker.sh -g "sign-up through the UI" # one test b e2e/scripts/run-in-docker.sh --grep @smoke # by tag: @smoke @core @slow @npm E2E_INCLUDE_QUARANTINE=1 e2e/scripts/run-in-docker.sh --grep @quarantine E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh --grep @superadmin # SEC-R16a, SEC-R16b (R16c, R16d also need E2E_INCLUDE_QUARANTINE=1) -E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # D12 to D15, the Firebird, libSQL, CouchDB and DynamoDB Local sidecar tests (starts all four sidecars) +E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --grep @node-service-sidecar # D12 to D16, the Firebird, libSQL, CouchDB, DynamoDB Local and S3 sidecar tests (starts all five sidecars) E2E_INCLUDE_INSERT_ALL=1 E2E_INCLUDE_QUARANTINE=1 E2E_INCLUDE_SUPERADMIN=1 e2e/scripts/run-in-docker.sh # everything on the default stack (not the @enterprise tests) E2E_STACK_PROFILE=enterprise e2e/scripts/run-in-docker.sh tests/security/enterprise.spec.ts # the ENTERPRISE stack, SEC-E01 to E04, E06a, E06b, E07a, E07b E2E_STACK_PROFILE=signup-disabled e2e/scripts/run-in-docker.sh tests/auth/signup-disabled.spec.ts # the stack with e-mail sign-up switched off, LC-AU20 to AU24 @@ -207,13 +214,15 @@ data; its tests are untagged. | `PLAYWRIGHT_IMAGE` | run-in-docker.sh | runner image; version must equal `@playwright/test` in `package-lock.json` (1.64.0) | | `POSTGRES_IMAGE` | run-in-docker.sh | PostgreSQL sidecar image | | `FIREBIRD_IMAGE` | run-in-docker.sh | Firebird sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | -| `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | script and config | non-empty, default stack only (any other profile stops the script): start the Firebird, libSQL, CouchDB and DynamoDB Local sidecars and include the `@node-service-sidecar` tests (D12, D13, D14, D15) | +| `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | script and config | non-empty, default stack only (any other profile stops the script): start the Firebird, libSQL, CouchDB, DynamoDB Local and S3 sidecars and include the `@node-service-sidecar` tests (D12, D13, D14, D15, D16) | | `LIBSQL_IMAGE` | run-in-docker.sh | libSQL server (sqld) sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | | `E2E_LIBSQL_HOST` | set by run-in-docker.sh | the libSQL sidecar's network alias, only in a run with the flag; `libsqlConnection()` reads it | | `COUCHDB_IMAGE` | run-in-docker.sh | CouchDB sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | | `E2E_COUCHDB_HOST` | set by run-in-docker.sh | the CouchDB sidecar's network alias, only in a run with the flag; `couchdbConnection()` reads it | | `DYNAMODB_IMAGE` | run-in-docker.sh | DynamoDB Local sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | | `E2E_DYNAMODB_HOST` | set by run-in-docker.sh | the DynamoDB Local sidecar's network alias, only in a run with the flag; `dynamodbConnection()` reads it | +| `S3_IMAGE` | run-in-docker.sh | S3-compatible server (versitygw) sidecar image (tag and digest pinned), used only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS` | +| `E2E_S3_IP` | set by run-in-docker.sh | the S3 sidecar's IP address on the run network (it has no alias: a bucket of a host name is addressed `.`), only in a run with the flag; `s3Connection()` reads it, and throws when it is unset or not an IPv4 address | | `E2E_FIREBIRD_HOST` | set by run-in-docker.sh | the Firebird sidecar's network alias, only in a run with the flag; `firebirdConnection()` reads it | | `E2E_INCLUDE_QUARANTINE`, `E2E_INCLUDE_INSERT_ALL`, `E2E_INCLUDE_SUPERADMIN` | script and config | non-empty: include that opt-in group | | `E2E_STACK_PROFILE` | run-in-docker.sh, config | `default` (the default), `signup-disabled` (the app container gets `LOWCODER_EMAIL_SIGNUP_ENABLED=false` and the run keeps only the `@signup-disabled` tests; `E2E_INCLUDE_QUARANTINE` is the only flag that applies) or `enterprise`: the app container gets `LOWCODER_WORKSPACE_MODE=ENTERPRISE` and the run keeps only the `@enterprise` tests (`grep`); another value stops the run. On the enterprise profile `E2E_INCLUDE_QUARANTINE` opens nothing extra (no enterprise test is quarantined any more), `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` change nothing (the stack has one workspace, so the D-47 limit does not arise). A `--grep` of the command line narrows the profile's selection further; it does not replace it (measured with Playwright 1.64: enterprise profile with `--grep SEC-R01b` lists 0 tests, with `--grep SEC-E02` lists 1, with the default profile `--grep SEC-E02` lists 0) | @@ -297,15 +306,16 @@ Test titles carry these ids. - D13 the Turso plugin of node-service against the opt-in libSQL server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): create, insert and select answer typed rows (integer, real, a lower-case `boolean`, `datetime`, NULL), `includeRaw` answers the server's own result set, a write answers no values and its raw result counts the change, a blob cell is dropped from the row (NSD-14 candidate), an integer beyond 2^53 is rounded (NSD-15 candidate), a real SQL error (syntax, unknown column, constraint, two statements) fails the query with `[object Object]` (NSD-1 candidate, the defect of D5d against a real server), a token of another key or a malformed one is a 401, a read-only token reads and its write is a 403, the published view after a click, a trailing slash after the URL is a 404, and the runner reaches the sidecar. The `libsql://` rewrite is not covered. - D14 the CouchDB plugin of node-service against the opt-in CouchDB server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): a database is created, listed (by a key range), described and deleted, and the server agrees at each step; a document is created, read, updated by its revision, read at its old revision, listed and deleted; a stale revision (as a query parameter or as `If-Match`) answers a conflict body and changes nothing (NSD-4 candidate); a missing database or document and an existing database answer their error bodies (NSD-4 candidate); a wrong password answers an unauthorized body and writes nothing (NSD-4 candidate); five wrong passwords lock the account for the client address and even the right password then gets the lockout's 403 body (NSD-4 candidate); `docGet` cannot run without `If-None-Match` and a matching ETag fails with `status: 304` (NSD-16 candidate); the listing options (`startkey`, `endkey`, `descending`, `skip`, `limit`) reach the server; the published view shows a document after a click; and the runner reaches the sidecar. The JWT credential and cookie sessions are not covered. - D15 the DynamoDB plugin of node-service against the opt-in DynamoDB Local server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): a table is created (the description's complete shape), refused when it exists, listed and paged by name, and the server agrees at each step (D15a); an item of every type the plugin writes (string, empty string, integers, negative, fraction, booleans, null, map, number set, string set, mixed list, list of maps) is stored in the typed form and read back as plain values (D15b); Query (key condition, range, projection, descending, `Limit`) and Scan (filter, `Select: COUNT`) answer unwrapped items with the counts, `LastEvaluatedKey` stays typed, and a scan with `Limit: 2` is paged by feeding each returned typed key into the next request until none is returned: no item missing or twice, no page above the limit, at least three requests, the last page without a key (D15c); UpdateItem and DeleteItem change the server's data, a failed condition changes nothing, and `ReturnValues` answers `Attributes` that stay typed (D15d, D15e, NSD-17 candidate); a missing table, a failed condition, a missing or mistyped key, an empty key, a bad table name and an existing table fail the query with the server's own message (D15f); an array of strings or numbers is always a set (order lost, duplicates and an empty array refused, NSD-18 candidate, D15g); a binary attribute reads as an object with index keys and a number beyond a double loses digits (NSD-19 candidate, D15h); an `ExclusiveStartKey` in the plain form fails with the SDK's `TypeError` (NSD-20 candidate, D15i); any access key reaches the same tables and a closed port of the sidecar's host fails with the connection error (D15j); the published view shows an item after a click (D15k); and the runner reaches the sidecar (D15l). DescribeTable and DeleteTable are not offered by the form (direct calls only); indexes, transactions, batch operations and streams are not covered. +- D16 the S3 plugin of node-service against the opt-in S3-compatible server sidecar (versitygw, `@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`; the endpoint is the sidecar's IP address, path-style): the connection test accepts the right key pair and the server itself refuses a wrong access key, a wrong secret and a wrong region with its own text (D16a), the form's Test Connection button shows the refusal and then the success (D16b), a `listBuckets` query shows a new bucket as a name only (D16c), `uploadData` stores the decoded bytes with the content type (text, all 256 byte values, an empty type becomes `application/octet-stream`, an overwrite replaces object and type) and `readFile` answers type, the server's length, the server's time and the data as text or base64 (D16d), `listObjects` with a prefix, a limit and no match (D16e), a listing cut by the limit cannot be continued: the plugin sends no marker and shows no truncation (NSD-21 candidate, D16f), a delimiter drops the common prefixes the server answers (NSD-22 candidate, D16g), `deleteFile` removes an existing key and answers the same success for an absent one (D16h), a presigned URL of `listObjects` and of `uploadData` downloads the object from the runner while the plain `url`, a changed signature and another key are refused by the server (D16i), keys with spaces, unicode, `+&=%?#;,'()*!` and slashes are stored under their exact names, listed and read, with an `url` that is not encoded (NSD-24 candidate, D16j), the server's `NoSuchBucket` (listObjects, readFile, uploadData, deleteFile), `NoSuchKey` (readFile) and, for a wrong access key or a wrong secret, `InvalidAccessKeyId` and `SignatureDoesNotMatch` (listBuckets, listObjects, readFile, uploadData, deleteFile) messages reach the query (D16k), an empty bucket name is refused with the messages above and stores nothing in an existing bucket (NSD-8 candidate, D16l; that no request is sent is shown by D10q against the echo's recorded requests, not by D16l), a 3 MiB body arrives byte for byte and its length agrees (D16m), `uploadData` with the default encoding stores plain text as other bytes without a message (NSD-23 candidate, D16n), and a closed port gives the whole connection-error envelope while the server's port gives the whole success envelope (D16o). Not covered: a real AWS S3, multipart upload, an expired presigned URL, versioning, ACLs. - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue -Counts (re-measured 2026-11-25 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 847-test suite after the DynamoDB Local sidecar scenarios (D15) landed (measured before the readiness loops of the four sidecars got their elapsed-time deadline and before one more unit test and the extra controls of D15c, D15e and D15f were added; it was not repeated after them, only the gates below were), `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (no variable set): 43 failed, 804 passed (6.7 min). It started no Firebird, libSQL, CouchDB or DynamoDB Local container (a separate default run measured with `docker events` created the PostgreSQL, echo, app and runner containers only) and ran no D12 to D15 test (they are not in the listing). The baseline from a clean worktree of the previous commit (840 tests, same command and image): 44 failed, 796 passed. The failing sets are identical except one test (compared by test name): 24 `@security`, 17 `@lifecycle` and 2 others (`components/npm-components.spec.ts` calendar, `@npm`; `apps/card-menu.spec.ts` export and import, `@core`); the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag, not analysed one by one). The one difference is `SEC-R09d`, which failed in the baseline and passed in this run (it is intermittent: it passed here and in an earlier full run, and failed in both baselines); the periodic trigger test of `logic/triggers.spec.ts` failed in neither. The eight extra passes are the seven new unit tests of `foundation/node-plugins.spec.ts` and the one more test that passed here instead of failing. No node-service scenario failed. The D12, D13 and D14 evidence is a separate gate each, `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 `: for `tests/datasource/plugin-firebird.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D12 landed), for `tests/datasource/plugin-turso-libsql.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D13 landed), for `tests/datasource/plugin-couchdb.spec.ts` 100 passed on `3.0.0-e2e` and 100 passed on `3.0.1-e2e`, and after the readiness probes got their time limits 110 passed for the Firebird spec and 110 for the libSQL spec on `3.0.0-e2e` (all three sidecars start; the app was ready 15 s after the first container started with the flag against 14 s without it). For `tests/datasource/plugin-dynamodb-local.spec.ts` (D15) 120 passed on `3.0.0-e2e` and 120 passed on `3.0.1-e2e`, run after the last change of the spec (all four sidecars start; `docker events` showed the PostgreSQL, echo, Firebird, libSQL, CouchDB and DynamoDB Local containers created within one second, and the script logged every readiness wait as `ready after 0s`, the last one three seconds after the first container was created; the readiness waits run after the app container is started, so they do not delay it). Dangling volumes, measured by hand on one machine (no artifact is committed): before the PostgreSQL and Firebird sidecars got a tmpfs over their declared data volumes (`/var/lib/postgresql/data`, `/var/lib/firebird/data`), a default run left one anonymous volume (PostgreSQL's) and a flagged run two (PostgreSQL's and Firebird's); the libSQL and CouchDB sidecars already mounted a tmpfs over theirs, and the images of DynamoDB Local, the echo and the app declare none. Method: `docker volume ls -q -f dangling=true` sorted and diffed before and after each run, and `docker events --since --until --filter type=volume --filter event=create` over the run. Results (count before to after, volume-create events, 0 in every row but the control): the default `tests/smoke` run 222 to 222; the flagged single-spec runs of Firebird, libSQL, CouchDB and DynamoDB Local 222 to 222 each; a deliberately failing flagged run (one assertion of the Firebird spec inverted, then restored; the run exited 1) 222 to 222; the five gates (`--repeat-each=10 --workers=4` of the four sidecar specs with the flag, and of `tests/smoke` without it) 223 to 223 each, and the Firebird gate on `lowcoderorg/lowcoder-ce:3.0.1-e2e` 223 to 223; in none of them did the list gain a name. A control, the pinned PostgreSQL image started without the tmpfs and then removed, logged exactly one create event and took the count from 222 to 223 (the new name was in the diff), so the method does see a leak. The count of the machine drifted between sessions (222, then 223) because of unrelated Docker activity, so only before/after pairs taken close together are evidence, not the absolute numbers. The 130 or more dangling volumes of earlier runs were not touched; `docker volume ls -q -f dangling=true` lists them, and it may list other projects' volumes, so delete them only knowing whose they are. With the flag, `--grep @node-service-sidecar` ran all the sidecar tests (D12, D13, D14) in one run when D14 landed: 32 passed; D15 was run through its own gate above, not in that combined run. After the four readiness loops got their elapsed-time deadline, `tests/datasource/plugin-firebird.spec.ts` (11), `plugin-turso-libsql.spec.ts` (11) and `plugin-couchdb.spec.ts` (10) each ran once on `3.0.0-e2e` with the flag and passed, and the D15 gate above was repeated (120 passed on both images). These Docker results were measured by hand on one machine; no result files are committed, so re-run the commands named here to reproduce them.): -default **850 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **864 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **855 in 114**; with both of those **869 in 115**; -with `E2E_INCLUDE_INSERT_ALL=1` **962 in 115**; with all three opt-in variables **981 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **894 in 118** (the 11 D12 tests of the Firebird sidecar, the 11 D13 tests of the libSQL sidecar, the 10 D14 tests of the CouchDB sidecar and the 12 D15 tests of the DynamoDB Local sidecar, which no other variable lists), and **1025 in 120** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: +Counts (re-measured 2026-11-25 with `LOWCODER_BASE_URL=http://localhost:1 ./node_modules/.bin/playwright test --list --reporter=list` from `e2e/`; this is a static listing, not a Docker run. Docker evidence: (1) the "confirmed in the combined run" notes of the security and lifecycle rows below come from an earlier run against an image built from the security-fix branch (tag `secfix-combined-e2e`, 693 of 696 default tests passed); that run predates the node-service specs (D3 to D10) and says nothing about them. (2) The full default run of the 859-test suite after the S3 sidecar scenarios (D16) landed, `e2e/scripts/run-in-docker.sh` without arguments on the default image `3.0.0-e2e` (no variable set): 44 failed, 815 passed (6.8 min). It started no Firebird, libSQL, CouchDB, DynamoDB Local or S3 container (the script's log shows only the PostgreSQL, echo and app `Starting` lines; a default `tests/smoke` run watched with a container sampler (one `docker ps` every 0.3 s) showed the PostgreSQL, echo, app and runner containers only) and ran no D12 to D16 test (they are not in the listing). The baseline from a clean `git worktree` of the previous commit (850 tests, same command and image, run before the edits): 45 failed, 805 passed (6.7 min). The failing sets are identical except one test (compared by test name, 45 against 44 lines): `components/media.spec.ts` S12 "carousel shows its two slides and the second dot fires change" failed in the baseline and passed in this run (it is not related to the node-service work and was not re-run to see whether it is intermittent). By tag the 44 failures are 25 `@security`, 17 `@lifecycle` (LC-PW02 of them also `@core`), 1 more `@core` (`apps/card-menu.spec.ts` export and import) and 1 `@npm` (`components/npm-components.spec.ts` calendar, also `@slow`), the same as the baseline's apart from the carousel test; the security and lifecycle ones depend on security fixes the unfixed image lacks (classified by tag, not analysed one by one). `SEC-R09d` failed in both runs (it is intermittent: it passed in earlier full runs); the periodic trigger test of `logic/triggers.spec.ts` failed in neither. The ten extra passes are the nine new unit tests of `foundation/node-plugins.spec.ts` and the carousel test. No node-service scenario failed. The D12, D13 and D14 evidence is a separate gate each, `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 `: for `tests/datasource/plugin-firebird.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D12 landed), for `tests/datasource/plugin-turso-libsql.spec.ts` 110 passed on `3.0.0-e2e` and 110 passed on `3.0.1-e2e` (measured when D13 landed), for `tests/datasource/plugin-couchdb.spec.ts` 100 passed on `3.0.0-e2e` and 100 passed on `3.0.1-e2e`, and after the readiness probes got their time limits 110 passed for the Firebird spec and 110 for the libSQL spec on `3.0.0-e2e` (all three sidecars start; the app was ready 15 s after the first container started with the flag against 14 s without it). For `tests/datasource/plugin-dynamodb-local.spec.ts` (D15) 120 passed on `3.0.0-e2e` and 120 passed on `3.0.1-e2e`, run after the last change of the spec (all four sidecars start; `docker events` showed the PostgreSQL, echo, Firebird, libSQL, CouchDB and DynamoDB Local containers created within one second, and the script logged every readiness wait as `ready after 0s`, the last one three seconds after the first container was created; the readiness waits run after the app container is started, so they do not delay it). Dangling volumes, measured by hand on one machine (no artifact is committed): before the PostgreSQL and Firebird sidecars got a tmpfs over their declared data volumes (`/var/lib/postgresql/data`, `/var/lib/firebird/data`), a default run left one anonymous volume (PostgreSQL's) and a flagged run two (PostgreSQL's and Firebird's); the libSQL and CouchDB sidecars already mounted a tmpfs over theirs, and the images of DynamoDB Local, the echo and the app declare none. Method: `docker volume ls -q -f dangling=true` sorted and diffed before and after each run, and `docker events --since --until --filter type=volume --filter event=create` over the run. Results (count before to after, volume-create events, 0 in every row but the control): the default `tests/smoke` run 222 to 222; the flagged single-spec runs of Firebird, libSQL, CouchDB and DynamoDB Local 222 to 222 each; a deliberately failing flagged run (one assertion of the Firebird spec inverted, then restored; the run exited 1) 222 to 222; the five gates (`--repeat-each=10 --workers=4` of the four sidecar specs with the flag, and of `tests/smoke` without it) 223 to 223 each, and the Firebird gate on `lowcoderorg/lowcoder-ce:3.0.1-e2e` 223 to 223; in none of them did the list gain a name. A control, the pinned PostgreSQL image started without the tmpfs and then removed, logged exactly one create event and took the count from 222 to 223 (the new name was in the diff), so the method does see a leak. The count of the machine drifted between sessions (222, then 223) because of unrelated Docker activity, so only before/after pairs taken close together are evidence, not the absolute numbers. The 130 or more dangling volumes of earlier runs were not touched; `docker volume ls -q -f dangling=true` lists them, and it may list other projects' volumes, so delete them only knowing whose they are. With the flag, `--grep @node-service-sidecar` ran all the sidecar tests (D12, D13, D14) in one run when D14 landed: 32 passed; D15 was run through its own gate above, not in that combined run. After the four readiness loops got their elapsed-time deadline, `tests/datasource/plugin-firebird.spec.ts` (11), `plugin-turso-libsql.spec.ts` (11) and `plugin-couchdb.spec.ts` (10) each ran once on `3.0.0-e2e` with the flag and passed, and the D15 gate above was repeated (120 passed on both images). For `tests/datasource/plugin-s3-server.spec.ts` (D16) `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 e2e/scripts/run-in-docker.sh --repeat-each=10 --workers=4 tests/datasource/plugin-s3-server.spec.ts`: 150 passed on `3.0.0-e2e` (34.8 s) and 150 passed on `lowcoderorg/lowcoder-ce:3.0.1-e2e` (36.0 s) (all five sidecars start; the script logged every readiness wait as `ready after 0s` or `1s`). With the flag, `--grep @node-service-sidecar --workers=4` ran all five sidecar specs in one run: 59 passed (D12 11, D13 11, D14 10, D15 12, D16 15; 16.9 s). Ten inverted assertions of the D16 spec (the wrong-secret message, a bucket listed after its create, the stored content type, the limited listing, the truncated answer, the deleted key's status, the tampered-signature code, the missing-key message, the empty-bucket message and the large body's size) failed in one run and the restored file passed again; six deliberate changes of the run script (the S3 loop back to the sleep-only counter, its accepted status widened, its abort limit removed, one tmpfs removed, the trap's container removed, a network alias added) made five structural tests fail, and three changes of `src/datasource/s3.ts` (the string to sign, the IPv4 check, the key encoding) made three unit tests fail; each was restored and checked by checksum. A deliberately failing flagged run (one D16h assertion inverted, restored afterwards) ended with the run exiting 1, no container and no network left (`docker ps -a` and `docker network ls` filtered on the run's name prefix: 0 and 0). A default `tests/smoke` run, the flagged hold run that made the hand measurements above, and that failing flagged run each took the dangling-volume count from 223 to 223 with no volume-create event (`docker events`), and the new names diff was empty. These Docker results were measured by hand on one machine; no result files are committed, so re-run the commands named here to reproduce them.): +default **859 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **873 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **864 in 114**; with both of those **878 in 115**; +with `E2E_INCLUDE_INSERT_ALL=1` **971 in 115**; with all three opt-in variables **990 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **918 in 119** (the 11 D12 tests of the Firebird sidecar, the 11 D13 tests of the libSQL sidecar, the 10 D14 tests of the CouchDB sidecar, the 12 D15 tests of the DynamoDB Local sidecar and the 15 D16 tests of the S3 sidecar, which no other variable lists), and **1049 in 121** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 145 in 10 files (the 54 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **189 in 14 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests, the 11 D13 tests, the 10 D14 tests and the 12 D15 tests); `@node-service-sidecar` 0 (**44 in 4 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests, D13a to D13k, the libSQL sidecar tests, D14a to D14j, the CouchDB sidecar tests, and D15a to D15l, the DynamoDB Local sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 154 in 10 files (the 63 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **213 in 15 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests, the 11 D13 tests, the 10 D14 tests, the 12 D15 tests and the 15 D16 tests); `@node-service-sidecar` 0 (**59 in 5 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests, D13a to D13k, the libSQL sidecar tests, D14a to D14j, the CouchDB sidecar tests, D15a to D15l, the DynamoDB Local sidecar tests, and D16a to D16o, the S3 sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -374,6 +384,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/plugin-turso-libsql.spec.ts | D13: the Turso plugin against the opt-in libSQL sidecar (sqld 0.24.33 with a JWT key; the data source URL is `http://e2e-libsql:8080`, the recorded `turso` form body with the sidecar's URL and token written over it; each test makes its own table `e2e_t_`). Measured on 3.0.0-e2e and 3.0.1-e2e. D13a CREATE, two INSERTs and a SELECT: a CREATE and an INSERT answer `[]`, the empty table answers `[]` before the inserts, then `integer` is a number, `real` 2 stays 2, a `boolean` column written in lower case is `true`/`false`, a `datetime` text is the ISO text of a `Date` (`2024-01-02T03:04:05.000Z`), NULL is `null`; D13b `includeRaw` answers `values` and the server's `raw` (columns with their declared types, cells such as `{type:"integer", value:"7"}`, the counters; the timing is only checked to be a number); D13c an INSERT answers `[]` with and without `includeRaw`, its raw result has `affected_row_count` 1 and `last_insert_rowid` `"2"` (a string) for the second row; D13d a blob cell is missing from the row (`[{id: 1}]`) while `includeRaw` shows the server sent `{type:"blob", base64:"AP8Q"}` (NSD-14 candidate); D13e `SELECT 9007199254740993` answers 9007199254740992 while the raw cell is the exact string (NSD-15 candidate); D13f `SELEC 1`, an unknown column, a duplicate key and `SELECT 1; SELECT 2` are errors of the server with codes `SQL_PARSE_ERROR`, `SQL_INPUT_ERROR`, `SQLITE_CONSTRAINT` and `SQL_MANY_STATEMENTS` (read by direct calls), and every one of them reaches the app as `Cannot parse result, received error: [object Object]` (NSD-1 candidate; a valid query of the same app succeeds first); D13g a token signed by another key and a string that is no JWT fail with `Failed to execute query. Endpoint returned 401: Unauthorized.` (the sidecar's own token reads the row first; direct calls show the server's `The JWT is invalid` and, without a header, `Expected authorization header but none given`); D13h a read-only token reads, its INSERT fails with `Endpoint returned 403: Forbidden.` and writes nothing (the read-write token then inserts the same row); D13i the published view shows a row after a click; D13j a URL with a trailing slash fails with `Endpoint returned 404: Not Found.` (the plugin builds `//v2/pipeline`; the same URL without it works); D13k the runner reaches the sidecar over HTTP and TCP, a closed port of the same host is refused. Limits: the `libsql://` to `https://` rewrite, a stream with a baton, and Turso's cloud features are not covered | @node-service @node-service-sidecar (opt-in) | 11 | | datasource/plugin-couchdb.spec.ts | D14: the CouchDB plugin against the opt-in CouchDB sidecar (Apache CouchDB 3.5.1; the data source URL is `http://e2e-couchdb:5984`; the recorded `couchdb` form body with the sidecar's URL and admin written over it; each test makes its own database `e2e_couch_` and removes it). Measured on 3.0.0-e2e and 3.0.1-e2e. D14a a database is created (`{ok: true}`), listed by a key range (`[]` before, `[]` after), described (`GET /`: the member set of 3.5.1, `doc_count` 0), and deleted, with direct reads of the server at each step; D14b a document is created (`{ok, id, rev: 1-...}`), read (`{_id, _rev, ...body}`), updated with `rev` as a query parameter (`2-...`), read at its first revision, listed with `include_docs`, and deleted (`3-...`; the server then answers `deleted`), and the server's own copy matches; D14c a stale revision (query parameter and `If-Match`, on write and delete) and a write without a revision answer `{error: "conflict", reason: "Document update conflict."}` as the data of a SUCCESSFUL query (the server's status is 409), change nothing, and the current revision is accepted by a write and by both kinds of delete (NSD-4 candidate); D14d a missing document, a document of a missing database, the information and the delete of a missing database (404 bodies) and a create of an existing database (412 `file_exists`) are successful queries with the error body as the data (NSD-4 candidate), with successful controls through the same operations (an existing document is read, an existing database is described and deleted, a new one is created); D14e a wrong password answers `{error: "unauthorized", reason: "Name or password is incorrect."}` as the data of a successful query and the refused create made no database, while the right password on the same queries lists and creates (NSD-4 candidate; the account is a second admin the test makes); D14f `docGet` with an empty `If-None-Match` fails with the plugin's own `Required parameter If-None-Match is not provided` (the server reads the same document without the header), a value that is not the current ETag reads the document, and the current ETag (the server answers 304) fails with `status: 304` (NSD-16 candidate); D14g `startkey`/`endkey`, `descending`, `skip` and `limit` give the lists the server gives, for databases and for the documents of a database (`total_rows` counts all of them), and an unscoped list holds the three system databases and the test's own; D14h the published view shows the document's title after a click; D14i the runner reaches the sidecar over HTTP and TCP (`Welcome`, version 3.5.1, `_all_dbs` needs credentials), a closed port of the same host is refused; D14j five wrong passwords of an account are 401 bodies, the sixth and the right password after them are the lockout's 403 body as the data of a successful query (the runner, another client address, is not locked until it fails five times itself, then the server's own status is 403) (NSD-4 candidate). Limits: JWT and cookie authentication, replication, design documents, partitions, attachments and bulk operations are not covered | @node-service @node-service-sidecar (opt-in) | 10 | | datasource/plugin-dynamodb-local.spec.ts | D15: the DynamoDB plugin against the opt-in DynamoDB Local sidecar (DynamoDB Local 3.3.2, `-inMemory -sharedDb`; the endpoint is `http://e2e-dynamodb:8000`; the recorded `dynamodb` form body with the sidecar's endpoint and throw-away key written over it; each test makes its own tables `e2e_ddb_` and removes them). Measured on 3.0.0-e2e and 3.0.1-e2e. D15a to D15l as in the catalogue (D15): table create, list and paging, the typed round trip of every type, Query and Scan with pagination keys, UpdateItem and DeleteItem with conditions and `ReturnValues`, the server's error messages, sets, binary and big numbers, the plain `ExclusiveStartKey`, any access key and a closed port, the published view, and the runner's reach. NSD-17 to NSD-20 candidates are characterised and annotated. Not covered: indexes, transactions, batch operations, streams, TTL, the signature (the server does not verify it) | @node-service @node-service-sidecar (opt-in) | 12 | +| datasource/plugin-s3-server.spec.ts | D16: the S3 plugin against the opt-in S3 sidecar (versitygw v1.11.0 with its POSIX backend in tmpfs; the endpoint is the sidecar's IP address `http://:7070`, never a name; the recorded `s3` form body and the five recorded queries with the sidecar's endpoint and throw-away key pair written over them; each test makes its own bucket `e2e-s3-` INSIDE its `try` and removes its objects and the bucket in the `finally`; direct signed calls from the test process, `s3Direct`, are the controls that show what the server holds). Measured on 3.0.0-e2e and 3.0.1-e2e. D16a to D16o as in the catalogue (D16). NSD-8, NSD-21, NSD-22, NSD-23 and NSD-24 candidates are characterised and annotated. Not covered: a real AWS S3 (the server differs in limits, versioning, ACLs, storage classes and checksums), multipart upload, an expired presigned URL | @node-service @node-service-sidecar (opt-in) | 15 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -524,8 +535,8 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i |---|---|---|---| | foundation/builders.spec.ts | every DSL builder's output shape, and the n8n recordings with `n8nWorkflowsQuery` | none | 40 | | foundation/recorded.spec.ts | recorded-fixture parsing and errors | none | 5 | -| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization`, and the Firebird sidecar helpers: `firebirdConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the firebird recordings (form fields with the sidecar's values, one query, no session value), `fixtures/firebird/init.sql` equals `FIREBIRD_ITEMS`, the script's Firebird constants equal `FIREBIRD`, and the run script starts, waits for and passes the sidecar only inside `if node_service_sidecars_enabled`; and the libSQL sidecar helpers: `libsqlConnection` (reads the host variable, builds the plain-HTTP URL, throws a named error when it is unset or empty), the script's libSQL values equal `LIBSQL` (alias, port, public key, token, an image pinned by tag and digest, the tmpfs data directory), the three tokens are JWTs with the claims they are named for and only the two sidecar ones verify under the sidecar's key (the foreign one is well-formed and does not), the script starts and waits for the libSQL sidecar only under the flag and appends its `--add-host` and host variable to the Firebird ones, and `libsqlDirect` against a local server (the pipeline body, the bearer header or none, a JSON or a text body); and the CouchDB sidecar helpers: `couchdbConnection` (reads the host variable, builds the plain-HTTP URL with the admin, throws a named error when it is unset or empty), the script's CouchDB values equal `COUCHDB` (alias, port, admin, the system databases, an image pinned by tag and digest, the tmpfs data directory), the script starts and waits for the CouchDB sidecar only under the flag, appends its `--add-host` and host variable to the others, bounds the wait by `STARTUP_TIMEOUT` and removes the container in the trap, the CouchDB recordings (one per operation: action name, the form's fields in order, every value the editor's empty default, no session value, no sidecar address), and `couchdbDirect` and `couchdbAdmin` against a local server (method, path, JSON body, extra headers, Basic credentials or none, a JSON or a text body), and the readiness steps of the script (every CouchDB readiness curl carries a connect and a total time limit, the system-database PUT counts only on 201 or 412, the libSQL fetch and the Firebird isql are bounded too), and the DynamoDB Local sidecar helpers: `dynamodbConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the script's DynamoDB values equal `DYNAMODB` (alias, port, image pinned by tag and digest, `-inMemory -sharedDb`), the start and wait steps run only under the flag and the host variable is named once, the readiness call has the abort limit, accepts exactly status 200 and needs a `TableNames` member, the eight dynamodb query recordings (one per action, no session value), the readiness loops of all four sidecars (elapsed-time deadline from `SECONDS`, compared with `STARTUP_TIMEOUT` after every failed probe; a loop that adds up its sleeps only fails), the DynamoDB probe parses the body as JSON and needs a `TableNames` array, and every `docker run` or `docker create` of the script, found whatever its flag order or line continuation, mounts a tmpfs over each volume its image declares, or is the foreground runner started with `--rm` (the discovery itself is tested on awkward forms; the facts are constants of the test, measured with `docker inspect`; PostgreSQL and Firebird lose their mount: it fails), and `dynamodbDirect` against a local server (method, path, target header, content type, typed body, credential scope, a JSON or a text answer) | @node-service | 54 | -| foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources), `@node-service-sidecar` (excluded by default, included by `E2E_INCLUDE_NODE_SERVICE_SIDECARS`, independent of the other flags, never selected on the enterprise and signup-disabled stacks), and the guard that every test of a spec that calls `firebirdConnection`, `libsqlConnection`, `couchdbConnection` or `dynamodbConnection` carries `@node-service-sidecar` (same parsing; synthetic sources; the specs that use a helper are the CouchDB, DynamoDB Local, Firebird and libSQL ones) | none | 32 | +| foundation/node-plugins.spec.ts | the node-service data source helpers (no stack): `parsePluginRecording` (wrong type, missing `comp.actionName`), `recordedPluginQuery` and `recordedPluginDatasource` errors, `nodePluginQuery` (action merge, recording unchanged), `nodePluginDatasourceBody`, `nodePluginIdsOf`, `NODE_PLUGIN_IDS`, the data source routes, and `createNodePluginDatasource`, `testDatasourceRaw`, `pluginDynamicConfigRaw` (method, path, body and answer handling) against a local server; the duckdb, turso, slack, gitlab, shopify and openApi recordings (type, action, placeholder host, the spec the form stored equals `OPEN_API_FIXTURE_SPEC`, no session value), the couchdb, jira, datadog, woocommerce and supabaseApi recordings (form fields, placeholders, recorded operation, no session value), the lowcoder, OpenAI, apiTemplate, carboneIo and uiPath recordings (same checks; uiPath's query is built by hand), the dynamodb, s3 and supabase recordings (form fields, placeholders, one query per action, no session value), `recordedPluginQuery` with a variant, `parseBasicAuthorization`, and `parseSigV4Authorization`, and the Firebird sidecar helpers: `firebirdConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the firebird recordings (form fields with the sidecar's values, one query, no session value), `fixtures/firebird/init.sql` equals `FIREBIRD_ITEMS`, the script's Firebird constants equal `FIREBIRD`, and the run script starts, waits for and passes the sidecar only inside `if node_service_sidecars_enabled`; and the libSQL sidecar helpers: `libsqlConnection` (reads the host variable, builds the plain-HTTP URL, throws a named error when it is unset or empty), the script's libSQL values equal `LIBSQL` (alias, port, public key, token, an image pinned by tag and digest, the tmpfs data directory), the three tokens are JWTs with the claims they are named for and only the two sidecar ones verify under the sidecar's key (the foreign one is well-formed and does not), the script starts and waits for the libSQL sidecar only under the flag and appends its `--add-host` and host variable to the Firebird ones, and `libsqlDirect` against a local server (the pipeline body, the bearer header or none, a JSON or a text body); and the CouchDB sidecar helpers: `couchdbConnection` (reads the host variable, builds the plain-HTTP URL with the admin, throws a named error when it is unset or empty), the script's CouchDB values equal `COUCHDB` (alias, port, admin, the system databases, an image pinned by tag and digest, the tmpfs data directory), the script starts and waits for the CouchDB sidecar only under the flag, appends its `--add-host` and host variable to the others, bounds the wait by `STARTUP_TIMEOUT` and removes the container in the trap, the CouchDB recordings (one per operation: action name, the form's fields in order, every value the editor's empty default, no session value, no sidecar address), and `couchdbDirect` and `couchdbAdmin` against a local server (method, path, JSON body, extra headers, Basic credentials or none, a JSON or a text body), and the readiness steps of the script (every CouchDB readiness curl carries a connect and a total time limit, the system-database PUT counts only on 201 or 412, the libSQL fetch and the Firebird isql are bounded too), and the DynamoDB Local sidecar helpers: `dynamodbConnection` (reads the host variable, throws a named error that names the variable and the flag when it is unset or empty), the script's DynamoDB values equal `DYNAMODB` (alias, port, image pinned by tag and digest, `-inMemory -sharedDb`), the start and wait steps run only under the flag and the host variable is named once, the readiness call has the abort limit, accepts exactly status 200 and needs a `TableNames` member, the eight dynamodb query recordings (one per action, no session value), the readiness loops of all five sidecars (elapsed-time deadline from `SECONDS`, compared with `STARTUP_TIMEOUT` after every failed probe; a loop that adds up its sleeps only fails), the DynamoDB probe parses the body as JSON and needs a `TableNames` array, and every `docker run` or `docker create` of the script, found whatever its flag order or line continuation, mounts a tmpfs over each volume its image declares, or is the foreground runner started with `--rm` (the discovery itself is tested on awkward forms; the facts are constants of the test, measured with `docker inspect`; PostgreSQL and Firebird lose their mount: it fails; for the S3 sidecar the two paths are directories the script chose, as its image declares no volume), and `dynamodbDirect` against a local server (method, path, target header, content type, typed body, credential scope, a JSON or a text answer), and the S3 sidecar helpers: `s3Connection` (builds the plain-HTTP endpoint on the IP address from the environment, throws a named error that names the variable and the flag when it is unset or empty and another for every value that is not an IPv4 address), the script's S3 values equal `S3` (port, key pair, region, an image pinned by tag and digest), the S3 sidecar is reached by IP only (no network alias, no `--add-host`, the IP variable named once), starts, is waited for and is removed in the trap, only under the flag and after the DynamoDB Local one, the readiness call is one signed request with the abort limit and exactly one accepted status, the readiness loop of the S3 sidecar is in the elapsed-time test, the declared-volumes table lists the two tmpfs directories, `signS3Request` reproduces three examples of AWS's own Signature Version 4 documentation, `s3Path`, `s3Query`, `amzDate` and `xmlValues`, and `s3Direct`, `s3CreateBucket`, `s3DirectKeys` and `s3RemoveBucket` against a local server (signed path-style request, key, scope, signed headers, content hash, body, content type; the location constraint of a bucket create; a gone bucket is fine, any other refusal throws) | @node-service | 63 | +| foundation/run-selection.spec.ts | `grepInvertFor`, `grepFor`, `excludedTags`, `runFlagsFromEnv`, `stackProfileFromEnv` for the four opt-in flags and the stack profile (every flag combination on the default and enterprise stacks and the signup-disabled profile: SEC-E05 runs only with its own flag and then alone), and the guard that every `superAdmin` fixture test carries `@superadmin` (parses each spec with the TypeScript compiler: `test` and every local name bound to it, by an aliased import of the fixtures or of `@playwright/test` or by a `test.extend(...)` variable; `test.only/skip/fixme/fail`, hooks, tags on an enclosing `test.describe`; comments, titles and annotations never count; the guard itself is tested on synthetic sources), `@node-service-sidecar` (excluded by default, included by `E2E_INCLUDE_NODE_SERVICE_SIDECARS`, independent of the other flags, never selected on the enterprise and signup-disabled stacks), and the guard that every test of a spec that calls `firebirdConnection`, `libsqlConnection`, `couchdbConnection`, `dynamodbConnection` or `s3Connection` carries `@node-service-sidecar` (same parsing; synthetic sources; the specs that use a helper are the CouchDB, DynamoDB Local, Firebird, S3 and libSQL ones) | none | 32 | | foundation/media.spec.ts | media fixtures have the right signatures | none | 8 | | foundation/create-module.spec.ts | `createModule` request shape | none | 4 | | foundation/module-host.spec.ts | module created through the API works in a host; republish rules | none | 2 | @@ -571,7 +582,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-5 candidate | the WooCommerce plugin appends `wp-json/wc/v3` to a server URL unless it ends exactly in `/wc/v3`, so a server URL copied with a trailing slash (`/wp-json/wc/v3/`) is requested at `/wp-json/wc/v3/wp-json/wc/v3/products`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-data.spec.ts` D8h asserts today's behaviour (characterisation, default run), annotation `{type:"defect", description:"NSD-5 candidate"}`; it changes when a trailing slash is accepted | | NSD-6 candidate | the UiPath plugin cannot run: `getSchemaExample` (`plugins/openApi/util.ts`) recurses without end on a circular schema of the bundled document, so the query configuration (`POST /api/datasources/getPluginDynamicConfig`, path `$.queryConfig`) answers 500 / code 5000 `get dynamic config error` (the editor lists no operation and cannot save a UiPath query) and every query fails with `Maximum call stack size exceeded` before any request is sent; the cause (`RangeError: Maximum call stack size exceeded` at `getSchemaExample`, from a circular schema) was read in the app container's node-service log while recording, not asserted: the suite asserts only the HTTP 500 / code 5000 of the configuration request, the query's failure message and that no request is sent; measured on 3.0.0-e2e and 3.0.1-e2e. Whether UiPath sends its `Authorization` header (a doubled `Bearer`, or none) cannot be measured today. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9j and D9k assert today's behaviour after a control that another plugin reaches the echo / lists its operations (characterisation, default run), annotation `{type:"defect", description:"NSD-6 candidate"}`; D9l asserts the desired behaviour (`GET /odata/Folders` with `Authorization: Bearer ` exactly), `@quarantine`, same annotation; they change when the plugin runs | | NSD-7 candidate | an OpenAI data source on spec version `v1.0` (the version an empty choice selects) sends no `Authorization` header: the plugin hands the key over as `ApiKeyAuth.value`, the security scheme of the `v2.3` document, while the `v1.0` document names its scheme `ApiKey`; with `v2.3` the same key is sent as `Authorization: Bearer `; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9h asserts today's behaviour after a control that v2.3 sends the key to the same echo (characterisation, default run), annotation `{type:"defect", description:"NSD-7 candidate"}`; it changes when the key reaches the `v1.0` document's scheme | -| NSD-8 candidate | the S3 plugin checks the bucket itself only for `listObjects` (`Bucket is required`); `readFile`, `uploadData` and `deleteFile` with an empty bucket reach the AWS SDK, which refuses before any request with its own text `Empty value provided for input HTTP label: Bucket.`, so the user sees an SDK message and the checks are inconsistent; no request is sent in any of the four cases; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-aws-sdk.spec.ts` D10q asserts today's messages after a control that a call with a bucket reaches the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-8 candidate"}`; it changes when the three operations check the bucket like `listObjects` | +| NSD-8 candidate | the S3 plugin checks the bucket itself only for `listObjects` (`Bucket is required`); `readFile`, `uploadData` and `deleteFile` with an empty bucket reach the AWS SDK, which refuses before any request with its own text `Empty value provided for input HTTP label: Bucket.`, so the user sees an SDK message and the checks are inconsistent; no request is sent in any of the four cases; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-aws-sdk.spec.ts` D10q asserts today's messages after a control that a call with a bucket reaches the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-8 candidate"}`; it changes when the three operations check the bucket like `listObjects`. The same four messages are asserted against the S3 sidecar by `datasource/plugin-s3-server.spec.ts` D16l, next to a control that a call with a real bucket works and that nothing was stored | | NSD-9 candidate | a storage error answer of the Supabase Storage plugin (any status: 400, 401 and 404 measured) fails the query with `{"size":0,"timeout":0}`, the JSON of node-fetch's `Response`, not with the API's message (`e2e-storage-error` in the canned answer): storage-js recognises an HTTP error only as an instance of the global `Response`, and node-service's proxy fetch answers with node-fetch's class; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11n and D11o assert today's message after a control that the same query succeeds when the API answers 200 (characterisation, default run), annotation `{type:"defect", description:"NSD-9 candidate"}`; they change when the message of the answer reaches the user | | NSD-10 candidate | the Supabase Storage plugin sends the signed-URL validity as `expiresIn: Date.now() + 5 minutes` in milliseconds (13 digits, about 1.8e12 when measured), computed once when node-service loads the plugin, where the API takes seconds: every signing request of one node-service process carries the same number; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11f, D11k and D11m assert the magnitude (above 1e12, and within clock-skew and plugin-age allowances of now plus five minutes) and, in D11m, that two queries send the same value (characterisation, default run), annotation `{type:"defect", description:"NSD-10 candidate"}`; they change when the validity is 300 | | NSD-11 candidate | the `search` field of the Supabase Storage listObjects query is never sent: the request body is `{limit, offset, sortBy, prefix}` whatever the field holds; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11e asserts today's body after a positive control that the query's prefix travels (characterisation, default run), annotation `{type:"defect", description:"NSD-11 candidate"}`; it changes when the search text is sent | @@ -584,6 +595,10 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | NSD-18 candidate | the DynamoDB plugin writes every array of strings as a string set and every array of numbers as a number set (`dynamodb-data-types` `detectType`; only other arrays are lists), so a list of strings or numbers cannot be stored: the order is lost (`["zeta","alpha","mid"]` reads back `["alpha","mid","zeta"]`), duplicates fail the query (`Input collection [a, a] contains duplicates`) and an empty array fails with `An number set may not be empty` (sic, the server's text). An array of mixed values is a list and keeps its order. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15g, `defect` annotation `NSD-18 candidate` (characterisation, passes today next to the mixed array, which is a list); it changes when a list can be written | | NSD-19 candidate | the DynamoDB plugin reads a number with `Number()`, so a number beyond a double loses digits (`12345678901234567890` reads `12345678901234567000`; the server holds it exactly), and a binary attribute (`B`, `BS`) is read as a byte array that the answer's JSON turns into an object with index keys (`{"0":104,"1":101,...}`); a binary cannot be written either: a typed `{"B":"..."}` inside `Item` is wrapped like any object and stored as a map. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15h, `defect` annotation `NSD-19 candidate` (characterisation, passes today next to a direct read that shows the exact number and the binary); it changes when numbers and binaries are returned exactly | | NSD-20 candidate | an `ExclusiveStartKey` given in the plain form (`{"id": 1}`, as `Key` is written) is not wrapped (only `Key`, `Item` and `Items` are) and fails inside the SDK's serialiser with the JavaScript text `Cannot read properties of undefined (reading '0')` instead of a validation message; the typed form (`{"id": {"N": "1"}}`) works. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15i, `defect` annotation `NSD-20 candidate` (characterisation, passes today next to the typed form of the same key, which continues the read); it changes when the key is wrapped or refused with a message | +| NSD-21 candidate | `listObjects` cannot continue a listing: it sends ListObjects (version 1) with the prefix, the delimiter and `limit` as max-keys, no marker, and returns a bare array of objects, so when the bucket holds more keys than `limit` the user sees the first page without any sign that it was cut (the server answered `IsTruncated: true` and a continuation token, shown by a direct call). Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar. The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16f, `defect` annotation `NSD-21 candidate` (characterisation, passes today next to a control that the same query with a larger limit shows every key); it changes when a marker or a truncation flag is offered | +| NSD-22 candidate | `listObjects` with a delimiter returns only the `Contents` of the answer: the common prefixes ("folders") the server lists are dropped, so `delimiter: "/"` shows the keys of one level and none of the folders below it. Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar (control: a direct call answers one key and two common prefixes). The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16g, `defect` annotation `NSD-22 candidate` (characterisation, passes today); it changes when the common prefixes are returned | +| NSD-23 candidate | `uploadData` decodes `data` as base64 unless the encoding is `utf8` (the form's default is base64), and Node's decoder accepts text that is not base64: `hello world, this is not base64!` is stored as other bytes and the query succeeds, with no message (the same text with the text encoding is stored as typed). Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar. The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16n, `defect` annotation `NSD-23 candidate` (characterisation, passes today next to the text-encoding control); it changes when invalid base64 is refused | +| NSD-24 candidate | the `url` that `listObjects` and `uploadData` answer is the endpoint, the bucket and the key joined as they are (`getFileUrl`): a key with `?`, `#` or `%` names another resource, and a space or non-ASCII text is not a valid URL until a client encodes it (with the bucket private the plain `url` is refused anyway, 403 `AccessDenied`, while the presigned URL of the same object works). Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar. The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16j (the `url` of eight keys equals the unencoded join) and D16i (the plain `url` is refused, the presigned URL downloads), `defect` annotation `NSD-24 candidate` on D16j (characterisation, passes today); it changes when the key is encoded in the `url` | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/scripts/run-in-docker.sh b/e2e/scripts/run-in-docker.sh index 1fc99a6b8d..12fa50c1f0 100755 --- a/e2e/scripts/run-in-docker.sh +++ b/e2e/scripts/run-in-docker.sh @@ -24,8 +24,8 @@ ## E2E_INCLUDE_SUPERADMIN set to 1 to also run the @superadmin tests (SEC-R16a to SEC-R16d, the instance super admin; ## independent of the other flags). Run: E2E_INCLUDE_SUPERADMIN=1 $0 --grep @superadmin ## E2E_INCLUDE_NODE_SERVICE_SIDECARS set to 1 to also start the sidecars of the node-service data sources: real servers a plugin can be pointed at, for plugins -## whose protocol the echo cannot serve (Firebird: a wire protocol) or whose real behaviour the echo's canned answers say nothing about (libSQL, CouchDB, DynamoDB Local) -## (today a Firebird server, FIREBIRD_IMAGE below, a libSQL server, LIBSQL_IMAGE below, a CouchDB server, COUCHDB_IMAGE below, and a DynamoDB Local server, DYNAMODB_IMAGE below) and run their @node-service-sidecar tests; independent of the +## whose protocol the echo cannot serve (Firebird: a wire protocol) or whose real behaviour the echo's canned answers say nothing about (libSQL, CouchDB, DynamoDB Local, S3) +## (today a Firebird server, FIREBIRD_IMAGE below, a libSQL server, LIBSQL_IMAGE below, a CouchDB server, COUCHDB_IMAGE below, a DynamoDB Local server, DYNAMODB_IMAGE below, and an S3-compatible server, S3_IMAGE below) and run their @node-service-sidecar tests; independent of the ## other flags, default stack only (any other profile is an error). Without it the run starts none of them, ## neither lists nor runs those tests, and pulls no extra image. ## Run only these: E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 $0 --grep @node-service-sidecar @@ -46,6 +46,7 @@ ## LIBSQL_IMAGE libSQL server (sqld) sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS ## COUCHDB_IMAGE CouchDB sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS ## DYNAMODB_IMAGE DynamoDB Local sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS +## S3_IMAGE S3-compatible server (versitygw) sidecar of the @node-service-sidecar tests (pinned by tag and digest); used only with E2E_INCLUDE_NODE_SERVICE_SIDECARS ## E2E_HOST_PORT also publish the app on 127.0.0.1: to look at it in a browser while the run lasts ## ## Set by the script for each run (a value of the caller is overwritten; the password is new every run, never printed, @@ -104,6 +105,16 @@ ## every access key (`-inMemory -sharedDb`), checks no credential, and the image declares no volume, so `cleanup` removes everything however the run ends. The script waits until ## one real ListTables call, posted from the echo container over the run network, answers 200 with a `TableNames` member. Without the flag nothing of this runs. ## +## Only with E2E_INCLUDE_NODE_SERVICE_SIDECARS=1 it also starts an S3-compatible server sidecar (S3_IMAGE, versitygw with its POSIX backend) on port 7070: the target of the S3 data +## source of node-service (a real server that verifies AWS Signature Version 4 in place of the echo's canned answers). It starts after the DynamoDB Local sidecar. Unlike the others it +## has NO name alias and no `--add-host` entry: the AWS SDK addresses a bucket of an endpoint that is a host NAME as `.` (virtual-host style), a name no mapping covers +## and that may resolve outside the run network, whereas an endpoint that is an IP address is addressed path-style. So the app container and the runner reach the server BY ITS IP +## address on the run network, which this script knows when it starts the container and passes to the runner as E2E_S3_IP (like E2E_ECHO_IP). The root user is one throw-away +## access key and secret (S3_ACCESS_KEY and S3_SECRET_KEY, which must equal S3 in e2e/src/constants.ts); the server verifies the signature of every request and refuses a wrong key or +## secret. Objects and their metadata live in two tmpfs directories (S3_DATA_DIR, S3_META_DIR: the image declares no volume, and the metadata sidecar directory keeps the server from +## needing extended attributes on the data directory), so nothing outlives the container. The script waits until one real signed ListBuckets request, posted from the echo container to the +## IP address over the run network, answers 200 with a ListAllMyBucketsResult. Without the flag nothing of this runs. +## ## Not covered: Firefox and WebKit (only Chromium runs), the multi-container compose setup, databases other than ## PostgreSQL. ## @@ -186,6 +197,19 @@ readonly DYNAMODB_ALIAS="e2e-dynamodb" readonly DYNAMODB_PORT=8000 # The one status the readiness ListTables call counts as "there" readonly DYNAMODB_HTTP_OK=200 +# S3-compatible server (versitygw, POSIX backend) sidecar of the @node-service-sidecar tests, started only with E2E_INCLUDE_NODE_SERVICE_SIDECARS. The image is versity/versitygw v1.11.0 +# by tag and digest. It verifies AWS Signature Version 4 against one root user, the throw-away key pair below (must equal S3 in e2e/src/constants.ts; the foundation tests check it). +# S3_PORT is the gateway's default port. The image declares no volume; the script gives it two tmpfs directories of its own choosing (objects and the metadata sidecar), so nothing outlives the container. +readonly DEFAULT_S3_IMAGE="versity/versitygw:v1.11.0@sha256:8319a530d08d537426e2f855bae5280709795dc73a3f0c347973ef915d6343c5" +readonly S3_IMAGE="${S3_IMAGE:-$DEFAULT_S3_IMAGE}" +readonly S3_PORT=7070 +readonly S3_ACCESS_KEY="e2eS3Key" +readonly S3_SECRET_KEY="e2e-s3-secret-key" +readonly S3_REGION="us-west-1" +readonly S3_DATA_DIR="/data" +readonly S3_META_DIR="/meta" +# The one status the readiness ListBuckets call counts as "there" +readonly S3_HTTP_OK=200 # The instance super admin of the throw-away stack; the domain equals TEST_EMAIL_DOMAIN in e2e/src/constants.ts; the suite # reads the name from E2E_SUPERUSER_USERNAME (SUPER_ADMIN_ENV). The password is generated per run (generate_superuser_password). readonly SUPERUSER_USERNAME="e2e-superadmin@example.test" @@ -222,6 +246,7 @@ readonly FIREBIRD_CONTAINER="${NAME_PREFIX}-fb" readonly LIBSQL_CONTAINER="${NAME_PREFIX}-libsql" readonly COUCHDB_CONTAINER="${NAME_PREFIX}-couchdb" readonly DYNAMODB_CONTAINER="${NAME_PREFIX}-dynamodb" +readonly S3_CONTAINER="${NAME_PREFIX}-s3" # The alias and port the app container and the runner use; E2E_ECHO_URL below is built from them (the suite reads it by ECHO_ENV in e2e/src/constants.ts) readonly ECHO_ALIAS="e2e-echo" readonly ECHO_PORT=8080 @@ -231,7 +256,9 @@ readonly ECHO_HEALTH_PATH="/__e2e/health" readonly ECHO_SCRIPT="$SCRIPT_DIR/echo-server.js" # Set by start_echo: the sidecar's IP on the run network (used for --add-host of the app and the runner) ECHO_IP="" -# Set by start_firebird, start_libsql, start_couchdb and start_dynamodb (only with E2E_INCLUDE_NODE_SERVICE_SIDECARS): the extra `--add-host` and `-e` arguments of the app and the runner. Empty otherwise. +# Set by start_s3 (only with E2E_INCLUDE_NODE_SERVICE_SIDECARS): the S3 sidecar's IP on the run network (the sidecar has no alias: the endpoint of the S3 data source is this IP) +S3_IP="" +# Set by start_firebird, start_libsql, start_couchdb, start_dynamodb and start_s3 (only with E2E_INCLUDE_NODE_SERVICE_SIDECARS): the extra `--add-host` and `-e` arguments of the app and the runner. Empty otherwise. SIDECAR_ADD_HOST=() SIDECAR_RUNNER_ENV=() @@ -245,7 +272,7 @@ fail() { } cleanup() { - docker rm -f "$RUNNER_CONTAINER" "$APP_CONTAINER" "$POSTGRES_CONTAINER" "$ECHO_CONTAINER" "$FIREBIRD_CONTAINER" "$LIBSQL_CONTAINER" "$COUCHDB_CONTAINER" "$DYNAMODB_CONTAINER" > /dev/null 2>&1 || true + docker rm -f "$RUNNER_CONTAINER" "$APP_CONTAINER" "$POSTGRES_CONTAINER" "$ECHO_CONTAINER" "$FIREBIRD_CONTAINER" "$LIBSQL_CONTAINER" "$COUCHDB_CONTAINER" "$DYNAMODB_CONTAINER" "$S3_CONTAINER" > /dev/null 2>&1 || true docker network rm "$NETWORK" > /dev/null 2>&1 || true } trap cleanup EXIT @@ -531,6 +558,38 @@ wait_for_dynamodb() { log "DynamoDB Local sidecar ready after ${waited}s" } +# The gateway takes global flags before the backend subcommand: `--quiet` silences its request log, the POSIX backend gets a directory for objects and one for the metadata +# sidecar. The root user comes from the environment (the image's own variable names), not from the command line. +start_s3() { + log "Starting $S3_IMAGE as $S3_CONTAINER (IP only, no alias, port $S3_PORT)" + docker run -d --name "$S3_CONTAINER" --network "$NETWORK" \ + --tmpfs "$S3_DATA_DIR" --tmpfs "$S3_META_DIR" \ + -e ROOT_ACCESS_KEY_ID="$S3_ACCESS_KEY" -e ROOT_SECRET_ACCESS_KEY="$S3_SECRET_KEY" -e VGW_REGION="$S3_REGION" \ + "$S3_IMAGE" --port ":${S3_PORT}" --quiet posix --sidecar "$S3_META_DIR" "$S3_DATA_DIR" > /dev/null + S3_IP="$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$S3_CONTAINER")" + [ -n "$S3_IP" ] || fail "no IP address for $S3_CONTAINER on $NETWORK" + SIDECAR_RUNNER_ENV+=(-e "E2E_S3_IP=${S3_IP}") + log "S3 sidecar is $S3_IP:$S3_PORT" +} + +# One real, SIGNED ListBuckets request (the server refuses an unsigned or wrongly signed one) posted to the sidecar's IP over the run network from the echo container (the image has +# no curl and no shell tools of use; node signs with its own crypto module): ready when it answers exactly S3_HTTP_OK with a ListAllMyBucketsResult. The fetch aborts after the request +# limit, so a stalled request ends the attempt and the wait loop checks its deadline again. The key pair is handed over by the container's environment, not on a command line. +wait_for_s3() { + local waited=0 started=$SECONDS + local probe="const c = require('crypto'), h = (k, d) => c.createHmac('sha256', k).update(d).digest(), x = (d) => c.createHash('sha256').update(d).digest('hex'), e = process.env, host = e.S3_PROBE_HOST, now = new Date().toISOString().replace(/[:-]|[.][0-9]{3}/g, ''), day = now.slice(0, 8), scope = day + '/' + e.S3_PROBE_REGION + '/s3/aws4_request', empty = x(''), canonical = 'GET\\n/\\n\\nhost:' + host + '\\nx-amz-content-sha256:' + empty + '\\nx-amz-date:' + now + '\\n\\nhost;x-amz-content-sha256;x-amz-date\\n' + empty, signingKey = h(h(h(h('AWS4' + e.S3_PROBE_SECRET, day), e.S3_PROBE_REGION), 's3'), 'aws4_request'); fetch('http://' + host + '/', { signal: AbortSignal.timeout($((PROBE_REQUEST_TIMEOUT * 1000))), headers: { 'x-amz-date': now, 'x-amz-content-sha256': empty, Authorization: 'AWS4-HMAC-SHA256 Credential=' + e.S3_PROBE_KEY + '/' + scope + ', SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=' + h(signingKey, 'AWS4-HMAC-SHA256\\n' + now + '\\n' + scope + '\\n' + x(canonical)).toString('hex') } }).then((r) => r.text().then((t) => process.exit(r.status === $S3_HTTP_OK && t.includes(' process.exit(1))" + until docker exec -e S3_PROBE_HOST="${S3_IP}:${S3_PORT}" -e S3_PROBE_REGION="$S3_REGION" -e S3_PROBE_KEY="$S3_ACCESS_KEY" -e S3_PROBE_SECRET="$S3_SECRET_KEY" "$ECHO_CONTAINER" node -e "$probe" > /dev/null 2>&1; do + waited=$((SECONDS - started)) + if [ "$waited" -ge "$STARTUP_TIMEOUT" ]; then + docker logs --tail "$LOG_TAIL_LINES" "$S3_CONTAINER" >&2 || true + fail "the S3 sidecar did not become ready within ${STARTUP_TIMEOUT}s" + fi + sleep "$POLL_INTERVAL" + done + waited=$((SECONDS - started)) + log "S3 sidecar ready after ${waited}s" +} + wait_for_app() { local waited=0 log "Waiting for $READY_PATH (at most ${STARTUP_TIMEOUT}s)" @@ -600,6 +659,9 @@ fi if node_service_sidecars_enabled; then start_dynamodb fi +if node_service_sidecars_enabled; then + start_s3 +fi start_app wait_for_postgres wait_for_echo @@ -615,5 +677,8 @@ fi if node_service_sidecars_enabled; then wait_for_dynamodb fi +if node_service_sidecars_enabled; then + wait_for_s3 +fi wait_for_app run_tests "$@" diff --git a/e2e/src/constants.ts b/e2e/src/constants.ts index e1f2ed3f46..6d83ce07d6 100644 --- a/e2e/src/constants.ts +++ b/e2e/src/constants.ts @@ -223,7 +223,7 @@ export const TAGS = { * The node-service data source tests that need a real server of their own to be pointed at: the echo cannot serve the plugin's protocol (the Firebird tests, a * wire protocol, `tests/datasource/plugin-firebird.spec.ts`) or its canned answers say nothing about the real server's behaviour (the libSQL server tests, * `tests/datasource/plugin-turso-libsql.spec.ts`, the CouchDB server tests, `tests/datasource/plugin-couchdb.spec.ts`, and the DynamoDB Local server tests, - * `tests/datasource/plugin-dynamodb-local.spec.ts`). Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of + * `tests/datasource/plugin-dynamodb-local.spec.ts`, and the S3-compatible server tests, `tests/datasource/plugin-s3-server.spec.ts`). Worn NEXT TO `@node-service`. Opt-in like `@superadmin`: out of * the default run (neither listed nor run, and the run script starts no such sidecar), in only with * `E2E_INCLUDE_NODE_SERVICE_SIDECARS` (see src/run-selection.ts and scripts/run-in-docker.sh). */ @@ -238,7 +238,7 @@ export const RUN_FLAGS = { /** Enterprise profile only: run SEC-E05 (`@enterprise-takeover`) and nothing else. */ INCLUDE_ENTERPRISE_TAKEOVER: "E2E_INCLUDE_ENTERPRISE_TAKEOVER", /** - * Default stack only: also start the sidecars of the node-service data sources (Firebird, a libSQL server, a CouchDB server, a DynamoDB Local server) and run + * Default stack only: also start the sidecars of the node-service data sources (Firebird, a libSQL server, a CouchDB server, a DynamoDB Local server, an S3-compatible server) and run * their `@node-service-sidecar` tests. Without it the run starts none of them. */ INCLUDE_NODE_SERVICE_SIDECARS: "E2E_INCLUDE_NODE_SERVICE_SIDECARS", @@ -357,6 +357,21 @@ export const DYNAMODB = { REGION: "us-west-1", } as const; +/** + * The S3-compatible server sidecar (versitygw) that scripts/run-in-docker.sh starts on the run's network ONLY when `E2E_INCLUDE_NODE_SERVICE_SIDECARS` is set. Unlike the other + * sidecars it has NO host name alias: the AWS SDK addresses a bucket of an endpoint that is a host NAME as `.`, a name no mapping covers, and an endpoint that is + * an IP address path-style (`//`). The run script passes the sidecar's IP address on the run network (`IP_ENV`) and the app container and the runner + * reach the server by it. The server verifies AWS Signature Version 4 against one root user, `ACCESS_KEY` and `SECRET_KEY`: throw-away values that must equal the `S3_*` values of + * the script (the container is removed when the run ends and holds no other data), never real secrets. `REGION` is the region the server is started with. + */ +export const S3 = { + IP_ENV: "E2E_S3_IP", + PORT: 7070, + ACCESS_KEY: "e2eS3Key", + SECRET_KEY: "e2e-s3-secret-key", + REGION: "us-west-1", +} as const; + export const SEEDED_ITEM_NAMES = ["alpha", "beta"] as const; /** Component type, panel search text, drop position and generated name of the button the editor tests drop. */ diff --git a/e2e/src/datasource/s3.ts b/e2e/src/datasource/s3.ts new file mode 100644 index 0000000000..8b43c5454d --- /dev/null +++ b/e2e/src/datasource/s3.ts @@ -0,0 +1,218 @@ +import { createHash, createHmac } from "node:crypto"; +import { RUN_FLAGS, S3 } from "../constants"; +import { IPV4_PATTERN } from "../security/echo"; + +/** Where an S3 data source connects: the S3-compatible sidecar of the run, as the app container reaches it (by its IP address, over plain HTTP, path-style). */ +export interface S3Connection { + /** `http://:`, no trailing slash: the data source's endpoint URL. An IP address, never a name: the AWS SDK derives `.` from a name. */ + endpointUrl: string; + /** The root user of the sidecar; the server verifies the signature of every request against this pair. */ + accessKey: string; + secretKey: string; + region: string; +} + +/** The sidecar's IP variable is not set: the run did not start the S3 sidecar. */ +export class S3SidecarMissingError extends Error { + constructor() { + super(`${S3.IP_ENV} is not set: the S3 sidecar was not started. Run the suite through e2e/scripts/run-in-docker.sh with ${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}=1.`); + this.name = "S3SidecarMissingError"; + } +} + +/** The sidecar's IP variable holds something that is not an IPv4 address: a name would make the SDK address `.`. */ +export class S3SidecarAddressError extends Error { + constructor(value: string) { + super(`${S3.IP_ENV} is not an IPv4 address: ${JSON.stringify(value)} (a host name would make the AWS SDK address a bucket as .)`); + this.name = "S3SidecarAddressError"; + } +} + +/** + * The connection to the run's S3 sidecar from the environment. Throws `S3SidecarMissingError` when the run script did not set the IP variable (it does so only with + * `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`), so a test that was selected without its sidecar fails loudly instead of passing vacuously, and `S3SidecarAddressError` when the + * value is not an IPv4 address (the endpoint of a bucket call must be an IP address, see `S3`). Reads only `env`. + */ +export function s3Connection(env: NodeJS.ProcessEnv = process.env): S3Connection { + const ip = env[S3.IP_ENV]; + if (!ip) throw new S3SidecarMissingError(); + if (!IPV4_PATTERN.test(ip)) throw new S3SidecarAddressError(ip); + return { endpointUrl: `http://${ip}:${S3.PORT}`, accessKey: S3.ACCESS_KEY, secretKey: S3.SECRET_KEY, region: S3.REGION }; +} + +/** The signing algorithm and the service of the credential scope, and the header names a signature of this module covers. */ +const SIGV4_ALGORITHM = "AWS4-HMAC-SHA256"; +const SIGV4_SERVICE = "s3"; +const SIGV4_TERMINATOR = "aws4_request"; + +function sha256Hex(data: Buffer | string): string { + return createHash("sha256").update(data).digest("hex"); +} + +function hmac(key: Buffer | string, data: string): Buffer { + return createHmac("sha256", key).update(data).digest(); +} + +/** `20130524T000000Z`: the `x-amz-date` form of an instant. */ +export function amzDate(date: Date): string { + return date.toISOString().replace(/[:-]|\.\d{3}/g, ""); +} + +/** One S3 request to sign (AWS Signature Version 4, header form). `path` and `query` are already in their canonical, URI-encoded form. */ +export interface S3SignInput { + method: string; + host: string; + /** The URI-encoded path, starting with "/". */ + path: string; + /** The canonical query string: keys sorted, keys and values URI-encoded; empty for none. */ + query: string; + /** Further headers to sign (lower-case names; a value is trimmed and its runs of whitespace collapsed to one space, as SigV4 requires). `host`, `x-amz-date` and `x-amz-content-sha256` are always signed and added. */ + headers: Record; + body: Buffer; + accessKey: string; + secretKey: string; + region: string; + now: Date; +} + +/** + * The headers a signed request carries: the given ones plus `host`, `x-amz-date`, `x-amz-content-sha256` and the `authorization` header. Follows the AWS Signature + * Version 4 specification for S3 (the canonical path is the path as sent, encoded once; the payload hash is the hex SHA-256 of the body); the foundation tests check it against the + * example of AWS's own documentation. Not covered: presigned (query) signatures, chunked or unsigned payloads, a session token. + */ +export function signS3Request(input: S3SignInput): Record { + const payloadHash = sha256Hex(input.body); + const stamp = amzDate(input.now); + const day = stamp.slice(0, 8); + const headers: Record = { ...input.headers, host: input.host, "x-amz-content-sha256": payloadHash, "x-amz-date": stamp }; + const names = Object.keys(headers).sort(); + const canonicalHeaders = names.map((name) => `${name}:${(headers[name] as string).trim().replace(/\s+/g, " ")}\n`).join(""); + const signedHeaders = names.join(";"); + const canonicalRequest = [input.method, input.path, input.query, canonicalHeaders, signedHeaders, payloadHash].join("\n"); + const scope = `${day}/${input.region}/${SIGV4_SERVICE}/${SIGV4_TERMINATOR}`; + const stringToSign = [SIGV4_ALGORITHM, stamp, scope, sha256Hex(canonicalRequest)].join("\n"); + const signingKey = hmac(hmac(hmac(hmac(`AWS4${input.secretKey}`, day), input.region), SIGV4_SERVICE), SIGV4_TERMINATOR); + const signature = hmac(signingKey, stringToSign).toString("hex"); + return { ...headers, authorization: `${SIGV4_ALGORITHM} Credential=${input.accessKey}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}` }; +} + +/** One URI-encoded path segment: everything but the unreserved characters is percent-encoded (`encodeURIComponent` leaves `!'()*`, which S3 wants encoded). */ +function encodeSegment(segment: string): string { + return encodeURIComponent(segment).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`); +} + +/** The path of a bucket, or of an object of it: `/` or `//`, the key encoded per `/`-separated segment. The key must have no `.` or `..` segment (a URL parser would resolve it). */ +export function s3Path(bucket?: string, key?: string): string { + if (bucket === undefined) return "/"; + if (key === undefined) return `/${encodeSegment(bucket)}`; + return `/${encodeSegment(bucket)}/${key.split("/").map(encodeSegment).join("/")}`; +} + +/** The canonical query string of the given parameters: names and values URI-encoded, then sorted by encoded name (then value). */ +export function s3Query(params: Record = {}): string { + // sorted AFTER encoding: SigV4 orders the encoded names (`a%2F` sorts before `a-`, the raw `a-` before `a/`) + return Object.keys(params) + .map((name) => [encodeSegment(name), encodeSegment(params[name] as string)] as const) + .sort(([nameA, valueA], [nameB, valueB]) => (nameA < nameB ? -1 : nameA > nameB ? 1 : valueA < valueB ? -1 : valueA > valueB ? 1 : 0)) + .map(([name, value]) => `${name}=${value}`) + .join("&"); +} + +/** How long a direct call to the sidecar may take before it is abandoned: a local server answers in milliseconds. */ +const DIRECT_CALL_TIMEOUT_MS = 10_000; + +/** One direct call from the test process: the verb, the bucket and key it addresses, a query, a body and a content type; `credentials` replaces the connection's key pair. */ +export interface S3DirectRequest { + method: "GET" | "PUT" | "DELETE" | "HEAD"; + bucket?: string; + key?: string; + query?: Record; + body?: Buffer | string; + contentType?: string; + credentials?: { accessKey: string; secretKey: string }; +} + +/** The answer of a direct call: the HTTP status, the headers (lower-case names), the body as bytes and as UTF-8 text. */ +export interface S3DirectAnswer { + status: number; + headers: Record; + body: Buffer; + text: string; +} + +/** + * One signed S3 call from the TEST process to the sidecar, path-style on the connection's IP address. It is the control that shows what the server itself holds and answers (the + * same bytes, content type and status the plugin sees), and the way a test makes and removes its own buckets and objects. Throws on a network failure or after 10 s; an HTTP error + * status is returned, not thrown. + */ +export async function s3Direct(connection: Pick, request: S3DirectRequest): Promise { + const body = Buffer.from(request.body ?? ""); + const path = s3Path(request.bucket, request.key); + const query = s3Query(request.query); + const url = new URL(`${path}${query ? `?${query}` : ""}`, connection.endpointUrl); + const headers = signS3Request({ + method: request.method, + host: url.host, + path, + query, + headers: request.contentType === undefined ? {} : { "content-type": request.contentType }, + body, + accessKey: request.credentials?.accessKey ?? connection.accessKey, + secretKey: request.credentials?.secretKey ?? connection.secretKey, + region: connection.region, + now: new Date(), + }); + const response = await fetch(url, { method: request.method, headers, body: request.method === "PUT" ? body : undefined, signal: AbortSignal.timeout(DIRECT_CALL_TIMEOUT_MS) }); + const bytes = Buffer.from(await response.arrayBuffer()); + return { status: response.status, headers: Object.fromEntries(response.headers.entries()), body: bytes, text: bytes.toString("utf8") }; +} + +/** The text of every `...` element of an XML answer, in order, with the five predefined entities and numeric character references decoded. */ +export function xmlValues(xml: string, tag: string): string[] { + const decode = (text: string): string => + text + .replace(/&#x([0-9a-fA-F]+);/g, (_, hex: string) => String.fromCodePoint(parseInt(hex, 16))) + .replace(/&#(\d+);/g, (_, dec: string) => String.fromCodePoint(parseInt(dec, 10))) + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, "&"); + return [...xml.matchAll(new RegExp(`<${tag}>([\\s\\S]*?)`, "g"))].map((match) => decode(match[1] as string)); +} + +/** The statuses a bucket call counts as done: created (200), removed (204), or already gone (404). */ +const BUCKET_GONE_STATUSES = [200, 204, 404]; + +/** + * Makes a bucket straight on the sidecar; throws when the server does not answer 200. A region other than `us-east-1` needs the bucket's location constraint in the body, as on + * AWS (measured: without it versitygw answers 400 `IllegalLocationConstraintException` for a server started in `us-west-1`). + */ +export async function s3CreateBucket(connection: S3Connection, bucket: string): Promise { + const body = `${connection.region}`; + const answer = await s3Direct(connection, { method: "PUT", bucket, body, contentType: "application/xml" }); + if (answer.status !== 200) throw new Error(`the S3 sidecar refused to create bucket ${bucket}: ${answer.status} ${answer.text}`); +} + +/** The keys of a bucket as the server lists them (up to 1000), in the server's order. */ +export async function s3DirectKeys(connection: S3Connection, bucket: string): Promise { + const answer = await s3Direct(connection, { method: "GET", bucket, query: { "list-type": "2" } }); + if (answer.status !== 200) throw new Error(`the S3 sidecar refused to list bucket ${bucket}: ${answer.status} ${answer.text}`); + return xmlValues(answer.text, "Key"); +} + +/** + * Removes a test's bucket whatever state the test ended in: deletes every object (up to 1000) and then the bucket. A bucket that is already gone (404) is fine; any other + * failure throws, so a leak is not silent. Safe to call when the bucket was never created. + */ +export async function s3RemoveBucket(connection: S3Connection, bucket: string): Promise { + const listed = await s3Direct(connection, { method: "GET", bucket, query: { "list-type": "2" } }); + if (listed.status === 404) return; + if (listed.status !== 200) throw new Error(`the S3 sidecar refused to list bucket ${bucket}: ${listed.status} ${listed.text}`); + for (const key of xmlValues(listed.text, "Key")) { + const removed = await s3Direct(connection, { method: "DELETE", bucket, key }); + if (!BUCKET_GONE_STATUSES.includes(removed.status)) throw new Error(`the S3 sidecar refused to delete ${bucket}/${key}: ${removed.status} ${removed.text}`); + } + const answer = await s3Direct(connection, { method: "DELETE", bucket }); + if (!BUCKET_GONE_STATUSES.includes(answer.status)) throw new Error(`the S3 sidecar refused to delete bucket ${bucket}: ${answer.status} ${answer.text}`); +} diff --git a/e2e/src/run-selection.ts b/e2e/src/run-selection.ts index 6f6a2a0804..d58ddc36e0 100644 --- a/e2e/src/run-selection.ts +++ b/e2e/src/run-selection.ts @@ -9,7 +9,7 @@ export interface RunFlags { /** Tests tagged `@superadmin` (SEC-R16a to SEC-R16d: they break a stack that holds more than ~420 workspaces, D-47). */ includeSuperAdmin: boolean; /** - * Tests tagged `@node-service-sidecar` (the node-service data sources that need a real server of their own: Firebird, libSQL, CouchDB, DynamoDB Local): they need the + * Tests tagged `@node-service-sidecar` (the node-service data sources that need a real server of their own: Firebird, libSQL, CouchDB, DynamoDB Local, S3): they need the * run script to start that sidecar, which it does only for this flag. Default stack only: the other stacks select their own tags. */ includeNodeServiceSidecars: boolean; diff --git a/e2e/src/security/echo.ts b/e2e/src/security/echo.ts index 9a8387e1b9..d713f6169d 100644 --- a/e2e/src/security/echo.ts +++ b/e2e/src/security/echo.ts @@ -40,7 +40,7 @@ export function echoReadPrefix(targetPath: string): string { /** Four dot-separated decimal octets, each 0 to 255 without a leading zero (the form `docker inspect` reports; a leading zero reads as octal in some parsers). */ const IPV4_OCTET = "(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)"; -const IPV4_PATTERN = new RegExp(`^${IPV4_OCTET}(\\.${IPV4_OCTET}){3}$`); +export const IPV4_PATTERN = new RegExp(`^${IPV4_OCTET}(\\.${IPV4_OCTET}){3}$`); /** The base URL of the echo sidecar from the environment, without a trailing slash; throws when the run script did not set it. */ export function echoBaseUrl(env: NodeJS.ProcessEnv): string { diff --git a/e2e/tests/datasource/plugin-s3-server.spec.ts b/e2e/tests/datasource/plugin-s3-server.spec.ts new file mode 100644 index 0000000000..d2510c0a91 --- /dev/null +++ b/e2e/tests/datasource/plugin-s3-server.spec.ts @@ -0,0 +1,675 @@ +import { createHash, randomBytes } from "node:crypto"; +import { connect } from "node:net"; +import type { Page } from "@playwright/test"; +import { createApp, createNodePluginDatasource, executeAppQueryRaw, nodePluginDatasourceBody, testDatasourceRaw, type RawAnswer, type RegisteredUser } from "../../src/api/client"; +import { API_OK, S3, TAGS } from "../../src/constants"; +import { appDsl, nodePluginQuery } from "../../src/dsl/builders"; +import { recordedPluginDatasource, recordedPluginQuery } from "../../src/dsl/recorded"; +import { s3Connection, s3CreateBucket, s3Direct, s3DirectKeys, s3RemoveBucket, xmlValues, type S3Connection } from "../../src/datasource/s3"; +import { expect, test } from "../../src/fixtures"; +import { DatasourcePage } from "../../src/pages/DatasourcePage"; + +/** + * D16: the S3 plugin of node-service (`server/node-service/src/plugins/s3/`, the plugin id `s3`, AWS SDK for JavaScript v3) run against a REAL S3-compatible + * server, the sidecar of the run (versitygw with its POSIX backend; `scripts/run-in-docker.sh` starts it only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`; image, auth + * and cost in the README, "S3 sidecar"). D10g to D10q run the same plugin against the echo's canned answers; here the answers are the server's own. + * + * Addressing: every bucket call of these tests goes to the sidecar's IP address (`E2E_S3_IP`, endpoint `http://:7070`), never to a name. The AWS SDK addresses a + * bucket of a host NAME as `.` (virtual-host style), a name that nothing maps and that may resolve outside the run network; for an IP address it uses + * path-style (`//`). The server has no name alias at all, so no test can reach it by name. The server verifies AWS Signature Version 4 for one root + * user (throw-away key pair in `S3` of `src/constants.ts`), so a wrong key or secret is refused by the server itself, not simulated. + * + * Every test makes its own bucket (a unique name), creates it INSIDE the try and removes its objects and the bucket in the `finally` (`s3RemoveBucket`): buckets are + * global to the sidecar, so no test counts buckets or objects it did not create. "Direct" calls (`s3Direct`, signed in the test process) are the controls that show what + * the server itself holds and answers, next to what the plugin makes of it for the app, and the way a test sets up and removes what it needs. + * + * Measured on the images `3.0.0-e2e` and `3.0.1-e2e` against versitygw v1.11.0 (the AWS SDK of the plugin is the one D10 measures, version 3.668.0 in its user agent): + * - Every answer of the plugin is `success: true, queryCode: "OK"` with the data below, or `success: false, queryCode: "FAILED"` with the server's own message and no data. + * - `listBuckets`: `[{ name }]`. `listObjects`: `[{ name, size, lastModified, signedUrl, url }]`: it sends ListObjects (version 1) with the prefix, the delimiter and `limit` as + * max-keys and nothing else, so the keys that a delimiter folds into prefixes are dropped (NSD-22) and a truncated listing cannot be continued (NSD-21). + * - `readFile`: `{ contentType, length, lastModified, data }` (the echo scenarios saw neither `length` nor `lastModified`: its canned answers carry no such headers). + * - `uploadData`: `{ fileName, signedUrl, url }`; `deleteFile`: `{ success: true }` for a key that exists and for one that does not. + * - A service error fails the query with the server's message: `NoSuchBucket`, `NoSuchKey`, `InvalidAccessKeyId`, `SignatureDoesNotMatch`. + * + * Not covered: a real AWS S3 (no vendor host is reachable; versitygw differs from S3 in limits, versioning, ACLs, storage classes, checksums, listing details such as ETag + * and owner, which the plugin does not return anyway), multipart upload, requests the plugin never makes (copy, tagging, ranges), and a presigned URL after it has expired + * (it lives 300 s), and a presigned URL fetched from inside the app container (hand-measured, README). + */ +/** Candidate defect: `listObjects` has no continuation: it sends no marker and returns neither `IsTruncated` nor a next marker, so a bucket with more keys than `limit` silently shows its first page. */ +const NO_CONTINUATION_DEFECT = { type: "defect", description: "NSD-21 candidate" } as const; +/** Candidate defect: `listObjects` with a delimiter returns only `Contents`: the common prefixes ("folders") the server answers are dropped. */ +const COMMON_PREFIXES_DEFECT = { type: "defect", description: "NSD-22 candidate" } as const; +/** Candidate defect: the `url` of `listObjects` and `uploadData` is the endpoint, the bucket and the key joined as they are: a key with `?`, `#` or `%` names another resource, and a space or non-ASCII text is not a valid URL until a client encodes it. */ +const UNENCODED_URL_DEFECT = { type: "defect", description: "NSD-24 candidate" } as const; +/** Candidate defect: `uploadData` decodes the data as base64 by default and Node's decoder accepts text that is not base64, so plain text typed into the form is stored as other bytes without a message. */ +const LENIENT_BASE64_DEFECT = { type: "defect", description: "NSD-23 candidate" } as const; + +const HTTP_OK = 200; +const HTTP_FORBIDDEN = 403; +const HTTP_NOT_FOUND = 404; +const QUERY_CODE_OK = "OK"; +const QUERY_CODE_FAILED = "FAILED"; +/** The `code` of the envelope of a refused connection test (`ResponseView.error(500, message)`). */ +const REFUSED_CODE = 500; +const MARKER_BYTES = 4; +const SERVICE_S3 = "s3"; +/** A region the sidecar is not started in (`S3.REGION`): a request signed for it is refused by the server. */ +const WRONG_REGION = "eu-west-1"; + +/** The recorded variants of the actions (`recordedPluginQuery("s3", variant)`; `""` is the editor's default action, listBuckets). */ +const VARIANT = { + LIST_BUCKETS: "", + LIST_OBJECTS: "ListObjects", + READ_FILE: "ReadFile", + UPLOAD_DATA: "UploadData", + DELETE_FILE: "DeleteFile", +} as const; + +/** + * The text of the connection test of the form, measured (`Connection Successful` toast; the refusal text is the server's message after this prefix, followed by a full + * stop the application adds: a message that already ends in one, as most of the server's do, shows two). + */ +const CONNECTION_OK_TOAST = "Connection Successful"; +const CONNECTION_FAILED_PREFIX = "Failed to connect data source: "; + +/** The server's own messages (versitygw v1.11.0), which the plugin reports as the query's message. */ +const SERVER_MESSAGES = { + NO_SUCH_BUCKET: "The specified bucket does not exist.", + NO_SUCH_KEY: "The specified key does not exist.", + INVALID_ACCESS_KEY: "The AWS Access Key Id you provided does not exist in our records.", + SIGNATURE_MISMATCH: "The request signature we calculated does not match the signature you provided. Check your key and signing method.", +} as const; + +/** What the plugin answers for an empty bucket name: `listObjects` checks it itself, the other actions hand the SDK's own text to the user (NSD-8 candidate, as in D10). */ +const BUCKET_REQUIRED_MESSAGE = "Bucket is required"; +const SDK_EMPTY_BUCKET_MESSAGE = "Empty value provided for input HTTP label: Bucket."; +const BUCKET_CHECK_DEFECT = { type: "defect", description: "NSD-8 candidate" } as const; + +/** The shapes of values the server generates. */ +const ISO_DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; +const SIGNATURE = /^[0-9a-f]{64}$/; + +/** The validity of a presigned URL the plugin asks for (`getFileSignedUrl`: `expiresIn: 60 * 5`). */ +const SIGNED_URL_EXPIRES_SECONDS = "300"; + +/** The content types of the uploads of these tests. */ +const TEXT_TYPE = "text/plain; charset=utf-8"; +const BINARY_TYPE = "application/octet-stream"; +const PNG_TYPE = "image/png"; + +/** The whole envelope of a successful connection test, and of one refused because nothing listens at the endpoint (measured; the text is the connection error the SDK reports). */ +const ACCEPTED_ENVELOPE = { code: API_OK, message: "", data: true, success: true } as const; +const closedPortEnvelope = (host: string): object => ({ code: REFUSED_CODE, message: `${CONNECTION_FAILED_PREFIX}connect ECONNREFUSED ${host}:${CLOSED_PORT}.`, success: false }); + +/** The size of the large upload (the form sends it as a base64 string of about 1.33 times this length). */ +const LARGE_BODY_BYTES = 3 * 1024 * 1024; + +/** A port of the sidecar's host where nothing listens: the control that a refused connection is seen as one. */ +const CLOSED_PORT = 7071; +const CONNECT_TIMEOUT_MS = 5000; + +/** The envelope of `POST /api/query/execute` (`QueryResultView`), the fields these tests read. */ +interface QueryEnvelope { + success?: boolean; + queryCode?: string; + message?: string | null; + data?: unknown; +} + +function envelopeOf(answer: RawAnswer): QueryEnvelope { + return answer.json as QueryEnvelope; +} + +function uniqueMarker(): string { + return randomBytes(MARKER_BYTES).toString("hex"); +} + +/** A bucket name of this test only (3 to 63 characters: lower-case letters, digits, hyphens). */ +function uniqueBucket(): string { + return `e2e-s3-${uniqueMarker()}`; +} + +/** One saved query: the recording's variant and the action's fields over the recorded defaults. */ +interface S3Query { + variant: string; + action: Record; +} + +const listBuckets = (): S3Query => ({ variant: VARIANT.LIST_BUCKETS, action: {} }); +const listObjects = (bucket: string, extra: Record = {}): S3Query => ({ variant: VARIANT.LIST_OBJECTS, action: { bucket, ...extra } }); +const readFile = (bucket: string, fileName: string, encoding?: string): S3Query => ({ variant: VARIANT.READ_FILE, action: { bucket, fileName, ...(encoding ? { encoding } : {}) } }); +const uploadData = (bucket: string, fileName: string, data: string, extra: Record = {}): S3Query => ({ + variant: VARIANT.UPLOAD_DATA, + action: { bucket, fileName, data, ...extra }, +}); +const deleteFile = (bucket: string, fileName: string): S3Query => ({ variant: VARIANT.DELETE_FILE, action: { bucket, fileName } }); + +/** The data source fields a test overrides over the sidecar's own. */ +interface Overrides { + accessKey?: string; + secretKey?: string; + endpointUrl?: string; + region?: string; +} + +/** The data source fields of the sidecar over the recorded form body. */ +function sidecarConfig(overrides: Overrides = {}): Record { + const sidecar = s3Connection(); + return { + accessKey: overrides.accessKey ?? sidecar.accessKey, + secretKey: overrides.secretKey ?? sidecar.secretKey, + endpointUrl: overrides.endpointUrl ?? sidecar.endpointUrl, + region: overrides.region ?? sidecar.region, + }; +} + +async function s3Datasource(page: Page, apiUser: RegisteredUser, overrides: Overrides = {}): Promise { + return createNodePluginDatasource(page.request, { orgId: apiUser.orgId, recorded: recordedPluginDatasource(SERVICE_S3), config: sidecarConfig(overrides) }); +} + +/** A saved app with one manual S3 query per entry of `queries` on one data source (not published: the draft runs with `viewMode: false`). */ +async function s3App(page: Page, apiUser: RegisteredUser, queries: Record, overrides: Overrides = {}): Promise { + const datasourceId = await s3Datasource(page, apiUser, overrides); + const saved = Object.entries(queries).map(([id, query]) => nodePluginQuery({ id, name: id, datasourceId, recorded: recordedPluginQuery(SERVICE_S3, query.variant), action: query.action })); + const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: "e2e-s3-server", dsl: appDsl([], { queries: saved }) }); + return appId; +} + +async function runDraft(page: Page, appId: string, queryId: string): Promise { + return executeAppQueryRaw(page.request, { applicationId: appId, queryId, viewMode: false }); +} + +function expectRan(answer: RawAnswer): void { + expect({ status: answer.status, code: answer.code }, "the query request was answered").toEqual({ status: HTTP_OK, code: API_OK }); +} + +function expectSucceeded(answer: RawAnswer): void { + expectRan(answer); + expect(envelopeOf(answer).success, "the query succeeded").toBe(true); + expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); +} + +function expectFailed(answer: RawAnswer, message: string): void { + expectRan(answer); + expect( + { success: envelopeOf(answer).success, queryCode: envelopeOf(answer).queryCode, message: envelopeOf(answer).message, data: envelopeOf(answer).data }, + "the query failed with the measured message", + ).toEqual({ success: false, queryCode: QUERY_CODE_FAILED, message, data: null }); +} + +/** Runs a query whose answer the test asserts as data: the success state first, then the data. */ +async function runForData(page: Page, appId: string, queryId: string): Promise { + const answer = await runDraft(page, appId, queryId); + expectSucceeded(answer); + return envelopeOf(answer).data; +} + +/** The sidecar's connection (the test fails loudly when the run did not start it). */ +function server(): S3Connection { + return s3Connection(); +} + +/** The object the server holds, as a direct call answers it (`undefined` status 404: no such key). */ +async function directObject(bucket: string, key: string): Promise<{ status: number; type?: string; bytes: Buffer }> { + const answer = await s3Direct(server(), { method: "GET", bucket, key }); + return { status: answer.status, type: answer.headers["content-type"], bytes: answer.body }; +} + +/** Puts an object straight on the sidecar. */ +async function directPut(bucket: string, key: string, body: Buffer | string, contentType?: string): Promise { + const answer = await s3Direct(server(), { method: "PUT", bucket, key, body, contentType }); + expect(answer.status, `the server stored ${bucket}/${key}`).toBe(HTTP_OK); +} + +/** How a TCP connection to `host:port` ended: `connected`, or the error code Node reports (`ECONNREFUSED`, ...). */ +async function tcpOutcome(host: string, port: number): Promise { + return new Promise((resolve) => { + const socket = connect({ host, port }); + socket.setTimeout(CONNECT_TIMEOUT_MS, () => { + socket.destroy(); + resolve("timeout"); + }); + socket.once("connect", () => { + socket.destroy(); + resolve("connected"); + }); + socket.once("error", (error: NodeJS.ErrnoException) => resolve(error.code ?? error.message)); + }); +} + +const sha256 = (bytes: Buffer): string => createHash("sha256").update(bytes).digest("hex"); + +/** The URL the plugin reports for an object: the endpoint, the bucket and the key, not encoded (`getFileUrl`). */ +const fileUrl = (bucket: string, key: string): string => `${server().endpointUrl}/${bucket}/${key}`; + +test.describe("S3 data source against a real S3-compatible server", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { + test("D16a: the connection test lists the buckets with the right key pair, and the server itself refuses a wrong access key, a wrong secret and a wrong region", async ({ page, apiUser }) => { + const bodyFor = (overrides: Overrides): object => nodePluginDatasourceBody(recordedPluginDatasource(SERVICE_S3), { orgId: apiUser.orgId, config: sidecarConfig(overrides) }); + + const accepted = await testDatasourceRaw(page.request, bodyFor({})); + expect({ status: accepted.status, json: accepted.json }, "the right key pair: the envelope of a success").toEqual({ status: HTTP_OK, json: { code: API_OK, message: "", data: true, success: true } }); + + const refusals: Array<{ title: string; overrides: Overrides; message: string }> = [ + { title: "wrong access key", overrides: { accessKey: `${S3.ACCESS_KEY}x` }, message: SERVER_MESSAGES.INVALID_ACCESS_KEY }, + { title: "wrong secret", overrides: { secretKey: `${S3.SECRET_KEY}x` }, message: SERVER_MESSAGES.SIGNATURE_MISMATCH }, + { title: "wrong region", overrides: { region: WRONG_REGION }, message: `The authorization header is malformed; the region '${WRONG_REGION}' is wrong; expecting '${S3.REGION}'` }, + ]; + for (const refusal of refusals) { + const refused = await testDatasourceRaw(page.request, bodyFor(refusal.overrides)); + expect({ status: refused.status, code: refused.code, json: refused.json }, refusal.title).toEqual({ + status: HTTP_OK, + code: REFUSED_CODE, + json: { code: REFUSED_CODE, message: `${CONNECTION_FAILED_PREFIX}${refusal.message}.`, success: false }, + }); + } + // the same bodies with the right key pair are accepted again: the answer above came from the key pair, not from the endpoint or the form + const again = await testDatasourceRaw(page.request, bodyFor({})); + expect(again.json, "control: the right key pair is accepted after the refusals").toEqual({ code: API_OK, message: "", data: true, success: true }); + }); + test("D16b: the form's Test Connection button shows the server's own refusal of a wrong secret, and the success once the secret is right", async ({ page, apiUser }) => { + // `apiUser` signs a new user in on the page (the data source page needs a session); the form is the subject, the user makes nothing + expect(apiUser.orgId, "the page is signed in as a user with a workspace").toBeTruthy(); + const sidecar = server(); + const datasources = new DatasourcePage(page); + await datasources.open(); + await datasources.newButton.click(); + await page.getByText("AWS S3", { exact: true }).first().click(); + // the field ids of the form (measured in D10: `name`, `accessKey`, `secretKey`, `endpointUrl`) + await page.locator("#name").fill("e2e-s3-form"); + await page.locator("#accessKey").fill(sidecar.accessKey); + await page.locator("#secretKey").fill(`${sidecar.secretKey}x`); + await page.locator("#endpointUrl").fill(sidecar.endpointUrl); + const testButton = page.getByRole("button", { name: "Test Connection" }); + await expect(page.getByText(CONNECTION_OK_TOAST), "before the first click no result is shown").toHaveCount(0); + + await testButton.click(); + + await expect(page.getByText(`${CONNECTION_FAILED_PREFIX}${SERVER_MESSAGES.SIGNATURE_MISMATCH}.`), "the server's refusal of the wrong secret is shown").toBeVisible(); + await expect(page.getByText(CONNECTION_OK_TOAST), "and no success with it").toHaveCount(0); + + await page.locator("#secretKey").fill(sidecar.secretKey); + await testButton.click(); + + await expect(page.getByText(CONNECTION_OK_TOAST), "with the right secret the same form reports success").toBeVisible(); + }); + + test("D16c: a listBuckets query shows a bucket the moment the server has it, as a name only", async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + try { + const appId = await s3App(page, apiUser, { buckets: listBuckets() }); + + const before = (await runForData(page, appId, "buckets")) as Array<{ name: string }>; + expect(before.map((entry) => entry.name), "before the create the bucket is not listed").not.toContain(bucket); + + await s3CreateBucket(server(), bucket); + const after = (await runForData(page, appId, "buckets")) as Array<{ name: string }>; + expect(after.map((entry) => entry.name), "after the create the bucket is listed").toContain(bucket); + expect(after.every((entry) => Object.keys(entry).join() === "name"), "every entry holds the name and nothing else").toBe(true); + const direct = await s3Direct(server(), { method: "GET" }); + expect({ status: direct.status, listed: xmlValues(direct.text, "Name").includes(bucket) }, "the server's own listing agrees").toEqual({ status: HTTP_OK, listed: true }); + } finally { + await s3RemoveBucket(server(), bucket); + } + }); + test("D16d: uploadData stores the decoded bytes with the content type and readFile answers them back, as text or as base64, with the server's length and time", async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + const text = "héllo wörld\nline 2: 日本語"; + const key = "docs/e2e file.txt"; + const binary = Buffer.from(Array.from({ length: 256 }, (_, value) => value)); + try { + await s3CreateBucket(server(), bucket); + const appId = await s3App(page, apiUser, { + putText: uploadData(bucket, key, text, { encoding: "utf8", contentType: TEXT_TYPE }), + readText: readFile(bucket, key, "utf8"), + readBase64: readFile(bucket, key), + putBinary: uploadData(bucket, "bin/all-bytes.bin", binary.toString("base64"), { contentType: PNG_TYPE }), + readBinary: readFile(bucket, "bin/all-bytes.bin"), + putDefaultType: uploadData(bucket, "bin/no-type.bin", binary.toString("base64"), { contentType: "" }), + putOver: uploadData(bucket, key, "second version", { encoding: "utf8", contentType: "text/markdown" }), + readOver: readFile(bucket, key, "utf8"), + }); + + expect((await directObject(bucket, key)).status, "before the upload the server has no such key").toBe(HTTP_NOT_FOUND); + expect(await runForData(page, appId, "putText"), "the upload answers the name, no signed URL, and the file URL").toEqual({ fileName: key, signedUrl: "", url: fileUrl(bucket, key) }); + const stored = await directObject(bucket, key); + expect({ status: stored.status, type: stored.type, text: stored.bytes.toString("utf8") }, "the server holds the decoded text with the content type").toEqual({ status: HTTP_OK, type: TEXT_TYPE, text }); + + const asText = (await runForData(page, appId, "readText")) as Record; + expect(asText, "readFile as text: type, length in bytes, time and the data").toEqual({ + contentType: TEXT_TYPE, + length: Buffer.byteLength(text), + lastModified: expect.stringMatching(ISO_DATE), + data: text, + }); + const asBase64 = (await runForData(page, appId, "readBase64")) as Record; + expect({ ...asBase64, lastModified: typeof asBase64.lastModified }, "readFile without an encoding is base64 of the same bytes").toEqual({ + contentType: TEXT_TYPE, + length: Buffer.byteLength(text), + lastModified: "string", + data: Buffer.from(text, "utf8").toString("base64"), + }); + + await runForData(page, appId, "putBinary"); + const storedBinary = await directObject(bucket, "bin/all-bytes.bin"); + expect({ status: storedBinary.status, type: storedBinary.type, sha: sha256(storedBinary.bytes), size: storedBinary.bytes.length }, "all 256 byte values arrive unchanged, with the given type").toEqual({ + status: HTTP_OK, + type: PNG_TYPE, + sha: sha256(binary), + size: 256, + }); + expect(((await runForData(page, appId, "readBinary")) as { data: string; length: number }).data, "read back as base64: the same bytes").toBe(binary.toString("base64")); + + await runForData(page, appId, "putDefaultType"); + expect((await directObject(bucket, "bin/no-type.bin")).type, "an empty content type is stored as the SDK's default for a binary body").toBe(BINARY_TYPE); + + await runForData(page, appId, "putOver"); + const over = await directObject(bucket, key); + expect({ type: over.type, text: over.bytes.toString("utf8") }, "an upload to an existing key replaces the object and its type").toEqual({ type: "text/markdown", text: "second version" }); + expect(((await runForData(page, appId, "readOver")) as { data: string }).data, "and the plugin reads the new version").toBe("second version"); + } finally { + await s3RemoveBucket(server(), bucket); + } + }); + + test("D16e: listObjects applies the prefix, the delimiter and the limit of the server, and answers name, size, time, an empty signed URL and the file URL", async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + const keys = ["p/a.txt", "p/b.txt", "p/sub/c.txt", "q/d.txt", "root.txt"]; + try { + await s3CreateBucket(server(), bucket); + for (const key of keys) await directPut(bucket, key, `body of ${key}`, TEXT_TYPE); + const appId = await s3App(page, apiUser, { + all: listObjects(bucket), + prefix: listObjects(bucket, { prefix: "p/" }), + none: listObjects(bucket, { prefix: "zzz/" }), + limit: listObjects(bucket, { limit: 2 }), + }); + expect(await s3DirectKeys(server(), bucket), "the server holds the five keys").toEqual(keys); + + const all = (await runForData(page, appId, "all")) as Array>; + expect(all, "every object: name, size in bytes, time, no signed URL, and the file URL").toEqual( + keys.map((key) => ({ name: key, size: Buffer.byteLength(`body of ${key}`), lastModified: expect.stringMatching(ISO_DATE), signedUrl: "", url: fileUrl(bucket, key) })), + ); + expect((await runForData(page, appId, "prefix") as Array<{ name: string }>).map((entry) => entry.name), "a prefix selects the keys below it").toEqual(["p/a.txt", "p/b.txt", "p/sub/c.txt"]); + expect(await runForData(page, appId, "none"), "a prefix nothing has: an empty list, a success").toEqual([]); + expect((await runForData(page, appId, "limit") as Array<{ name: string }>).map((entry) => entry.name), "a limit of 2 is the first two keys in order").toEqual(["p/a.txt", "p/b.txt"]); + } finally { + await s3RemoveBucket(server(), bucket); + } + }); + test("D16f: a listing cut by the limit cannot be continued (the plugin sends no marker and shows no truncation flag)", { annotation: NO_CONTINUATION_DEFECT }, async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + const keys = ["k/1.txt", "k/2.txt", "k/3.txt", "k/4.txt", "k/5.txt"]; + try { + await s3CreateBucket(server(), bucket); + for (const key of keys) await directPut(bucket, key, key); + const appId = await s3App(page, apiUser, { first: listObjects(bucket, { limit: 2 }), whole: listObjects(bucket, { limit: 100 }) }); + + // control: the server itself reports the cut and offers a continuation token, so a client that asked could go on + const page1 = await s3Direct(server(), { method: "GET", bucket, query: { "list-type": "2", "max-keys": "2" } }); + expect({ status: page1.status, keys: xmlValues(page1.text, "Key"), truncated: xmlValues(page1.text, "IsTruncated"), hasToken: xmlValues(page1.text, "NextContinuationToken").length }, "the server's own first page").toEqual({ + status: HTTP_OK, + keys: keys.slice(0, 2), + truncated: ["true"], + hasToken: 1, + }); + + const first = await runDraft(page, appId, "first"); + expectSucceeded(first); + expect(envelopeOf(first).data, "the plugin's answer is a bare array of the first two objects: no token, no flag, no marker field").toEqual( + keys.slice(0, 2).map((key) => ({ name: key, size: key.length, lastModified: expect.stringMatching(ISO_DATE), signedUrl: "", url: fileUrl(bucket, key) })), + ); + expect((await runForData(page, appId, "whole") as Array<{ name: string }>).map((entry) => entry.name), "positive control: with a limit above the count the same query shows all five, so the cut came from the limit").toEqual(keys); + } finally { + await s3RemoveBucket(server(), bucket); + } + }); + + test("D16g: listObjects with a delimiter returns only the keys of that level and drops the common prefixes the server answers", { annotation: COMMON_PREFIXES_DEFECT }, async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + const keys = ["p/a.txt", "p/sub/c.txt", "q/d.txt", "root.txt"]; + try { + await s3CreateBucket(server(), bucket); + for (const key of keys) await directPut(bucket, key, key); + const appId = await s3App(page, apiUser, { top: listObjects(bucket, { delimiter: "/" }), inP: listObjects(bucket, { prefix: "p/", delimiter: "/" }) }); + + const direct = await s3Direct(server(), { method: "GET", bucket, query: { delimiter: "/", "list-type": "2" } }); + expect({ keys: xmlValues(direct.text, "Key"), prefixes: xmlValues(direct.text, "Prefix").filter((prefix) => prefix !== "") }, "control: the server answers one key and two common prefixes").toEqual({ + keys: ["root.txt"], + prefixes: ["p/", "q/"], + }); + + expect((await runForData(page, appId, "top") as Array<{ name: string }>).map((entry) => entry.name), "the plugin shows the key and no folder").toEqual(["root.txt"]); + expect((await runForData(page, appId, "inP") as Array<{ name: string }>).map((entry) => entry.name), "below a prefix the same: the key of that level only, the sub-folder is missing").toEqual(["p/a.txt"]); + } finally { + await s3RemoveBucket(server(), bucket); + } + }); + + test("D16h: deleteFile removes an existing key and answers success for a key that does not exist, leaving the others", async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + try { + await s3CreateBucket(server(), bucket); + await directPut(bucket, "keep.txt", "keep"); + await directPut(bucket, "gone.txt", "gone"); + const appId = await s3App(page, apiUser, { removeExisting: deleteFile(bucket, "gone.txt"), removeAbsent: deleteFile(bucket, "never-was.txt") }); + + expect(await s3DirectKeys(server(), bucket), "before the delete the server holds both keys").toEqual(["gone.txt", "keep.txt"]); + expect(await runForData(page, appId, "removeExisting"), "the plugin's own answer").toEqual({ success: true }); + expect({ keys: await s3DirectKeys(server(), bucket), gone: (await directObject(bucket, "gone.txt")).status }, "the key is gone from the server, the other stays").toEqual({ keys: ["keep.txt"], gone: HTTP_NOT_FOUND }); + + expect(await runForData(page, appId, "removeAbsent"), "a key that was never there is the same answer").toEqual({ success: true }); + expect(await s3DirectKeys(server(), bucket), "and nothing else changed").toEqual(["keep.txt"]); + } finally { + await s3RemoveBucket(server(), bucket); + } + }); + test("D16i: a presigned URL from listObjects and from uploadData works from the test process, and the same object without the signature or with a changed one is refused", async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + const key = "signed/e2e file.txt"; + const content = "content behind a presigned URL"; + try { + await s3CreateBucket(server(), bucket); + await directPut(bucket, key, content, TEXT_TYPE); + const appId = await s3App(page, apiUser, { + listSigned: listObjects(bucket, { returnSignedUrl: true }), + putSigned: uploadData(bucket, "uploaded.txt", "uploaded and signed", { encoding: "utf8", contentType: TEXT_TYPE, returnSignedUrl: true }), + }); + + const listed = (await runForData(page, appId, "listSigned")) as Array<{ name: string; signedUrl: string; url: string }>; + expect(listed.map((file) => file.name), "the one object").toEqual([key]); + const signed = new URL(listed[0]?.signedUrl ?? ""); + expect({ origin: signed.origin, path: signed.pathname }, "the presigned URL addresses the object path-style below the sidecar's IP address").toEqual({ origin: server().endpointUrl, path: "/" + bucket + "/signed/e2e%20file.txt" }); + const params = Object.fromEntries(signed.searchParams); + expect( + { + algorithm: params["X-Amz-Algorithm"], + payload: params["X-Amz-Content-Sha256"], + credentialScope: params["X-Amz-Credential"]?.replace(/\/\d{8}\//, "//"), + expires: params["X-Amz-Expires"], + signedHeaders: params["X-Amz-SignedHeaders"], + signature: SIGNATURE.test(params["X-Amz-Signature"] ?? ""), + }, + "the stable parts of the presigned URL", + ).toEqual({ + algorithm: "AWS4-HMAC-SHA256", + payload: "UNSIGNED-PAYLOAD", + credentialScope: `${S3.ACCESS_KEY}//${S3.REGION}/s3/aws4_request`, + expires: SIGNED_URL_EXPIRES_SECONDS, + signedHeaders: "host", + signature: true, + }); + + const fetched = await fetch(signed); + expect({ status: fetched.status, type: fetched.headers.get("content-type"), text: await fetched.text() }, "the presigned URL downloads the object from the test process, with no key pair").toEqual({ status: HTTP_OK, type: TEXT_TYPE, text: content }); + + const unsigned = await fetch(listed[0]?.url ?? ""); + const unsignedText = await unsigned.text(); + expect({ status: unsigned.status, code: xmlValues(unsignedText, "Code") }, "the plain `url` of the same object is refused: the bucket is not public").toEqual({ status: HTTP_FORBIDDEN, code: ["AccessDenied"] }); + const tampered = new URL(signed); + tampered.searchParams.set("X-Amz-Signature", "0".repeat(64)); + const tamperedAnswer = await fetch(tampered); + expect({ status: tamperedAnswer.status, code: xmlValues(await tamperedAnswer.text(), "Code") }, "a changed signature is refused by the server's verification").toEqual({ status: HTTP_FORBIDDEN, code: ["SignatureDoesNotMatch"] }); + const otherKey = new URL(signed); + otherKey.pathname = `/${bucket}/other-key.txt`; + expect((await fetch(otherKey)).status, "the signature belongs to the key: another key with the same signature is refused").toBe(HTTP_FORBIDDEN); + + const uploaded = (await runForData(page, appId, "putSigned")) as { fileName: string; signedUrl: string; url: string }; + expect({ fileName: uploaded.fileName, url: uploaded.url }, "the upload answers the name and the file URL").toEqual({ fileName: "uploaded.txt", url: fileUrl(bucket, "uploaded.txt") }); + const uploadedFetch = await fetch(uploaded.signedUrl); + expect({ status: uploadedFetch.status, text: await uploadedFetch.text() }, "the signed URL of the upload downloads what was uploaded").toEqual({ status: HTTP_OK, text: "uploaded and signed" }); + } finally { + await s3RemoveBucket(server(), bucket); + } + }); + + test("D16j: keys with spaces, unicode, reserved characters and slashes are stored under their exact names, listed, and read back", { annotation: UNENCODED_URL_DEFECT }, async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + const keys = ["a+b&c=d.txt", "dir/e2e file.txt", "deep/er/est/key.txt", "percent%20sign.txt", "q?mark#hash.txt", "quote'(star)*!.txt", "semi;colon,comma.txt", "ünï/日本語.txt"]; + try { + await s3CreateBucket(server(), bucket); + const queries: Record = {}; + keys.forEach((key, index) => { + queries[`put${index}`] = uploadData(bucket, key, `content of ${key}`, { encoding: "utf8", contentType: TEXT_TYPE }); + queries[`read${index}`] = readFile(bucket, key, "utf8"); + }); + queries.list = listObjects(bucket, { limit: 100 }); + const appId = await s3App(page, apiUser, queries); + + expect(await s3DirectKeys(server(), bucket), "before the uploads the bucket is empty").toEqual([]); + for (const [index, key] of keys.entries()) { + expect(await runForData(page, appId, `put${index}`), `upload of ${key}`).toEqual({ fileName: key, signedUrl: "", url: fileUrl(bucket, key) }); + } + expect(await s3DirectKeys(server(), bucket), "the server holds exactly the keys that were sent, byte for byte").toEqual([...keys].sort()); + for (const [index, key] of keys.entries()) { + expect(((await runForData(page, appId, `read${index}`)) as { data: string }).data, `read of ${key}`).toBe(`content of ${key}`); + expect(new TextDecoder().decode((await directObject(bucket, key)).bytes), `the server's own copy of ${key}`).toBe(`content of ${key}`); + } + const listed = (await runForData(page, appId, "list")) as Array<{ name: string; url: string }>; + expect(listed.map((file) => file.name), "the listing shows the same names").toEqual([...keys].sort()); + expect(listed.map((file) => file.url), "the `url` of each object is the endpoint, the bucket and the key as they are: spaces and reserved characters are not encoded").toEqual([...keys].sort().map((key) => fileUrl(bucket, key))); + } finally { + await s3RemoveBucket(server(), bucket); + } + }); + + test("D16k: the server's own errors reach the query as its message: a missing bucket for every action, a missing key, a wrong access key and a wrong secret", async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + const missing = uniqueBucket(); + try { + await s3CreateBucket(server(), bucket); + await directPut(bucket, "present.txt", "present"); + const queries = { + listMissing: listObjects(missing), + readMissingBucket: readFile(missing, "present.txt", "utf8"), + uploadMissing: uploadData(missing, "x.txt", "x", { encoding: "utf8" }), + deleteMissing: deleteFile(missing, "present.txt"), + readMissingKey: readFile(bucket, "absent.txt", "utf8"), + readPresent: readFile(bucket, "present.txt", "utf8"), + list: listObjects(bucket), + }; + const appId = await s3App(page, apiUser, queries); + const wrongKey = await s3App(page, apiUser, { buckets: listBuckets(), list: queries.list, read: queries.readPresent, upload: uploadData(bucket, "x.txt", "x", { encoding: "utf8" }), remove: deleteFile(bucket, "present.txt") }, { accessKey: `${S3.ACCESS_KEY}x` }); + const wrongSecret = await s3App(page, apiUser, { list: queries.list, read: queries.readPresent, upload: uploadData(bucket, "x.txt", "x", { encoding: "utf8" }), remove: deleteFile(bucket, "present.txt"), buckets: listBuckets() }, { secretKey: `${S3.SECRET_KEY}x` }); + + // positive controls first: the same data source reads and lists the bucket that exists + expect(((await runForData(page, appId, "readPresent")) as { data: string }).data, "control: the existing key is read").toBe("present"); + expect((await runForData(page, appId, "list") as Array<{ name: string }>).map((file) => file.name), "control: the existing bucket is listed").toEqual(["present.txt"]); + + expectFailed(await runDraft(page, appId, "listMissing"), SERVER_MESSAGES.NO_SUCH_BUCKET); + expectFailed(await runDraft(page, appId, "readMissingBucket"), SERVER_MESSAGES.NO_SUCH_BUCKET); + expectFailed(await runDraft(page, appId, "uploadMissing"), SERVER_MESSAGES.NO_SUCH_BUCKET); + expectFailed(await runDraft(page, appId, "deleteMissing"), SERVER_MESSAGES.NO_SUCH_BUCKET); + expectFailed(await runDraft(page, appId, "readMissingKey"), SERVER_MESSAGES.NO_SUCH_KEY); + expect(await s3DirectKeys(server(), bucket), "the failed calls changed nothing").toEqual(["present.txt"]); + + for (const queryId of ["buckets", "list", "read", "upload", "remove"]) expectFailed(await runDraft(page, wrongKey, queryId), SERVER_MESSAGES.INVALID_ACCESS_KEY); + for (const queryId of ["buckets", "list", "read", "upload", "remove"]) expectFailed(await runDraft(page, wrongSecret, queryId), SERVER_MESSAGES.SIGNATURE_MISMATCH); + expect(await s3DirectKeys(server(), bucket), "the refused upload and delete changed nothing").toEqual(["present.txt"]); + } finally { + await s3RemoveBucket(server(), bucket); + await s3RemoveBucket(server(), missing); + } + }); + + test("D16l: a bucket call without a bucket name reaches no bucket", { annotation: BUCKET_CHECK_DEFECT }, async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + try { + await s3CreateBucket(server(), bucket); + const appId = await s3App(page, apiUser, { + listEmpty: listObjects(""), + readEmpty: readFile("", "e2e.txt", "utf8"), + uploadEmpty: uploadData("", "e2e.txt", "x", { encoding: "utf8" }), + deleteEmpty: deleteFile("", "e2e.txt"), + listReal: listObjects(bucket), + }); + + // the one operation that checks the bucket itself; NSD-8 candidate: the others hand the SDK's own text to the user (measured) + expectFailed(await runDraft(page, appId, "listEmpty"), BUCKET_REQUIRED_MESSAGE); + expectFailed(await runDraft(page, appId, "readEmpty"), SDK_EMPTY_BUCKET_MESSAGE); + expectFailed(await runDraft(page, appId, "uploadEmpty"), SDK_EMPTY_BUCKET_MESSAGE); + expectFailed(await runDraft(page, appId, "deleteEmpty"), SDK_EMPTY_BUCKET_MESSAGE); + expect(await s3DirectKeys(server(), bucket), "nothing was stored in the existing bucket").toEqual([]); + // positive control: the same data source with a bucket name works, so the refusals above came from the missing name + expect(await runForData(page, appId, "listReal"), "the listing of the real, empty bucket").toEqual([]); + } finally { + await s3RemoveBucket(server(), bucket); + } + }); + + test("D16m: a body of several megabytes is stored byte for byte and read back, and the server's length and the plugin's length agree", async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + const bytes = randomBytes(LARGE_BODY_BYTES); + try { + await s3CreateBucket(server(), bucket); + const appId = await s3App(page, apiUser, { + put: uploadData(bucket, "large.bin", bytes.toString("base64"), { contentType: BINARY_TYPE }), + read: readFile(bucket, "large.bin"), + list: listObjects(bucket), + }); + + expect(await runForData(page, appId, "put"), "the upload answers the name").toMatchObject({ fileName: "large.bin" }); + const stored = await directObject(bucket, "large.bin"); + expect({ status: stored.status, size: stored.bytes.length, sha: sha256(stored.bytes) }, "the server holds every byte").toEqual({ status: HTTP_OK, size: LARGE_BODY_BYTES, sha: sha256(bytes) }); + const read = (await runForData(page, appId, "read")) as { length: number; data: string }; + expect({ length: read.length, sha: sha256(Buffer.from(read.data, "base64")) }, "the plugin reads the same length and bytes").toEqual({ length: LARGE_BODY_BYTES, sha: sha256(bytes) }); + expect(((await runForData(page, appId, "list")) as Array<{ size: number }>).map((file) => file.size), "and the listing's size").toEqual([LARGE_BODY_BYTES]); + } finally { + await s3RemoveBucket(server(), bucket); + } + }); + + test("D16n: uploadData with the default encoding decodes text that is not base64 into other bytes and stores them without a message", { annotation: LENIENT_BASE64_DEFECT }, async ({ page, apiUser }) => { + const bucket = uniqueBucket(); + const typed = "hello world, this is not base64!"; + try { + await s3CreateBucket(server(), bucket); + const appId = await s3App(page, apiUser, { + defaultEncoding: uploadData(bucket, "typed.txt", typed), + asText: uploadData(bucket, "typed-as-text.txt", typed, { encoding: "utf8" }), + }); + + await runForData(page, appId, "asText"); + expect((await directObject(bucket, "typed-as-text.txt")).bytes.toString("utf8"), "control: with the text encoding the typed text is stored as typed").toBe(typed); + expect(await runForData(page, appId, "defaultEncoding"), "with the default encoding the upload succeeds").toMatchObject({ fileName: "typed.txt" }); + const stored = (await directObject(bucket, "typed.txt")).bytes; + expect(stored.equals(Buffer.from(typed, "base64")), "the server holds what Node's lenient base64 decoder made of the typed text").toBe(true); + expect(stored.toString("utf8"), "which is not the typed text").not.toBe(typed); + } finally { + await s3RemoveBucket(server(), bucket); + } + }); + + test("D16o: a connection to a port where nothing listens is refused locally, and the same data source works on the server's port", async ({ page, apiUser }) => { + const sidecar = server(); + const host = new URL(sidecar.endpointUrl).hostname; + expect(await tcpOutcome(host, CLOSED_PORT), "nothing listens on the closed port").toBe("ECONNREFUSED"); + expect(await tcpOutcome(host, S3.PORT), "control: the sidecar's port accepts the connection").toBe("connected"); + const body = nodePluginDatasourceBody(recordedPluginDatasource(SERVICE_S3), { orgId: apiUser.orgId, config: sidecarConfig({ endpointUrl: `http://${host}:${CLOSED_PORT}` }) }); + + const refused = await testDatasourceRaw(page.request, body); + + expect({ status: refused.status, json: refused.json }, "the connection test of the closed port is refused with the connection error").toEqual({ status: HTTP_OK, json: closedPortEnvelope(host) }); + const accepted = await testDatasourceRaw(page.request, nodePluginDatasourceBody(recordedPluginDatasource(SERVICE_S3), { orgId: apiUser.orgId, config: sidecarConfig() })); + expect({ status: accepted.status, json: accepted.json }, "control: the server's port is accepted with the envelope of a success").toEqual({ status: HTTP_OK, json: ACCEPTED_ENVELOPE }); + }); +}); diff --git a/e2e/tests/foundation/node-plugins.spec.ts b/e2e/tests/foundation/node-plugins.spec.ts index 25ab930226..b6b51dd061 100644 --- a/e2e/tests/foundation/node-plugins.spec.ts +++ b/e2e/tests/foundation/node-plugins.spec.ts @@ -5,7 +5,7 @@ import type { AddressInfo } from "node:net"; import { join } from "node:path"; import { expect, test } from "@playwright/test"; import { createNodePluginDatasource, LowcoderApiError, nodePluginDatasourceBody, pluginDynamicConfigRaw, testDatasourceRaw } from "../../src/api/client"; -import { API_OK, API_PATHS, COUCHDB, DYNAMODB, FIREBIRD, LIBSQL, orgDatasourceTypesPath, RUN_FLAGS, TAGS } from "../../src/constants"; +import { API_OK, API_PATHS, COUCHDB, DYNAMODB, FIREBIRD, LIBSQL, orgDatasourceTypesPath, RUN_FLAGS, S3, TAGS } from "../../src/constants"; import { nodePluginQuery } from "../../src/dsl/builders"; import { parsePluginRecording, @@ -20,6 +20,7 @@ import { couchdbAdmin, couchdbConnection, couchdbDirect, CouchdbSidecarMissingEr import { DYNAMODB_CONTENT_TYPE, DYNAMODB_TARGET_PREFIX, dynamodbConnection, dynamodbDirect, DynamodbSidecarMissingError } from "../../src/datasource/dynamodb"; import { FIREBIRD_ITEMS, firebirdConnection, FirebirdSidecarMissingError } from "../../src/datasource/firebird"; import { LIBSQL_PIPELINE_PATH, libsqlConnection, libsqlDirect, LibsqlSidecarMissingError } from "../../src/datasource/libsql"; +import { amzDate, s3Connection, s3CreateBucket, s3Direct, s3DirectKeys, s3Path, s3Query, s3RemoveBucket, S3SidecarAddressError, S3SidecarMissingError, signS3Request, xmlValues } from "../../src/datasource/s3"; import { NODE_PLUGIN_FIXTURE_PLACEHOLDER_URL, NODE_PLUGIN_IDS, @@ -595,6 +596,8 @@ const LIBSQL_ALIAS = "e2e-libsql"; const COUCHDB_ALIAS = "e2e-couchdb"; /** The alias the run script gives the DynamoDB Local sidecar. */ const DYNAMODB_ALIAS = "e2e-dynamodb"; +/** The IP address of the S3 sidecar in the unit tests below (the sidecar has no alias: its address is the endpoint). */ +const S3_TEST_IP = "172.18.0.9"; /** The text of `scripts/run-in-docker.sh` and of `fixtures/firebird/init.sql`. */ const RUN_SCRIPT = readFileSync(join(__dirname, "..", "..", "scripts", "run-in-docker.sh"), "utf8"); @@ -1036,7 +1039,7 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = expect(startBody, "one database for every access key").toContain("-sharedDb"); }); - test("the run script starts, waits for and passes the DynamoDB Local sidecar only under the flag, next to the other three", () => { + test("the run script starts, waits for and passes the DynamoDB Local sidecar only under the flag, next to the other sidecars", () => { const lines = RUN_SCRIPT.split("\n"); for (const fn of ["start_dynamodb", "wait_for_dynamodb"]) { const calls = lines.map((line, index) => ({ line, index })).filter(({ line }) => line.trim() === fn); @@ -1055,8 +1058,8 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = expect(RUN_SCRIPT, "the readiness step shows the server's log on failure").toMatch(/wait_for_dynamodb\(\) \{[\s\S]*?docker logs --tail "\$LOG_TAIL_LINES" "\$DYNAMODB_CONTAINER"[\s\S]*?\n\}/); }); - test("the four sidecar readiness loops measure real elapsed time against STARTUP_TIMEOUT, so the time a probe takes counts (a loop that adds up its sleeps only fails here)", () => { - for (const fn of ["wait_for_firebird", "wait_for_libsql", "wait_for_couchdb", "wait_for_dynamodb"]) { + test("the five sidecar readiness loops measure real elapsed time against STARTUP_TIMEOUT, so the time a probe takes counts (a loop that adds up its sleeps only fails here)", () => { + for (const fn of ["wait_for_firebird", "wait_for_libsql", "wait_for_couchdb", "wait_for_dynamodb", "wait_for_s3"]) { const body = new RegExp(`${fn}\\(\\) \\{[\\s\\S]*?\\n\\}`).exec(RUN_SCRIPT)?.[0] ?? ""; expect(body, `${fn} exists`).not.toBe(""); expect(body, `${fn}: the start is recorded from the shell's SECONDS`).toContain("local waited=0 started=$SECONDS"); @@ -1069,14 +1072,14 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = const poll = Number(RUN_SCRIPT.match(/^readonly POLL_INTERVAL=(\d+)$/m)?.[1]); const request = Number(RUN_SCRIPT.match(/^readonly PROBE_REQUEST_TIMEOUT=(\d+)$/m)?.[1]); expect(poll + request, "the worst overshoot past STARTUP_TIMEOUT (one sleep and one probe) is small against it").toBeLessThanOrEqual(Number(RUN_SCRIPT.match(/^readonly STARTUP_TIMEOUT=(\d+)$/m)?.[1]) / 10); - // the overshoot above holds only if one probe is bounded as a whole: the Firebird, libSQL and DynamoDB probes are one request, the CouchDB probe shares one budget + // the overshoot above holds only if one probe is bounded as a whole: the Firebird, libSQL, DynamoDB and S3 probes are one request, the CouchDB probe shares one budget const functionOf = (name: string): string => new RegExp(`${name}\\(\\) \\{[\\s\\S]*?\\n\\}`).exec(RUN_SCRIPT)?.[0] ?? ""; - for (const fn of ["wait_for_firebird", "wait_for_libsql", "wait_for_dynamodb"]) { + for (const fn of ["wait_for_firebird", "wait_for_libsql", "wait_for_dynamodb", "wait_for_s3"]) { expect(functionOf(fn).match(/docker exec/g), `${fn}: the probe is exactly one docker exec`).toHaveLength(1); } expect(functionOf("wait_for_firebird").match(/isql/g), "wait_for_firebird: one isql run, under the container's own timeout").toHaveLength(1); expect(functionOf("wait_for_firebird"), "the isql run is killed after PROBE_REQUEST_TIMEOUT").toContain('timeout -s KILL "$PROBE_REQUEST_TIMEOUT" /opt/firebird/bin/isql'); - for (const fn of ["wait_for_libsql", "wait_for_dynamodb"]) { + for (const fn of ["wait_for_libsql", "wait_for_dynamodb", "wait_for_s3"]) { expect(functionOf(fn).match(/fetch\(/g), `${fn}: the probe is exactly one fetch`).toHaveLength(1); expect(functionOf(fn).match(/AbortSignal\.timeout\(/g), `${fn}: that fetch aborts after the request limit`).toHaveLength(1); } @@ -1088,7 +1091,9 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = test("every container the run script starts with `docker run -d` mounts a tmpfs over each volume its image declares, so the cleanup leaves no anonymous volume behind", () => { // Measured by hand with `docker inspect --format '{{json .Config.Volumes}}'` on the images the script pins (the default APP_IMAGE, PLAYWRIGHT_IMAGE, - // POSTGRES_IMAGE, FIREBIRD_IMAGE, LIBSQL_IMAGE, COUCHDB_IMAGE and DYNAMODB_IMAGE). An empty list is an image whose answer was `null`: it declares no volume. + // POSTGRES_IMAGE, FIREBIRD_IMAGE, LIBSQL_IMAGE, COUCHDB_IMAGE, DYNAMODB_IMAGE and S3_IMAGE). An empty list is an image whose answer was `null`: it declares no volume. + // The S3 image (versity/versitygw) declares none either, yet its row lists two paths: they are directories the script chooses for the server (objects and the metadata + // sidecar), mounted as tmpfs so that the objects live in memory and no layer or volume holds them; the test requires the same mount over them as over a declared volume. // Without a mount over a declared path Docker creates an anonymous volume per container, and the trap's container removal does not remove it. // The test needs no docker: when an image pin changes, measure again and change the facts below. // `run_tests` is the one foreground container: the runner (PLAYWRIGHT_IMAGE, no declared volume) runs with `docker run --rm`, which removes the container @@ -1101,6 +1106,7 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = start_libsql: { constants: ["LIBSQL_DATA_DIR"], paths: ["/var/lib/sqld"], detached: true }, start_couchdb: { constants: ["COUCHDB_DATA_DIR"], paths: ["/opt/couchdb/data"], detached: true }, start_dynamodb: { constants: [], paths: [], detached: true }, + start_s3: { constants: ["S3_DATA_DIR", "S3_META_DIR"], paths: ["/data", "/meta"], detached: true }, run_tests: { constants: [], paths: [], detached: false }, }; const invocations = containerInvocations(RUN_SCRIPT); @@ -1115,7 +1121,7 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = expect(invocation.detached, `${fn}: detached as the facts say`).toBe(facts.detached); expect(facts.constants, `${fn}: one constant per declared path`).toHaveLength(facts.paths.length); facts.constants.forEach((constant, index) => { - expect(scriptConstant(constant), `${constant} holds the path its image declares`).toBe(facts.paths[index]); + expect(scriptConstant(constant), `${constant} holds the path its image declares (or, for the S3 sidecar, the directory the script chose)`).toBe(facts.paths[index]); expect(invocation.command, `${fn}: a tmpfs over ${facts.paths[index]}`).toContain(`--tmpfs "$${constant}"`); }); if (facts.paths.length === 0) { @@ -1242,4 +1248,234 @@ test.describe("node-service sidecar helpers", { tag: [TAGS.NODE_SERVICE] }, () = await new Promise((resolve) => server.close(() => resolve())); } }); + test("s3Connection builds a plain-HTTP endpoint on the sidecar's IP address from the environment, with the suite's throw-away key pair", () => { + expect(s3Connection({ [S3.IP_ENV]: S3_TEST_IP })).toEqual({ + endpointUrl: `http://${S3_TEST_IP}:${S3.PORT}`, + accessKey: S3.ACCESS_KEY, + secretKey: S3.SECRET_KEY, + region: S3.REGION, + }); + }); + + test("s3Connection throws a named error that names the variable and the flag when the IP is unset or empty, and another when it is not an IPv4 address", () => { + for (const env of [{}, { [S3.IP_ENV]: "" }]) { + expect(() => s3Connection(env), `env ${JSON.stringify(env)}`).toThrow(S3SidecarMissingError); + expect(() => s3Connection(env)).toThrow(S3.IP_ENV); + expect(() => s3Connection(env)).toThrow(`${RUN_FLAGS.INCLUDE_NODE_SERVICE_SIDECARS}=1`); + } + // a name would make the SDK address `.`: every shape that is not four decimal octets is refused, with the offending value in the message + for (const value of ["e2e-s3", "s3.example.test", "172.18.0", "172.18.0.9.1", "172.18.0.256", "172.018.0.9", "172.18.0.9:7070", "http://172.18.0.9", " 172.18.0.9"]) { + expect(() => s3Connection({ [S3.IP_ENV]: value }), `value ${JSON.stringify(value)}`).toThrow(S3SidecarAddressError); + expect(() => s3Connection({ [S3.IP_ENV]: value })).toThrow(JSON.stringify(value)); + } + expect(() => s3Connection({ [S3.IP_ENV]: "0.0.0.0" }), "control: a valid address passes the same check").not.toThrow(); + }); + + test("the run script's S3 values equal S3 in the constants, and the sidecar is reached by IP only (no alias, no --add-host, no name for a bucket to be derived from)", () => { + expect(Number(RUN_SCRIPT.match(/^readonly S3_PORT=(\d+)$/m)?.[1]), "port").toBe(S3.PORT); + expect(scriptConstant("S3_ACCESS_KEY"), "access key").toBe(S3.ACCESS_KEY); + expect(scriptConstant("S3_SECRET_KEY"), "secret key").toBe(S3.SECRET_KEY); + expect(scriptConstant("S3_REGION"), "region").toBe(S3.REGION); + expect(scriptConstant("DEFAULT_S3_IMAGE"), "the image is pinned by tag and digest").toMatch(/^versity\/versitygw:v\d+\.\d+\.\d+@sha256:[0-9a-f]{64}$/); + const startBody = /start_s3\(\) \{[\s\S]*?\n\}/.exec(RUN_SCRIPT)?.[0] ?? ""; + expect(startBody, "start_s3 exists").not.toBe(""); + expect(startBody, "the runner gets the IP address, not a name").toContain(`SIDECAR_RUNNER_ENV+=(-e "${S3.IP_ENV}=\${S3_IP}")`); + expect(startBody, "no network alias: nothing can resolve a name for the sidecar").not.toContain("--network-alias"); + expect(startBody, "no --add-host entry and no change of SIDECAR_ADD_HOST").not.toMatch(/--add-host|SIDECAR_ADD_HOST/); + expect(startBody, "the objects and the metadata sidecar of the POSIX backend live in tmpfs mounts").toContain('--tmpfs "$S3_DATA_DIR" --tmpfs "$S3_META_DIR"'); + expect(startBody, "the server is started with the POSIX backend, its metadata sidecar directory and its data directory").toContain('posix --sidecar "$S3_META_DIR" "$S3_DATA_DIR"'); + expect(startBody, "the key pair goes by the image's environment variables, not on the server's command line").toContain('-e ROOT_ACCESS_KEY_ID="$S3_ACCESS_KEY" -e ROOT_SECRET_ACCESS_KEY="$S3_SECRET_KEY"'); + expect(startBody.split("\n").filter((line) => line.includes("docker run") || line.trim().startsWith('"$S3_IMAGE"')).join("\n"), "no key on the command line of the server").not.toMatch(/--access|--secret/); + const lines = RUN_SCRIPT.split("\n"); + const codeLines = lines.filter((line) => !line.trim().startsWith("#")).join("\n"); + expect(codeLines.match(new RegExp(S3.IP_ENV, "g")), "the IP variable is named once in the script's code, in start_s3").toHaveLength(1); + expect(codeLines, "no `--add-host` of the S3 sidecar anywhere in the script's code").not.toMatch(/--add-host[^\n]*S3_/); + }); + + test("the run script starts, waits for and cleans up the S3 sidecar only under the flag, after the DynamoDB Local one", () => { + const lines = RUN_SCRIPT.split("\n"); + for (const fn of ["start_s3", "wait_for_s3"]) { + const calls = lines.map((line, index) => ({ line, index })).filter(({ line }) => line.trim() === fn); + expect(calls, `${fn} is called exactly once`).toHaveLength(1); + const call = calls[0] as { index: number }; + expect(lines[call.index - 1]?.trim(), `${fn} is the first line of an if node_service_sidecars_enabled block`).toBe("if node_service_sidecars_enabled; then"); + expect(lines[call.index + 1]?.trim(), `${fn} is the only line of that block`).toBe("fi"); + } + const indexOf = (fn: string): number => lines.findIndex((line) => line.trim() === fn); + expect(indexOf("start_s3"), "the S3 sidecar starts after the DynamoDB Local one").toBeGreaterThan(indexOf("start_dynamodb")); + expect(indexOf("wait_for_s3"), "and is waited for after it").toBeGreaterThan(indexOf("wait_for_dynamodb")); + expect(indexOf("start_s3"), "both sidecars start before the app (the app container is told their addresses)").toBeLessThan(indexOf("start_app")); + expect(RUN_SCRIPT, "the cleanup trap removes the container").toMatch(/docker rm -f [^\n]*"\$S3_CONTAINER"/); + expect(RUN_SCRIPT, "the readiness step shows the server's log on failure").toMatch(/wait_for_s3\(\) \{[\s\S]*?docker logs --tail "\$LOG_TAIL_LINES" "\$S3_CONTAINER"[\s\S]*?\n\}/); + expect(RUN_SCRIPT, "the runner is started with the extra environment of the sidecars").toContain('"${SIDECAR_RUNNER_ENV[@]}"'); + }); + + test("the S3 readiness call is one signed ListBuckets request with a request limit, accepts exactly one status and needs the answer's XML", () => { + const body = /wait_for_s3\(\) \{[\s\S]*?\n\}/.exec(RUN_SCRIPT)?.[0] ?? ""; + expect(body, "the fetch aborts after the request limit").toContain("AbortSignal.timeout($((PROBE_REQUEST_TIMEOUT * 1000)))"); + expect(body, "a signed request: the server verifies the signature, so an unsigned probe would not prove the credentials").toContain("AWS4-HMAC-SHA256 Credential="); + expect(body, "the signature covers host, content hash and date").toContain("SignedHeaders=host;x-amz-content-sha256;x-amz-date"); + expect(body, "ready only on the one accepted status (a named constant), not on any answer").toContain("r.status === $S3_HTTP_OK"); + expect(Number(RUN_SCRIPT.match(/^readonly S3_HTTP_OK=(\d+)$/m)?.[1]), "the accepted status is 200").toBe(200); + expect(body, "and on the listing's root element in the body").toContain("t.includes(' process.exit(1))"); + expect(body, "the probe runs in the echo container, over the run network, against the sidecar's IP").toMatch(/S3_PROBE_HOST="\$\{S3_IP\}:\$\{S3_PORT\}"[^\n]*"\$ECHO_CONTAINER" node -e/); + expect(body, "the key pair reaches the probe through the container's environment").toContain('-e S3_PROBE_KEY="$S3_ACCESS_KEY" -e S3_PROBE_SECRET="$S3_SECRET_KEY"'); + expect(body, "nothing is logged but the wait time").not.toMatch(/log "[^"]*(SECRET|KEY)/); + const request = Number(RUN_SCRIPT.match(/^readonly PROBE_REQUEST_TIMEOUT=(\d+)$/m)?.[1]); + const startupTimeout = Number(RUN_SCRIPT.match(/^readonly STARTUP_TIMEOUT=(\d+)$/m)?.[1]); + expect(request, "a positive request limit small against the startup timeout").toBeGreaterThan(0); + expect(request).toBeLessThanOrEqual(startupTimeout / 10); + }); + + test("signS3Request reproduces the three examples of AWS's Signature Version 4 documentation for S3 (a GET with a range, a listing with a query, a PUT with a body)", () => { + const secretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"; + const common = { host: "examplebucket.s3.amazonaws.com", accessKey: "AKIAIOSFODNN7EXAMPLE", secretKey, region: "us-east-1", now: new Date("2013-05-24T00:00:00.000Z") }; + const signatureOf = (headers: Record): string | undefined => headers.authorization?.split("Signature=")[1]; + const get = signS3Request({ ...common, method: "GET", path: "/test.txt", query: "", headers: { range: "bytes=0-9" }, body: Buffer.alloc(0) }); + expect(get.authorization).toBe( + "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41", + ); + expect(get["x-amz-date"], "the date header").toBe("20130524T000000Z"); + expect(get["x-amz-content-sha256"], "the hash of the empty body").toBe("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + const list = signS3Request({ ...common, method: "GET", path: "/", query: s3Query({ "max-keys": "2", prefix: "J" }), headers: {}, body: Buffer.alloc(0) }); + expect(signatureOf(list), "a listing with a canonical query").toBe("34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7"); + const put = signS3Request({ + ...common, + method: "PUT", + path: s3Path("examplebucket", "x").replace("/examplebucket/x", "/test%24file.text"), + query: "", + headers: { date: "Fri, 24 May 2013 00:00:00 GMT", "x-amz-storage-class": "REDUCED_REDUNDANCY" }, + body: Buffer.from("Welcome to Amazon S3."), + }); + expect(signatureOf(put), "a PUT with a body and extra signed headers").toBe("98ad721746da40c64f1a55b78f14c238d841ea1380cd77a1b5971af0ece108bd"); + // a header value is trimmed and its runs of whitespace collapse to one space before it is signed (SigV4), so these three spell one value + const spaced = (value: string): string | undefined => signatureOf(signS3Request({ ...common, method: "GET", path: "/test.txt", query: "", headers: { "x-amz-meta-note": value }, body: Buffer.alloc(0) })); + expect(spaced(" a \t b "), "runs of whitespace and the ends collapse").toBe(spaced("a b")); + expect(spaced("a b"), "a double space is one space").toBe(spaced("a b")); + expect(spaced("ab"), "control: a value without the space is another value").not.toBe(spaced("a b")); + // negative controls: another secret, or another body, gives another signature (the vector above is not matched by accident) + const otherSecret = signS3Request({ ...common, secretKey: `${secretKey}x`, method: "GET", path: "/test.txt", query: "", headers: { range: "bytes=0-9" }, body: Buffer.alloc(0) }); + expect(signatureOf(otherSecret)).not.toBe("f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"); + const otherBody = signS3Request({ ...common, method: "GET", path: "/test.txt", query: "", headers: { range: "bytes=0-9" }, body: Buffer.from("x") }); + expect(signatureOf(otherBody)).not.toBe("f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"); + }); + + test("s3Path, s3Query, amzDate and xmlValues encode and decode as S3 does (keys per segment, a sorted query, the signing date, the XML entities)", () => { + expect(s3Path(), "no bucket").toBe("/"); + expect(s3Path("b"), "a bucket").toBe("/b"); + expect(s3Path("b", "dir/e2e file.txt"), "a space is encoded, the slash kept").toBe("/b/dir/e2e%20file.txt"); + expect(s3Path("b", "ünï/日本語 (1)!'*.txt"), "unicode and the characters encodeURIComponent leaves are encoded").toBe("/b/%C3%BCn%C3%AF/%E6%97%A5%E6%9C%AC%E8%AA%9E%20%281%29%21%27%2A.txt"); + expect(s3Path("b", "a+b&c=d?e#f%g"), "reserved characters").toBe("/b/a%2Bb%26c%3Dd%3Fe%23f%25g"); + expect(s3Query({ prefix: "p/", "list-type": "2" }), "sorted, encoded").toBe("list-type=2&prefix=p%2F"); + expect(s3Query({ "a/": "1", "a-": "2" }), "sorted after encoding: `a%2F` (the raw `a/` sorts after `a-`) comes first").toBe("a%2F=1&a-=2"); + expect(s3Query({ k: "b", "k ": "a" }), "a name that is a prefix of another encoded name comes first").toBe("k=b&k%20=a"); + expect(s3Query(), "empty").toBe(""); + expect(amzDate(new Date("2026-11-25T06:43:40.123Z")), "the signing date has no separators and no fraction").toBe("20261125T064340Z"); + const xml = "a&b <c> "d" 'e' λ 😀plainx"; + expect(xmlValues(xml, "Key"), "both keys, in order, decoded").toEqual(["a&b \"d\" 'e' λ \u{1F600}", "plain"]); + expect(xmlValues(xml, "Missing"), "a tag that is not there").toEqual([]); + }); + + test("s3Direct sends a signed, path-style request (key, scope, signed headers, content hash, body, content type) and returns status, headers, bytes and text; another key pair replaces the connection's", async () => { + const received: { method?: string; url?: string; host?: string; authorization?: string; hash?: string; contentType?: string; body: string }[] = []; + const server: Server = createServer((request: IncomingMessage, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + received.push({ + method: request.method, + url: request.url, + host: request.headers.host, + authorization: request.headers.authorization, + hash: request.headers["x-amz-content-sha256"] as string | undefined, + contentType: request.headers["content-type"], + body: Buffer.concat(chunks).toString("utf8"), + }); + response.writeHead(received.length === 1 ? 200 : 403, { "Content-Type": "application/xml", "x-e2e": "yes" }).end(received.length === 1 ? "ok ü" : "AccessDenied"); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = (server.address() as AddressInfo).port; + const connection = { endpointUrl: `http://127.0.0.1:${port}`, accessKey: "e2eKey", secretKey: "e2eSecret", region: "eu-test-1" }; + try { + const put = await s3Direct(connection, { method: "PUT", bucket: "bkt", key: "dir/e2e file.txt", query: { "x-id": "PutObject" }, body: "hello", contentType: "text/plain" }); + const denied = await s3Direct(connection, { method: "GET", bucket: "bkt", credentials: { accessKey: "otherKey", secretKey: "otherSecret" } }); + + expect({ status: put.status, type: put.headers["content-type"], extra: put.headers["x-e2e"], text: put.text, bytes: put.body.length }, "a 200 answer: status, headers with lower-case names, text and bytes").toEqual({ + status: 200, + type: "application/xml", + extra: "yes", + text: "ok ü", + bytes: Buffer.byteLength("ok ü"), + }); + expect(denied, "an HTTP error is returned, not thrown").toMatchObject({ status: 403, text: "AccessDenied" }); + expect(received.map(({ method, url, host, contentType, body }) => ({ method, url, host, contentType, body })), "method, path-style URL with the encoded key and the query, host with the port, type, body").toEqual([ + { method: "PUT", url: "/bkt/dir/e2e%20file.txt?x-id=PutObject", host: `127.0.0.1:${port}`, contentType: "text/plain", body: "hello" }, + { method: "GET", url: "/bkt", host: `127.0.0.1:${port}`, contentType: undefined, body: "" }, + ]); + const first = parseSigV4Authorization(received[0]?.authorization); + expect({ ...first, signature: undefined, date: undefined }, "the first call is signed with the connection's key, region and service, and covers the content type").toEqual({ + accessKey: "e2eKey", + date: undefined, + region: "eu-test-1", + service: "s3", + signedHeaders: ["content-type", "host", "x-amz-content-sha256", "x-amz-date"], + signature: undefined, + }); + expect(received[0]?.hash, "the content hash is the SHA-256 of the body").toBe("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"); + expect(parseSigV4Authorization(received[1]?.authorization)?.accessKey, "the replacement key pair signs the second call").toBe("otherKey"); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }); + + test("s3CreateBucket, s3DirectKeys and s3RemoveBucket drive the server's bucket API, tolerate a bucket that is gone, and throw on any other refusal", async () => { + const calls: string[] = []; + const created: { body: string; contentType?: string }[] = []; + let mode: "normal" | "gone" | "refuse-list" | "refuse-delete" = "normal"; + const keys = ["a&b.txt", "dir/ü.txt"]; + const server: Server = createServer((request: IncomingMessage, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + calls.push(`${request.method} ${request.url}`); + if (request.method === "PUT") created.push({ body: Buffer.concat(chunks).toString("utf8"), contentType: request.headers["content-type"] }); + const listing = request.method === "GET" && (request.url ?? "").includes("list-type=2"); + if (mode === "gone" && !(request.method === "PUT")) return void response.writeHead(404).end("NoSuchBucket"); + if (listing && mode === "refuse-list") return void response.writeHead(403).end("AccessDenied"); + if (request.method === "DELETE" && mode === "refuse-delete" && request.url === "/bkt") return void response.writeHead(409).end("BucketNotEmpty"); + if (listing) return void response.writeHead(200).end(`${keys.map((key) => `${key.replace("&", "&")}`).join("")}`); + response.writeHead(request.method === "DELETE" ? 204 : 200).end(); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const connection = { endpointUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, accessKey: "k", secretKey: "s", region: "r" }; + try { + await s3CreateBucket(connection, "bkt"); + expect(created, "the bucket is created with its location constraint (the connection's region), which a region other than us-east-1 requires").toEqual([ + { body: `r`, contentType: "application/xml" }, + ]); + expect(await s3DirectKeys(connection, "bkt"), "the keys, decoded").toEqual(keys); + calls.length = 0; + await s3RemoveBucket(connection, "bkt"); + expect(calls, "the listing, one delete per object, then the bucket").toEqual(["GET /bkt?list-type=2", "DELETE /bkt/a%26b.txt", "DELETE /bkt/dir/%C3%BC.txt", "DELETE /bkt"]); + + mode = "gone"; + calls.length = 0; + await s3RemoveBucket(connection, "bkt"); + expect(calls, "a bucket that is gone: one listing, nothing else, no error").toEqual(["GET /bkt?list-type=2"]); + + mode = "refuse-list"; + await expect(s3RemoveBucket(connection, "bkt"), "a refused listing is a leak that must not be silent").rejects.toThrow("403"); + mode = "refuse-delete"; + await expect(s3RemoveBucket(connection, "bkt"), "a bucket the server will not delete").rejects.toThrow("409"); + mode = "gone"; + await expect(s3CreateBucket(connection, "bkt"), "control: creating works while the server answers 200 for a PUT").resolves.toBeUndefined(); + mode = "refuse-list"; + await expect(s3DirectKeys(connection, "bkt"), "a refused listing throws").rejects.toThrow("403"); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }); }); diff --git a/e2e/tests/foundation/run-selection.spec.ts b/e2e/tests/foundation/run-selection.spec.ts index 3b96496cae..5d5cb70098 100644 --- a/e2e/tests/foundation/run-selection.spec.ts +++ b/e2e/tests/foundation/run-selection.spec.ts @@ -566,8 +566,8 @@ test.describe("run selection: the node-service sidecar tests are opt-in", () => }); }); -/** The names of the helpers whose use makes a spec need a sidecar (Firebird, libSQL, CouchDB, DynamoDB Local), and the tag every test of such a spec must wear. */ -const SIDECAR_HELPERS = ["firebirdConnection", "libsqlConnection", "couchdbConnection", "dynamodbConnection"] as const; +/** The names of the helpers whose use makes a spec need a sidecar (Firebird, libSQL, CouchDB, DynamoDB Local, S3), and the tag every test of such a spec must wear. */ +const SIDECAR_HELPERS = ["firebirdConnection", "libsqlConnection", "couchdbConnection", "dynamodbConnection", "s3Connection"] as const; const SIDECAR_HELPER = SIDECAR_HELPERS[0]; const SIDECAR_TAG_KEY = "NODE_SERVICE_SIDECAR"; @@ -589,7 +589,7 @@ function detailsTagWithSidecar(details: ts.Expression): boolean { } /** - * The tests of a spec source that does not wear `TAGS.NODE_SERVICE_SIDECAR`, when the source uses a sidecar helper (`firebirdConnection`, `libsqlConnection`, `couchdbConnection` or `dynamodbConnection`; a spec that needs the + * The tests of a spec source that does not wear `TAGS.NODE_SERVICE_SIDECAR`, when the source uses a sidecar helper (`firebirdConnection`, `libsqlConnection`, `couchdbConnection`, `dynamodbConnection` or `s3Connection`; a spec that needs the * sidecar: untagged, its tests would run in the default run, where the sidecar is not started). A source that does not use the helper * reports nothing. A tag on an enclosing `test.describe*(title, details, body)` counts for every test inside. Each result is `line `. * Limits: the same as `untaggedSuperAdminTests` (a `test` passed through a parameter is not recognised, a tag through a variable is not followed). @@ -624,7 +624,7 @@ function untaggedSidecarTests(source: string, fileName = "synthetic.spec.ts"): s } test.describe("run selection: every test that needs a sidecar carries the opt-in tag", () => { - test("every spec that uses a sidecar helper tags all its tests with TAGS.NODE_SERVICE_SIDECAR, and the Firebird, libSQL, CouchDB and DynamoDB Local specs do use one", () => { + test("every spec that uses a sidecar helper tags all its tests with TAGS.NODE_SERVICE_SIDECAR, and the Firebird, libSQL, CouchDB, DynamoDB Local and S3 specs do use one", () => { const untagged: string[] = []; const users: string[] = []; for (const file of specFilesUnder(join(__dirname, ".."))) { @@ -634,10 +634,11 @@ test.describe("run selection: every test that needs a sidecar carries the opt-in untagged.push(...untaggedSidecarTests(source, file).map((entry) => `${file}: ${entry}`)); } - expect(users.map((file) => file.split("tests/")[1]), "the specs that use the helper (a positive control that the guard looks at the CouchDB, the DynamoDB Local, the Firebird and the libSQL spec)").toEqual([ + expect(users.map((file) => file.split("tests/")[1]), "the specs that use the helper (a positive control that the guard looks at the CouchDB, the DynamoDB Local, the Firebird, the S3 and the libSQL spec)").toEqual([ "datasource/plugin-couchdb.spec.ts", "datasource/plugin-dynamodb-local.spec.ts", "datasource/plugin-firebird.spec.ts", + "datasource/plugin-s3-server.spec.ts", "datasource/plugin-turso-libsql.spec.ts", ]); expect(untagged, "tests of a sidecar spec without TAGS.NODE_SERVICE_SIDECAR (they would run, and fail, in the default run)").toEqual([]); @@ -658,5 +659,7 @@ test.describe("run selection: every test that needs a sidecar carries the opt-in expect(untaggedSidecarTests(`const c = couchdbConnection();\ntest.describe("g", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { test("a", async () => {}); });`), "and accepts its describe tag").toEqual([]); expect(untaggedSidecarTests(`const c = dynamodbConnection();\ntest("a", async () => {});`), "the DynamoDB Local helper is asked too").toEqual(["line 2"]); expect(untaggedSidecarTests(`const c = dynamodbConnection();\ntest.describe("g", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { test("a", async () => {}); });`), "and accepts its describe tag").toEqual([]); + expect(untaggedSidecarTests(`const c = s3Connection();\ntest("a", async () => {});`), "the S3 helper is asked too").toEqual(["line 2"]); + expect(untaggedSidecarTests(`const c = s3Connection();\ntest.describe("g", { tag: [TAGS.NODE_SERVICE, TAGS.NODE_SERVICE_SIDECAR] }, () => { test("a", async () => {}); });`), "and accepts its describe tag").toEqual([]); }); }); From 7783e2dd335ab4aa995bf15ceb0d02c27adbbcbd Mon Sep 17 00:00:00 2001 From: Ludo Mikula Date: Wed, 25 Nov 2026 08:47:12 +0100 Subject: [PATCH 20/20] test: number the node-service defect findings in the shared D-series Claude-Session: https://claude.ai/code/session_015KPtHMWb4EyLtt5JPr1vtb --- e2e/README.md | 104 +++++++++--------- e2e/tests/datasource/plugin-aws-sdk.spec.ts | 4 +- e2e/tests/datasource/plugin-couchdb.spec.ts | 20 ++-- e2e/tests/datasource/plugin-duckdb.spec.ts | 8 +- .../datasource/plugin-dynamodb-local.spec.ts | 12 +- e2e/tests/datasource/plugin-firebird.spec.ts | 2 +- e2e/tests/datasource/plugin-graphql.spec.ts | 6 +- .../plugin-openapi-wrappers-apps.spec.ts | 14 +-- .../plugin-openapi-wrappers-data.spec.ts | 4 +- e2e/tests/datasource/plugin-openapi.spec.ts | 4 +- e2e/tests/datasource/plugin-s3-server.spec.ts | 16 +-- .../plugin-supabase-storage.spec.ts | 22 ++-- .../datasource/plugin-turso-libsql.spec.ts | 16 +-- .../datasource/plugin-turso-slack.spec.ts | 4 +- 14 files changed, 118 insertions(+), 118 deletions(-) diff --git a/e2e/README.md b/e2e/README.md index 33da475a5a..aaff6acd98 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -8,7 +8,7 @@ the Extensions panel and the visual components. Apps are seeded through the HTTP Rules for writing or changing tests: [AGENTS.md](AGENTS.md). -Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; Firebird (node-firebird over TCP, D12) runs against a Firebird sidecar of its own that only a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` starts, and a default run neither starts it nor lists or runs those tests, and Turso also runs against a real libSQL server (sqld, D13) the same way, where the `libsql://` to `https://` rewrite of the URL is not covered because the sidecar speaks plain HTTP, and CouchDB also runs against a real Apache CouchDB server (D14) the same way, where the JWT credential and cookie sessions are not covered because the image's default configuration has no JWT authentication handler and the plugin sends the `Authorization` header only, and DynamoDB also runs against a real DynamoDB Local server (D15) the same way, where indexes, transactions, batch operations, streams and the request signature (the server verifies none) are not covered, and S3 also runs against a real S3-compatible server (versitygw, D16) the same way, reached by its IP address only (it has no name), where a real AWS S3, multipart upload, an expired presigned URL, versioning and ACLs are not covered; the UiPath plugin fails every query and its query configuration before it sends a request (D9, NSD-6 candidate); no other plugin query is run yet); the server and +Not covered: Firefox and WebKit; the multi-container compose setup; databases other than PostgreSQL (the data sources that run in node-service are covered by their catalogue, D3: which plugins the image serves and that each definition has a form and a query config; of the plugins DuckDB runs queries, D4, embedded in the app container with no network, and Turso, Slack, GitLab, Shopify, the generic Open API plugin and the Open API wrappers CouchDB, Jira, Datadog, WooCommerce, Supabase Management API, Lowcoder API, OpenAI, APITemplate.io and Carbone run queries (and, for Open API, build the data source form's dynamic config from a document the echo serves), and DynamoDB and S3 (AWS SDK v3, signed requests; the S3 calls that take a bucket go to the echo's IP address, `E2E_ECHO_IP`, never to the alias), D5 to D10, and Supabase Storage (supabase-js against a project URL on the echo, the key in `apikey` and `authorization`), D11, against the echo sidecar, which proves the request they build and the path of a canned answer into the app, not the vendor service; Firebird (node-firebird over TCP, D12) runs against a Firebird sidecar of its own that only a run with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` starts, and a default run neither starts it nor lists or runs those tests, and Turso also runs against a real libSQL server (sqld, D13) the same way, where the `libsql://` to `https://` rewrite of the URL is not covered because the sidecar speaks plain HTTP, and CouchDB also runs against a real Apache CouchDB server (D14) the same way, where the JWT credential and cookie sessions are not covered because the image's default configuration has no JWT authentication handler and the plugin sends the `Authorization` header only, and DynamoDB also runs against a real DynamoDB Local server (D15) the same way, where indexes, transactions, batch operations, streams and the request signature (the server verifies none) are not covered, and S3 also runs against a real S3-compatible server (versitygw, D16) the same way, reached by its IP address only (it has no name), where a real AWS S3, multipart upload, an expired presigned URL, versioning and ACLs are not covered; the UiPath plugin fails every query and its query configuration before it sends a request (D9, D-71 candidate); no other plugin query is run yet); the server and node-service as separate units; any request to a real external host (the network guard blocks them); the app-level layouts `navLayout` and `mobileTabLayout` (open decision). The functional behaviour of the nine components that need a cloud service, credentials, third-party scripts or a device (3 Agora meetings, `turnstileCaptcha`, `scanner`, @@ -256,7 +256,7 @@ e2e/ fixtures/firebird/init.sql Firebird sidecar data (opt-in sidecar): FB_ITEMS, FB_NOTES fixtures/dsl/.json 112 DSL defaults recorded from the editor fixtures/dsl/n8n/ n8nQuery.json (the query the editor saved for "Retrieve all workflows", reduced to type and action) and n8nDatasource.json (the data source form's create body, without workspace, target or key); no id or timestamp of the recording session survives (a unit test checks); a subfolder so the component catalog test does not count them - fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb` (the form's body with placeholders, `couchdbQuery.json` is the editor's saved `allDBs`, and one query recording per further operation of the CouchDB sidecar tests, `couchdbQuery.json`: Put, Get, Delete, DocPut, DocGet, DocDelete, DocGetAll; recorded in a session on a stack with the sidecar, the data source typed with the sidecar's own host and login, operation picked in the editor's Resource and Operation lists; the field values of every recording are the editor's empty defaults, so no host or login survives), `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, NSD-6 candidate), `firebird` (the form's body with the sidecar's own host, port, database path and throw-away login, because the host cannot be a placeholder, and the editor's saved query; recorded in a session on a stack with the sidecar), `supabase` (the form's body, and one query recording per action: `supabaseQuery.json` is listBuckets, the others are `supabaseQuery.json`: ListObjects, ReadFile, UploadData, DeleteFile, CreateSignedUrl), `dynamodb` and `s3` (the form's body, and one query recording per action because the saved query differs by action: `Query.json` is the editor's default action, the others are `Query.json`, loaded by `recordedPluginQuery(id, "")`: `dynamodb` Query, Scan, PutItem, GetItem, UpdateItem, DeleteItem, ListTables, CreateTable (the first four were recorded against the echo, the other four in a session on a stack with the DynamoDB Local sidecar: the data source typed with the sidecar's own endpoint and throw-away key, one query per action picked in the editor's Action list; the field values are the editor's defaults, so no host or key survives); `s3` listBuckets, ListObjects, ReadFile, UploadData, DeleteFile) + fixtures/dsl/plugins/ `/Datasource.json` and `Query.json` per node-service data source plugin (loaders `recordedPluginQuery` and `recordedPluginDatasource`, same reduction and no-session-value rule as `fixtures/dsl/n8n/`); a subfolder so the component catalog test does not count them; recorded so far: `duckdb`, `turso`, `slack`, `gitlab`, `shopify`, `openApi` (its data source body keeps the `extra` the form stored: the spec text and the key field definition), `couchdb` (the form's body with placeholders, `couchdbQuery.json` is the editor's saved `allDBs`, and one query recording per further operation of the CouchDB sidecar tests, `couchdbQuery.json`: Put, Get, Delete, DocPut, DocGet, DocDelete, DocGetAll; recorded in a session on a stack with the sidecar, the data source typed with the sidecar's own host and login, operation picked in the editor's Resource and Operation lists; the field values of every recording are the editor's empty defaults, so no host or login survives), `jira`, `datadog`, `woocommerce`, `supabaseApi`, `lowcoder`, `OpenAI`, `apiTemplate`, `carboneIo`, `uiPath` (their forms have no dynamic config, so the body holds only the typed fields; the queries are the editor's saved defaults for one read-only operation each; `uiPath`'s query is built by hand in the shape the editor saved for the others, because the editor cannot list that plugin's operations, D-71 candidate), `firebird` (the form's body with the sidecar's own host, port, database path and throw-away login, because the host cannot be a placeholder, and the editor's saved query; recorded in a session on a stack with the sidecar), `supabase` (the form's body, and one query recording per action: `supabaseQuery.json` is listBuckets, the others are `supabaseQuery.json`: ListObjects, ReadFile, UploadData, DeleteFile, CreateSignedUrl), `dynamodb` and `s3` (the form's body, and one query recording per action because the saved query differs by action: `Query.json` is the editor's default action, the others are `Query.json`, loaded by `recordedPluginQuery(id, "")`: `dynamodb` Query, Scan, PutItem, GetItem, UpdateItem, DeleteItem, ListTables, CreateTable (the first four were recorded against the echo, the other four in a session on a stack with the DynamoDB Local sidecar: the data source typed with the sidecar's own endpoint and throw-away key, one query per action picked in the editor's Action list; the field values are the editor's defaults, so no host or key survives); `s3` listBuckets, ListObjects, ReadFile, UploadData, DeleteFile) src/ constants.ts TAGS, RUN_FLAGS, D3_RETRY_ANNOTATION, API paths, timeouts with reasons, PRODUCTS, labels fixtures.ts `test` with networkGuard, apiUser, newUserSession, actor, superAdmin; uniqueEmail @@ -295,18 +295,18 @@ Test titles carry these ids. - D1 a PostgreSQL query feeds a text and a table, write queries re-read; D2 table with query data (sort, page, filter, edit). - D3 the plugin catalogue of node-service: the image serves exactly the registered node plugins, each definition has a form and a query config, the Java-native types carry no definition (`@node-service`; the catalogue only, no plugin query runs). - D4 the DuckDB plugin of node-service, run in the app container with an in-memory database and no network: rows, the published view after a click, a BIGINT as a string, a fresh database per run, a syntax error as a failed query (`@node-service`). -- D5 the Turso and Slack plugins of node-service against the echo sidecar: a Turso query sends one Hrana pipeline and answers its rows, `includeRaw` answers values and raw, a non-OK answer and an `error` result fail the query (the latter prints `[object Object]`, NSD-1 candidate), the published view after a click; a Slack query posts the form payload to the webhook (`@node-service`; the request shape and the answer's path into the app, not the vendor service). -- D6 the GitLab and Shopify GraphQL plugins of node-service against the echo sidecar: a GitLab query posts the query, the variables and every header (data source, query and the access token), a GraphQL error answer fails the query, the published view after a click; a Shopify query reaches the endpoint, and the header the query sets does not (NSD-2 candidate) (`@node-service`; the request shape and the answer's path into the app, not the vendor service). -- D7 the generic Open API plugin of node-service against the echo sidecar: the data source form's dynamic config reads the OpenAPI document from its URL (the echo serves a canned document) and answers the spec and the key field, an operation runs against the server URL with the key in the header the document names, the key comes from the data source (no key, no header), an error status answers its body as a successful result (NSD-4 candidate), the published view after a click, the dynamic config answer is cached in memory per request body, with no expiry (observation) (`@node-service`). -- D8 the Open API wrapper plugins of node-service with a server URL (CouchDB, Jira, Datadog, WooCommerce, Supabase Management API) against the echo sidecar: one read-only operation each reaches the server URL (the target's path survives as the base path) with its credentials and answers the canned data, CouchDB JWT credential alone and with a Basic one (observation), WooCommerce server URL forms and refusal of v1/v2, a trailing slash after the API path doubles it (NSD-5 candidate), concurrent queries against two server URLs each reach their own server (`@node-service`). -- D9 the Open API wrapper plugins of node-service with a server URL (Lowcoder API, OpenAI, APITemplate.io, Carbone, UiPath) against the echo sidecar: one read-only operation each reaches the server URL with its credentials and answers the canned data (Carbone `get_status` sends no token: observation), every Lowcoder spec version, an OpenAI chat completion posts its JSON body, OpenAI on spec version v1.0 sends no key (NSD-7 candidate), an error status answered as success (NSD-4 candidate), UiPath fails every query and its query configuration request (HTTP 500) and sends nothing (NSD-6 candidate; its desired behaviour is quarantined), concurrent queries against two server URLs each reach their own server (`@node-service`). -- D10 the DynamoDB and S3 plugins of node-service (AWS SDK v3) against the echo sidecar: a DynamoDB call is a signed JSON POST to `/ddb/` (`x-amz-target`, credential scope with the access key and region, the secret never sent), GetItem, PutItem and Query wrap the request's values and unwrap the answer's typed attributes, a service error fails the query with its message, the published view after a click; the S3 connection test lists the buckets (API and the form's Test Connection button), a refused test answers `code` 500 with the service's text (HTTP 200), a listBuckets query answers the names, every call that takes a bucket (listObjects with and without a presigned URL, readFile, uploadData, deleteFile) is path-style `/s3//` on the echo's IP address, a service error fails the query, a bucket call without a bucket sends nothing (readFile, uploadData and deleteFile show the SDK's text, NSD-8 candidate) (`@node-service`; the signed request's shape and the answer's path into the app, not the vendor service). -- D11 the Supabase Storage plugin of node-service (`supabase-js`, project URL `/sb`) against the echo sidecar: every operation (listBuckets, listObjects, readFile, uploadData, deleteFile, createSignedUrl) sends its Storage API request below `/sb/storage/v1` with the key in `apikey` and `authorization` and nowhere else, a trailing slash of the project URL changes nothing, a storage error fails the query with `{"size":0,"timeout":0}` and not the API's message (NSD-9 candidate), the signed-URL validity is an epoch time in milliseconds (NSD-10 candidate), the `search` field of listObjects is not sent (NSD-11 candidate), only listObjects refuses an empty bucket (NSD-12 candidate), the published view after a click (`@node-service`; the request shape and the answer's path into the app, not Supabase). -- D12 the Firebird plugin of node-service against the opt-in Firebird sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): the connection test attaches, a wrong password and a missing database file fail it with the server's text, a named parameter answers the lower-cased row, every column type of the seeded table, parameters bound in SQL order, not object order, an unknown parameter is refused with its name, an INSERT is read back by its own owner, a SQL error is the failed query's message, the lower-case option, a failing query leaves its attachment open (NSD-13 candidate), and the runner reaches the sidecar over TCP. -- D13 the Turso plugin of node-service against the opt-in libSQL server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): create, insert and select answer typed rows (integer, real, a lower-case `boolean`, `datetime`, NULL), `includeRaw` answers the server's own result set, a write answers no values and its raw result counts the change, a blob cell is dropped from the row (NSD-14 candidate), an integer beyond 2^53 is rounded (NSD-15 candidate), a real SQL error (syntax, unknown column, constraint, two statements) fails the query with `[object Object]` (NSD-1 candidate, the defect of D5d against a real server), a token of another key or a malformed one is a 401, a read-only token reads and its write is a 403, the published view after a click, a trailing slash after the URL is a 404, and the runner reaches the sidecar. The `libsql://` rewrite is not covered. -- D14 the CouchDB plugin of node-service against the opt-in CouchDB server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): a database is created, listed (by a key range), described and deleted, and the server agrees at each step; a document is created, read, updated by its revision, read at its old revision, listed and deleted; a stale revision (as a query parameter or as `If-Match`) answers a conflict body and changes nothing (NSD-4 candidate); a missing database or document and an existing database answer their error bodies (NSD-4 candidate); a wrong password answers an unauthorized body and writes nothing (NSD-4 candidate); five wrong passwords lock the account for the client address and even the right password then gets the lockout's 403 body (NSD-4 candidate); `docGet` cannot run without `If-None-Match` and a matching ETag fails with `status: 304` (NSD-16 candidate); the listing options (`startkey`, `endkey`, `descending`, `skip`, `limit`) reach the server; the published view shows a document after a click; and the runner reaches the sidecar. The JWT credential and cookie sessions are not covered. -- D15 the DynamoDB plugin of node-service against the opt-in DynamoDB Local server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): a table is created (the description's complete shape), refused when it exists, listed and paged by name, and the server agrees at each step (D15a); an item of every type the plugin writes (string, empty string, integers, negative, fraction, booleans, null, map, number set, string set, mixed list, list of maps) is stored in the typed form and read back as plain values (D15b); Query (key condition, range, projection, descending, `Limit`) and Scan (filter, `Select: COUNT`) answer unwrapped items with the counts, `LastEvaluatedKey` stays typed, and a scan with `Limit: 2` is paged by feeding each returned typed key into the next request until none is returned: no item missing or twice, no page above the limit, at least three requests, the last page without a key (D15c); UpdateItem and DeleteItem change the server's data, a failed condition changes nothing, and `ReturnValues` answers `Attributes` that stay typed (D15d, D15e, NSD-17 candidate); a missing table, a failed condition, a missing or mistyped key, an empty key, a bad table name and an existing table fail the query with the server's own message (D15f); an array of strings or numbers is always a set (order lost, duplicates and an empty array refused, NSD-18 candidate, D15g); a binary attribute reads as an object with index keys and a number beyond a double loses digits (NSD-19 candidate, D15h); an `ExclusiveStartKey` in the plain form fails with the SDK's `TypeError` (NSD-20 candidate, D15i); any access key reaches the same tables and a closed port of the sidecar's host fails with the connection error (D15j); the published view shows an item after a click (D15k); and the runner reaches the sidecar (D15l). DescribeTable and DeleteTable are not offered by the form (direct calls only); indexes, transactions, batch operations and streams are not covered. -- D16 the S3 plugin of node-service against the opt-in S3-compatible server sidecar (versitygw, `@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`; the endpoint is the sidecar's IP address, path-style): the connection test accepts the right key pair and the server itself refuses a wrong access key, a wrong secret and a wrong region with its own text (D16a), the form's Test Connection button shows the refusal and then the success (D16b), a `listBuckets` query shows a new bucket as a name only (D16c), `uploadData` stores the decoded bytes with the content type (text, all 256 byte values, an empty type becomes `application/octet-stream`, an overwrite replaces object and type) and `readFile` answers type, the server's length, the server's time and the data as text or base64 (D16d), `listObjects` with a prefix, a limit and no match (D16e), a listing cut by the limit cannot be continued: the plugin sends no marker and shows no truncation (NSD-21 candidate, D16f), a delimiter drops the common prefixes the server answers (NSD-22 candidate, D16g), `deleteFile` removes an existing key and answers the same success for an absent one (D16h), a presigned URL of `listObjects` and of `uploadData` downloads the object from the runner while the plain `url`, a changed signature and another key are refused by the server (D16i), keys with spaces, unicode, `+&=%?#;,'()*!` and slashes are stored under their exact names, listed and read, with an `url` that is not encoded (NSD-24 candidate, D16j), the server's `NoSuchBucket` (listObjects, readFile, uploadData, deleteFile), `NoSuchKey` (readFile) and, for a wrong access key or a wrong secret, `InvalidAccessKeyId` and `SignatureDoesNotMatch` (listBuckets, listObjects, readFile, uploadData, deleteFile) messages reach the query (D16k), an empty bucket name is refused with the messages above and stores nothing in an existing bucket (NSD-8 candidate, D16l; that no request is sent is shown by D10q against the echo's recorded requests, not by D16l), a 3 MiB body arrives byte for byte and its length agrees (D16m), `uploadData` with the default encoding stores plain text as other bytes without a message (NSD-23 candidate, D16n), and a closed port gives the whole connection-error envelope while the server's port gives the whole success envelope (D16o). Not covered: a real AWS S3, multipart upload, an expired presigned URL, versioning, ACLs. +- D5 the Turso and Slack plugins of node-service against the echo sidecar: a Turso query sends one Hrana pipeline and answers its rows, `includeRaw` answers values and raw, a non-OK answer and an `error` result fail the query (the latter prints `[object Object]`, D-66 candidate), the published view after a click; a Slack query posts the form payload to the webhook (`@node-service`; the request shape and the answer's path into the app, not the vendor service). +- D6 the GitLab and Shopify GraphQL plugins of node-service against the echo sidecar: a GitLab query posts the query, the variables and every header (data source, query and the access token), a GraphQL error answer fails the query, the published view after a click; a Shopify query reaches the endpoint, and the header the query sets does not (D-67 candidate) (`@node-service`; the request shape and the answer's path into the app, not the vendor service). +- D7 the generic Open API plugin of node-service against the echo sidecar: the data source form's dynamic config reads the OpenAPI document from its URL (the echo serves a canned document) and answers the spec and the key field, an operation runs against the server URL with the key in the header the document names, the key comes from the data source (no key, no header), an error status answers its body as a successful result (D-69 candidate), the published view after a click, the dynamic config answer is cached in memory per request body, with no expiry (observation) (`@node-service`). +- D8 the Open API wrapper plugins of node-service with a server URL (CouchDB, Jira, Datadog, WooCommerce, Supabase Management API) against the echo sidecar: one read-only operation each reaches the server URL (the target's path survives as the base path) with its credentials and answers the canned data, CouchDB JWT credential alone and with a Basic one (observation), WooCommerce server URL forms and refusal of v1/v2, a trailing slash after the API path doubles it (D-70 candidate), concurrent queries against two server URLs each reach their own server (`@node-service`). +- D9 the Open API wrapper plugins of node-service with a server URL (Lowcoder API, OpenAI, APITemplate.io, Carbone, UiPath) against the echo sidecar: one read-only operation each reaches the server URL with its credentials and answers the canned data (Carbone `get_status` sends no token: observation), every Lowcoder spec version, an OpenAI chat completion posts its JSON body, OpenAI on spec version v1.0 sends no key (D-72 candidate), an error status answered as success (D-69 candidate), UiPath fails every query and its query configuration request (HTTP 500) and sends nothing (D-71 candidate; its desired behaviour is quarantined), concurrent queries against two server URLs each reach their own server (`@node-service`). +- D10 the DynamoDB and S3 plugins of node-service (AWS SDK v3) against the echo sidecar: a DynamoDB call is a signed JSON POST to `/ddb/` (`x-amz-target`, credential scope with the access key and region, the secret never sent), GetItem, PutItem and Query wrap the request's values and unwrap the answer's typed attributes, a service error fails the query with its message, the published view after a click; the S3 connection test lists the buckets (API and the form's Test Connection button), a refused test answers `code` 500 with the service's text (HTTP 200), a listBuckets query answers the names, every call that takes a bucket (listObjects with and without a presigned URL, readFile, uploadData, deleteFile) is path-style `/s3//` on the echo's IP address, a service error fails the query, a bucket call without a bucket sends nothing (readFile, uploadData and deleteFile show the SDK's text, D-73 candidate) (`@node-service`; the signed request's shape and the answer's path into the app, not the vendor service). +- D11 the Supabase Storage plugin of node-service (`supabase-js`, project URL `/sb`) against the echo sidecar: every operation (listBuckets, listObjects, readFile, uploadData, deleteFile, createSignedUrl) sends its Storage API request below `/sb/storage/v1` with the key in `apikey` and `authorization` and nowhere else, a trailing slash of the project URL changes nothing, a storage error fails the query with `{"size":0,"timeout":0}` and not the API's message (D-74 candidate), the signed-URL validity is an epoch time in milliseconds (D-75 candidate), the `search` field of listObjects is not sent (D-76 candidate), only listObjects refuses an empty bucket (D-77 candidate), the published view after a click (`@node-service`; the request shape and the answer's path into the app, not Supabase). +- D12 the Firebird plugin of node-service against the opt-in Firebird sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): the connection test attaches, a wrong password and a missing database file fail it with the server's text, a named parameter answers the lower-cased row, every column type of the seeded table, parameters bound in SQL order, not object order, an unknown parameter is refused with its name, an INSERT is read back by its own owner, a SQL error is the failed query's message, the lower-case option, a failing query leaves its attachment open (D-78 candidate), and the runner reaches the sidecar over TCP. +- D13 the Turso plugin of node-service against the opt-in libSQL server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): create, insert and select answer typed rows (integer, real, a lower-case `boolean`, `datetime`, NULL), `includeRaw` answers the server's own result set, a write answers no values and its raw result counts the change, a blob cell is dropped from the row (D-79 candidate), an integer beyond 2^53 is rounded (D-80 candidate), a real SQL error (syntax, unknown column, constraint, two statements) fails the query with `[object Object]` (D-66 candidate, the defect of D5d against a real server), a token of another key or a malformed one is a 401, a read-only token reads and its write is a 403, the published view after a click, a trailing slash after the URL is a 404, and the runner reaches the sidecar. The `libsql://` rewrite is not covered. +- D14 the CouchDB plugin of node-service against the opt-in CouchDB server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): a database is created, listed (by a key range), described and deleted, and the server agrees at each step; a document is created, read, updated by its revision, read at its old revision, listed and deleted; a stale revision (as a query parameter or as `If-Match`) answers a conflict body and changes nothing (D-69 candidate); a missing database or document and an existing database answer their error bodies (D-69 candidate); a wrong password answers an unauthorized body and writes nothing (D-69 candidate); five wrong passwords lock the account for the client address and even the right password then gets the lockout's 403 body (D-69 candidate); `docGet` cannot run without `If-None-Match` and a matching ETag fails with `status: 304` (D-81 candidate); the listing options (`startkey`, `endkey`, `descending`, `skip`, `limit`) reach the server; the published view shows a document after a click; and the runner reaches the sidecar. The JWT credential and cookie sessions are not covered. +- D15 the DynamoDB plugin of node-service against the opt-in DynamoDB Local server sidecar (`@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`): a table is created (the description's complete shape), refused when it exists, listed and paged by name, and the server agrees at each step (D15a); an item of every type the plugin writes (string, empty string, integers, negative, fraction, booleans, null, map, number set, string set, mixed list, list of maps) is stored in the typed form and read back as plain values (D15b); Query (key condition, range, projection, descending, `Limit`) and Scan (filter, `Select: COUNT`) answer unwrapped items with the counts, `LastEvaluatedKey` stays typed, and a scan with `Limit: 2` is paged by feeding each returned typed key into the next request until none is returned: no item missing or twice, no page above the limit, at least three requests, the last page without a key (D15c); UpdateItem and DeleteItem change the server's data, a failed condition changes nothing, and `ReturnValues` answers `Attributes` that stay typed (D15d, D15e, D-82 candidate); a missing table, a failed condition, a missing or mistyped key, an empty key, a bad table name and an existing table fail the query with the server's own message (D15f); an array of strings or numbers is always a set (order lost, duplicates and an empty array refused, D-83 candidate, D15g); a binary attribute reads as an object with index keys and a number beyond a double loses digits (D-84 candidate, D15h); an `ExclusiveStartKey` in the plain form fails with the SDK's `TypeError` (D-85 candidate, D15i); any access key reaches the same tables and a closed port of the sidecar's host fails with the connection error (D15j); the published view shows an item after a click (D15k); and the runner reaches the sidecar (D15l). DescribeTable and DeleteTable are not offered by the form (direct calls only); indexes, transactions, batch operations and streams are not covered. +- D16 the S3 plugin of node-service against the opt-in S3-compatible server sidecar (versitygw, `@node-service-sidecar`, only with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`; the endpoint is the sidecar's IP address, path-style): the connection test accepts the right key pair and the server itself refuses a wrong access key, a wrong secret and a wrong region with its own text (D16a), the form's Test Connection button shows the refusal and then the success (D16b), a `listBuckets` query shows a new bucket as a name only (D16c), `uploadData` stores the decoded bytes with the content type (text, all 256 byte values, an empty type becomes `application/octet-stream`, an overwrite replaces object and type) and `readFile` answers type, the server's length, the server's time and the data as text or base64 (D16d), `listObjects` with a prefix, a limit and no match (D16e), a listing cut by the limit cannot be continued: the plugin sends no marker and shows no truncation (D-86 candidate, D16f), a delimiter drops the common prefixes the server answers (D-87 candidate, D16g), `deleteFile` removes an existing key and answers the same success for an absent one (D16h), a presigned URL of `listObjects` and of `uploadData` downloads the object from the runner while the plain `url`, a changed signature and another key are refused by the server (D16i), keys with spaces, unicode, `+&=%?#;,'()*!` and slashes are stored under their exact names, listed and read, with an `url` that is not encoded (D-89 candidate, D16j), the server's `NoSuchBucket` (listObjects, readFile, uploadData, deleteFile), `NoSuchKey` (readFile) and, for a wrong access key or a wrong secret, `InvalidAccessKeyId` and `SignatureDoesNotMatch` (listBuckets, listObjects, readFile, uploadData, deleteFile) messages reach the query (D16k), an empty bucket name is refused with the messages above and stores nothing in an existing bucket (D-73 candidate, D16l; that no request is sent is shown by D10q against the echo's recorded requests, not by D16l), a 3 MiB body arrives byte for byte and its length agrees (D16m), `uploadData` with the default encoding stores plain text as other bytes without a message (D-88 candidate, D16n), and a closed port gives the whole connection-error envelope while the server's port gives the whole success envelope (D16o). Not covered: a real AWS S3, multipart upload, an expired presigned URL, versioning, ACLs. - M1 two module instances, every direction across the boundary; M2 which module version a host shows; M3 host built in the editor. ## Test catalogue @@ -315,7 +315,7 @@ Counts (re-measured 2026-11-25 with `LOWCODER_BASE_URL=http://localhost:1 ./node default **859 tests in 114 files**; with `E2E_INCLUDE_QUARANTINE=1` **873 in 115**; with `E2E_INCLUDE_SUPERADMIN=1` **864 in 114**; with both of those **878 in 115**; with `E2E_INCLUDE_INSERT_ALL=1` **971 in 115**; with all three opt-in variables **990 in 116** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **918 in 119** (the 11 D12 tests of the Firebird sidecar, the 11 D13 tests of the libSQL sidecar, the 10 D14 tests of the CouchDB sidecar, the 12 D15 tests of the DynamoDB Local sidecar and the 15 D16 tests of the S3 sidecar, which no other variable lists), and **1049 in 121** with the other three variables as well. With `E2E_STACK_PROFILE=enterprise`: **8 in 1** (SEC-E01 to E04, E06a, E06b, E07a, E07b as of D-34; also with `E2E_INCLUDE_QUARANTINE=1` alone, which opens nothing extra), **1 in 1** with `E2E_INCLUDE_ENTERPRISE_TAKEOVER=1` alone (SEC-E05 alone, no quarantine flag needed any more); `E2E_INCLUDE_INSERT_ALL` and `E2E_INCLUDE_SUPERADMIN` add nothing there. `@enterprise` is 9 tests, none in a default-stack listing. With `E2E_STACK_PROFILE=signup-disabled`: **5 in 1** (LC-AU20 to AU24). -Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 154 in 10 files (the 63 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **213 in 15 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests, the 11 D13 tests, the 10 D14 tests, the 12 D15 tests and the 15 D16 tests); `@node-service-sidecar` 0 (**59 in 5 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests, D13a to D13k, the libSQL sidecar tests, D14a to D14j, the CouchDB sidecar tests, D15a to D15l, the DynamoDB Local sidecar tests, and D16a to D16o, the S3 sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; NSD-6 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 5, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 111, `@node-service` 154 in 10 files (the 63 unit tests of `foundation/node-plugins.spec.ts` plus the 91 scenario tests of the plugin specs: D3a to D3c, D4a to D4e, D5a to D5f, D6a to D6e, D7a to D7f, D8a to D8i (11 tests), D9a to D9k with the four D9m tests (15 tests) and D10a to D10q (19 tests: D10m and D10n have two each) and D11a to D11q (21 tests: D11b and D11g have two each, D11n three); a selection tag, they stay in the default run; **213 in 15 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`, which adds the 11 D12 tests, the 11 D13 tests, the 10 D14 tests, the 12 D15 tests and the 15 D16 tests); `@node-service-sidecar` 0 (**59 in 5 files** with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1`: D12a to D12k, the Firebird sidecar tests, D13a to D13k, the libSQL sidecar tests, D14a to D14j, the CouchDB sidecar tests, D15a to D15l, the DynamoDB Local sidecar tests, and D16a to D16o, the S3 sidecar tests). On request: `@quarantine` 14 (with `E2E_INCLUDE_QUARANTINE=1`; no `@quarantine` test also carries `@superadmin` any more, so the same 14 with both variables), `@superadmin` 5 (the four SEC-R16 tests and the `superAdmin` fixture helper test), `@insert-all` 112. The 14 `@quarantine` tests: the lifecycle ones are LC-AK04 (D-45, intermittent UI test), LC-AU15 (D-30) and the three new creator-shortcut candidates LC-DL13 to LC-DL15 (`workspace/leave-removal.spec.ts`, D-26/D-60 residual, an open scope question for the owner); the rest are the open security findings SEC-C17c (D-30, two variants), SEC-R17f (D-46), SEC-A10b (D-13), the two quarantined tests of `foundation/security-helpers.spec.ts` (D-45, D-46 candidates), `editor/drop-size.spec.ts` (D-5), the icon switch of `components/displays.spec.ts` (CD-9 candidate) and D9l of `datasource/plugin-openapi-wrappers-apps.spec.ts` (the UiPath query that should reach the server URL with its Bearer token; D-71 candidate; it fails on `3.0.0-e2e` and `3.0.1-e2e`). For all of these except D9l, whether each PASSES as expected (quarantined ones failing, default-run ones passing) on a built image is confirmed in the combined run (2026-11-24, image `secfix-combined-e2e`). That run predates the node-service specs, so it says nothing about D9l: D9l was checked separately with `E2E_INCLUDE_QUARANTINE=1` on the default image `3.0.0-e2e` and on `lowcoderorg/lowcoder-ce:3.0.1-e2e`, where it fails with "the query succeeded" as intended. Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the quarantine holds only what still fails there (plus LC-AK04, an intermittent UI test): 25 tests whose test passed on 3.0.1 left it and are in the default run (SEC-R16c and SEC-R16d are in the `@superadmin` run), and LC-GR03, LC-PR06 and LC-IP07 left the open list. ### smoke (4) @@ -372,19 +372,19 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | datasource/table.spec.ts | D2: editor-built table bound to a query; published table; sort, page, select, filter, notes edit/save | @core @slow | 3 | | datasource/query-feeds-components.spec.ts | D1: query feeds text and table, owner-scoped writes re-read, chart renders | @core @slow @npm | 1 | | datasource/notes-queries.spec.ts | unit tests of the query builders | none | 4 | -| datasource/plugin-duckdb.spec.ts | D4: DuckDB through the app container, database `:memory:`, no network. D4a a query answers rows, D4b the published view shows the result after a click, D4c a BIGINT and a HUGEINT arrive as exact strings, D4d each run is a fresh database (a table created by one run is gone in the next), D4e a syntax error is a failed query (`success: false`, `queryCode: FAILED`; the field `code` is 1 either way). D4a to D4c assert the measured row shape, keys are the column positions (NSD-3 candidate) | @node-service | 5 | -| datasource/plugin-turso-slack.spec.ts | D5: Turso and Slack against the echo sidecar (the data source URL is the test's own echo target). D5a a Turso query sends one POST of `{requests: [execute, close]}` to `/v2/pipeline` with `Authorization: Bearer ` and answers the rows keyed by column name (an `integer` cell as a number), D5b `includeRaw` answers `{values, raw}`, D5c a 500 answer fails the query (`Endpoint returned 500`), D5d an `error` result fails the query with `Cannot parse result, received error: [object Object]` (NSD-1 candidate: the server's message is lost), D5e the published view shows the row after a click, D5f a Slack query posts `payload=` as `application/x-www-form-urlencoded;charset=UTF-8` to the webhook path and answers the webhook's text. Not covered: the `libsql://` rewrite (the echo does not speak TLS) | @node-service | 6 | -| datasource/plugin-graphql.spec.ts | D6: GitLab and Shopify against the echo sidecar (the endpoint is the test's own echo target plus `/api/graphql`). D6a a GitLab query posts one JSON body `{query, variables: {n: 3}, operationName}` (the variable's text `3` arrives as the number 3) with `PRIVATE-TOKEN`, the data source header and the query header, and answers the `data` member, D6b a `{"errors":[...]}` answer fails the query with `: `, D6c a Shopify query posts `{query, variables: {}}` and answers the `data` member (control), D6d the header the Shopify query sets reaches the echo neither as name nor as value (NSD-2 candidate), D6e the published view shows the GitLab answer after a click | @node-service | 5 | -| datasource/plugin-openapi.spec.ts | D7: the generic Open API plugin against the echo sidecar (spec URL `/spec.json`, server URL `/api`; the document is `OPEN_API_FIXTURE_SPEC`: `GET /items`, operation `listItems`, parameter `q`, API key header `X-E2E-Key`, placeholder server). D7a the dynamic config call (`path` `$.dataSourceConfig.extra`) answers `[{data: {spec}, extraParams}]` with the key field `E2EKeyAuth.value` labelled `X-E2E-Key` and fetches the document with exactly one GET, D7b `listItems` sends `GET /api/items?q=` with `x-e2e-key` and answers the canned `[{id: 1}]`, D7c a data source with an empty `dynamicParamsConfig` sends no key header, D7d a canned 404 `{"message":"e2e-missing"}` is answered as `success: true`, `queryCode: "OK"`, data the 404 body (NSD-4 candidate), D7e the published view shows the first item's id only after the click (echo 0 requests before, exactly 1 after), D7f the same dynamic config request answers from the cache after the document changed on the echo (one fetch), while a request with another body fetches again; the cache is an in-process object keyed on path, query and body with no expiry (observation) | @node-service | 6 | -| datasource/plugin-openapi-wrappers-data.spec.ts | D8: CouchDB, Jira, Datadog, WooCommerce and the Supabase Management API against the echo sidecar (server URL ``, one read-only operation of each bundled document). D8a couchdb `GET /_all_dbs` with `Authorization: Basic` of the configured user and password, D8b jira `GET /rest/api/3/myself` with Basic, D8c datadog `GET /api/v1/validate` with `dd-api-key` and `dd-application-key`, D8d woocommerce `GET /wp-json/wc/v3/products?context=view&order=asc&orderby=date&status=any&type=simple&stock_status=instock` with Basic, D8e supabaseApi `GET /v1/projects` with `Authorization: Bearer `; each asserts echo empty before, exactly one request (method, full path and query, no body, the complete header set) and the canned body as the query's data; D8f couchdb: a JWT credential alone is sent as `Authorization`, with a Basic credential too only the Basic one is (observation), each request asserted completely; D8g woocommerce: a plain, a slash-terminated and an already `/wp-json/wc/v3` server URL each give the API path once, `/wc/v1` and `/wc/v2` are refused with `only woocommerce api v3 is supported` and send nothing; D8h woocommerce: a server URL ending in `/wp-json/wc/v3/` gets the API path twice (NSD-5 candidate); D8i couchdb, woocommerce and datadog: 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 11 | -| datasource/plugin-openapi-wrappers-apps.spec.ts | D9: the Lowcoder API, OpenAI, APITemplate.io, Carbone and UiPath against the echo sidecar (server URL ``, one read-only operation of each bundled document). D9a lowcoder `GET /api/users/currentUser` with `Authorization: Bearer `, D9b OpenAI (spec version v2.3) `GET /models` with `Authorization: Bearer `, D9c apiTemplate `GET /v2/list-templates` with `x-api-key`, D9d carboneIo `GET /status` with NO credential header (observation: that operation lists no security scheme), D9e carboneIo `GET /template/` with `Authorization: Bearer ` and `carbone-version: 4`; each asserts echo empty before, exactly one request (method, full path and query, body, the complete header set) and the canned body as the query's data; D9f lowcoder: spec versions v1.0 to v1.3 send the same request; D9g OpenAI: a chat completion `POST /chat/completions` carries the JSON body, `content-type`, `content-length` and the key, and answers the canned completion; D9h OpenAI: spec version v1.0, chosen or by default, sends no `Authorization` header while v2.3 with the same key does (NSD-7 candidate); D9i apiTemplate: a canned 404 body is reported as a successful result (NSD-4 candidate); D9j uiPath: a query fails with the message `Maximum call stack size exceeded` and sends no request, after a control that another wrapper's query reaches the same echo target (NSD-6 candidate); D9k uiPath: the form's query configuration request for the UiPath document answers 500 / code 5000 `get dynamic config error`, while the identical request for apiTemplate answers success and lists its operations (NSD-6 candidate; the test asserts the failure and the control, not its cause); D9l uiPath (`@quarantine`, not counted in the default run): the folders query should reach `GET /odata/Folders` with `Bearer ` exactly and answer the canned data, fails today; D9m lowcoder, apiTemplate, carboneIo and OpenAI: 8, 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 15 (+1 `@quarantine`) | -| datasource/plugin-aws-sdk.spec.ts | D10: DynamoDB and S3 against the echo sidecar (endpoints `/ddb` and `/s3`; bucket calls on the echo's IP address). Measured on 3.0.0-e2e and 3.0.1-e2e (the SDK version printed in its user agent is 3.668.0 on 3.0.0-e2e; the tests match the shape, not the version): the SDK keeps the endpoint's path, DynamoDB posts to `/ddb/`, S3 without a bucket gets `/s3/?x-id=ListBuckets`, and with a bucket on an IP-address endpoint it is path-style (`/s3//`, `Host` the IP address). Every request a D10 test makes is asserted completely: method, path and query, body, the whole header set (per-request values by shape: date, invocation id, user agents, signature), the credential scope (access key, date, region, service) and the signed-header list, and every D10 test that sends a request also asserts that the secret key is in no header, path or body of the echo's records (with a control that the access key is: it travels in the credential scope). The rows of D10q that send nothing assert that the echo holds no record, after which a control call with a bucket is asserted completely. The presigned URL of D10l is asserted by its stable query parameters and by shape, not by value. D10a DynamoDB ListTables (region `eu-central-1` in the scope, body `{TableName: "", Limit: 10}`, answer without `$metadata`), D10b GetItem wraps the key and unwraps a string, a number, a string set and a boolean, D10c PutItem wraps a number, a string and a boolean, D10d Query keeps the expression and unwraps the items, D10e a 400 `ResourceNotFoundException` fails the query (`Requested resource not found`, one request), D10f the published view after a click, D10g the connection test (`code` 1, `success`, `data` true; one `GET /s3/?x-id=ListBuckets`), D10h a 403 test answers HTTP 200 with `code` 500, `success` false and `Failed to connect data source: Access Denied.`, and the same body succeeds once the endpoint answers 200, D10i the form's Test Connection button shows that text, then `Connection Successful`, D10j listBuckets answers `[{name}]`, D10k listObjects is path-style on the IP with `delimiter`, `max-keys` and `prefix` and answers name, size, time, file URL, D10l `returnSignedUrl` adds a presigned URL (`X-Amz-Expires=300`, signed header `host`, no extra request), D10m readFile as text and base64, D10n uploadData of text and of base64 without a content type (`application/octet-stream`), D10o deleteFile, D10p a 403 and a 404 fail the query with the service's text, D10q a bucket call without a bucket sends nothing: listObjects says `Bucket is required`, readFile, uploadData and deleteFile say `Empty value provided for input HTTP label: Bucket.` (NSD-8 candidate), after a control that a call with a bucket reaches the echo. Not covered: a real DynamoDB or S3 service, the SDK's retry of a 5xx answer | @node-service | 19 | -| datasource/plugin-supabase-storage.spec.ts | D11: the Supabase Storage plugin against the echo sidecar (project URL `/sb`; the Storage API is `/sb/storage/v1/...`). Measured on 3.0.0-e2e and 3.0.1-e2e (same requests and answers; supabase-js 2.45.4 in `x-client-info`, matched by shape): the client keeps the project URL's path with or without a trailing slash and derives no host name; every request carries `apikey: `, `authorization: Bearer `, the `node-fetch` user agent, `accept-encoding: gzip,deflate` and `connection: close`. Every request a D11 test makes is asserted completely (method, path and query, body, the whole header set), and every test that sends one also asserts that the key is in no header besides those two, no path or body, and no answer of the query (the whole query answer; in D11q the view's whole `q.data` as text); control: it is in those two. D11a listBuckets `GET /bucket` and the buckets as the API answered, D11b the project URL with and without a trailing slash reach the same path, D11c listObjects `POST /object/list/` with `{limit: 10, offset: 0, sortBy: {column: name, order: asc}, prefix}` and the public URL of each file in the answer, D11d limit, offset and sort order of the query, D11e the `search` field is not sent (NSD-11 candidate), D11f `returnSignedUrl` adds `POST /object/sign/` with `{expiresIn, paths}` and the signed URL in the answer, D11g readFile as text and base64 (`GET /object//`, answer `{data, type}`), D11h readFile with a transform goes to `/render/image/authenticated//?width=10`, D11i uploadData of text `POST /object//` with the text, its content type, `cache-control: max-age=3600` and `x-upsert: false`, D11j base64 without a content type sends an empty `content-type` header (observation), D11k uploadData with `returnSignedUrl` uploads then signs, D11l deleteFile `DELETE /object/` with `{prefixes: [name]}`, D11m createSignedUrl sends `expiresIn` as an integer above 1e12, an epoch time in milliseconds computed once (the second query, asserted completely too, sends the same number; the bounds allow one hour of clock skew and a plugin load up to six hours old; NSD-10 candidate, also asserted in D11f and D11k), D11n a 400, a 404 and a 401 answer fail the query with `{"size":0,"timeout":0}` instead of the answer's message, each followed by a control that the same query succeeds once the API answers 200 (NSD-9 candidate), D11o the signing and the listing fail the same way, each followed by a control that both succeed once the API answers 200 on their paths, D11p an empty bucket: listObjects says `Bucket is required` and sends nothing, readFile, uploadData, deleteFile and createSignedUrl send requests with an empty bucket segment (NSD-12 candidate), D11q the published view shows the bucket name only after the click (echo empty before, one request after). Not covered: a real Supabase project; the connection test (none is wired up for this plugin) | @node-service | 21 | -| datasource/plugin-firebird.spec.ts | D12: the Firebird plugin against the opt-in Firebird sidecar (Firebird 3.0.12, `fixtures/firebird/init.sql`; host, port, database path and login of the sidecar written over the recorded form body). Measured on 3.0.0-e2e and 3.0.1-e2e. D12a the connection test answers `code` 1, `success` true, `data` true; D12b a wrong password answers `code` 500 with `Failed to connect data source: Your user name and password are not defined. Ask your database\nadministrator to set up a Firebird login\n.` and a missing database file with the server's `I/O error for file ...` (the right fields attach first); D12c `SELECT ID, NAME FROM FB_ITEMS WHERE ID = :id` with `{"id": 2}` answers `[{id: 2, name: "beta"}]`; D12d the three seeded rows with `price` as a number and a NULL as `null`; D12e parameters bind in the order the names appear in the SQL, not the key order of the parameter object (`CAST(:first AS INTEGER) - CAST(:second AS INTEGER)` with 10 and 3 answers 7 whichever order the object lists them); D12f an unknown name fails with `Named parameter "missing" not found in Query Parameters object.` (the same SQL with the name present runs); D12g an INSERT answers `{}` and is read back by the test's own owner (the owner has no row before); D12h a syntax error and an unknown table answer the server's text; D12i `lowercaseKeys: false` answers upper-case keys; D12j a query that fails after the attach leaves its attachment open on the server, a succeeding one does not: two failing runs of a statement that tags its attachment with a per-test context variable leave exactly two tagged attachments in `MON$CONTEXT_VARIABLES`, and a succeeding tagged run does not add a third (NSD-13 candidate, `defect` annotation); D12k the runner connects to the sidecar's port 3050, and a closed port of the same host is refused. Limits: `role`, `blobAsText` and Firebird 4 and 5 are not covered; the sidecar authenticates with Legacy_Auth (see the architecture bullet) | @node-service @node-service-sidecar (opt-in) | 11 | -| datasource/plugin-turso-libsql.spec.ts | D13: the Turso plugin against the opt-in libSQL sidecar (sqld 0.24.33 with a JWT key; the data source URL is `http://e2e-libsql:8080`, the recorded `turso` form body with the sidecar's URL and token written over it; each test makes its own table `e2e_t_`). Measured on 3.0.0-e2e and 3.0.1-e2e. D13a CREATE, two INSERTs and a SELECT: a CREATE and an INSERT answer `[]`, the empty table answers `[]` before the inserts, then `integer` is a number, `real` 2 stays 2, a `boolean` column written in lower case is `true`/`false`, a `datetime` text is the ISO text of a `Date` (`2024-01-02T03:04:05.000Z`), NULL is `null`; D13b `includeRaw` answers `values` and the server's `raw` (columns with their declared types, cells such as `{type:"integer", value:"7"}`, the counters; the timing is only checked to be a number); D13c an INSERT answers `[]` with and without `includeRaw`, its raw result has `affected_row_count` 1 and `last_insert_rowid` `"2"` (a string) for the second row; D13d a blob cell is missing from the row (`[{id: 1}]`) while `includeRaw` shows the server sent `{type:"blob", base64:"AP8Q"}` (NSD-14 candidate); D13e `SELECT 9007199254740993` answers 9007199254740992 while the raw cell is the exact string (NSD-15 candidate); D13f `SELEC 1`, an unknown column, a duplicate key and `SELECT 1; SELECT 2` are errors of the server with codes `SQL_PARSE_ERROR`, `SQL_INPUT_ERROR`, `SQLITE_CONSTRAINT` and `SQL_MANY_STATEMENTS` (read by direct calls), and every one of them reaches the app as `Cannot parse result, received error: [object Object]` (NSD-1 candidate; a valid query of the same app succeeds first); D13g a token signed by another key and a string that is no JWT fail with `Failed to execute query. Endpoint returned 401: Unauthorized.` (the sidecar's own token reads the row first; direct calls show the server's `The JWT is invalid` and, without a header, `Expected authorization header but none given`); D13h a read-only token reads, its INSERT fails with `Endpoint returned 403: Forbidden.` and writes nothing (the read-write token then inserts the same row); D13i the published view shows a row after a click; D13j a URL with a trailing slash fails with `Endpoint returned 404: Not Found.` (the plugin builds `//v2/pipeline`; the same URL without it works); D13k the runner reaches the sidecar over HTTP and TCP, a closed port of the same host is refused. Limits: the `libsql://` to `https://` rewrite, a stream with a baton, and Turso's cloud features are not covered | @node-service @node-service-sidecar (opt-in) | 11 | -| datasource/plugin-couchdb.spec.ts | D14: the CouchDB plugin against the opt-in CouchDB sidecar (Apache CouchDB 3.5.1; the data source URL is `http://e2e-couchdb:5984`; the recorded `couchdb` form body with the sidecar's URL and admin written over it; each test makes its own database `e2e_couch_` and removes it). Measured on 3.0.0-e2e and 3.0.1-e2e. D14a a database is created (`{ok: true}`), listed by a key range (`[]` before, `[]` after), described (`GET /`: the member set of 3.5.1, `doc_count` 0), and deleted, with direct reads of the server at each step; D14b a document is created (`{ok, id, rev: 1-...}`), read (`{_id, _rev, ...body}`), updated with `rev` as a query parameter (`2-...`), read at its first revision, listed with `include_docs`, and deleted (`3-...`; the server then answers `deleted`), and the server's own copy matches; D14c a stale revision (query parameter and `If-Match`, on write and delete) and a write without a revision answer `{error: "conflict", reason: "Document update conflict."}` as the data of a SUCCESSFUL query (the server's status is 409), change nothing, and the current revision is accepted by a write and by both kinds of delete (NSD-4 candidate); D14d a missing document, a document of a missing database, the information and the delete of a missing database (404 bodies) and a create of an existing database (412 `file_exists`) are successful queries with the error body as the data (NSD-4 candidate), with successful controls through the same operations (an existing document is read, an existing database is described and deleted, a new one is created); D14e a wrong password answers `{error: "unauthorized", reason: "Name or password is incorrect."}` as the data of a successful query and the refused create made no database, while the right password on the same queries lists and creates (NSD-4 candidate; the account is a second admin the test makes); D14f `docGet` with an empty `If-None-Match` fails with the plugin's own `Required parameter If-None-Match is not provided` (the server reads the same document without the header), a value that is not the current ETag reads the document, and the current ETag (the server answers 304) fails with `status: 304` (NSD-16 candidate); D14g `startkey`/`endkey`, `descending`, `skip` and `limit` give the lists the server gives, for databases and for the documents of a database (`total_rows` counts all of them), and an unscoped list holds the three system databases and the test's own; D14h the published view shows the document's title after a click; D14i the runner reaches the sidecar over HTTP and TCP (`Welcome`, version 3.5.1, `_all_dbs` needs credentials), a closed port of the same host is refused; D14j five wrong passwords of an account are 401 bodies, the sixth and the right password after them are the lockout's 403 body as the data of a successful query (the runner, another client address, is not locked until it fails five times itself, then the server's own status is 403) (NSD-4 candidate). Limits: JWT and cookie authentication, replication, design documents, partitions, attachments and bulk operations are not covered | @node-service @node-service-sidecar (opt-in) | 10 | -| datasource/plugin-dynamodb-local.spec.ts | D15: the DynamoDB plugin against the opt-in DynamoDB Local sidecar (DynamoDB Local 3.3.2, `-inMemory -sharedDb`; the endpoint is `http://e2e-dynamodb:8000`; the recorded `dynamodb` form body with the sidecar's endpoint and throw-away key written over it; each test makes its own tables `e2e_ddb_` and removes them). Measured on 3.0.0-e2e and 3.0.1-e2e. D15a to D15l as in the catalogue (D15): table create, list and paging, the typed round trip of every type, Query and Scan with pagination keys, UpdateItem and DeleteItem with conditions and `ReturnValues`, the server's error messages, sets, binary and big numbers, the plain `ExclusiveStartKey`, any access key and a closed port, the published view, and the runner's reach. NSD-17 to NSD-20 candidates are characterised and annotated. Not covered: indexes, transactions, batch operations, streams, TTL, the signature (the server does not verify it) | @node-service @node-service-sidecar (opt-in) | 12 | -| datasource/plugin-s3-server.spec.ts | D16: the S3 plugin against the opt-in S3 sidecar (versitygw v1.11.0 with its POSIX backend in tmpfs; the endpoint is the sidecar's IP address `http://:7070`, never a name; the recorded `s3` form body and the five recorded queries with the sidecar's endpoint and throw-away key pair written over them; each test makes its own bucket `e2e-s3-` INSIDE its `try` and removes its objects and the bucket in the `finally`; direct signed calls from the test process, `s3Direct`, are the controls that show what the server holds). Measured on 3.0.0-e2e and 3.0.1-e2e. D16a to D16o as in the catalogue (D16). NSD-8, NSD-21, NSD-22, NSD-23 and NSD-24 candidates are characterised and annotated. Not covered: a real AWS S3 (the server differs in limits, versioning, ACLs, storage classes and checksums), multipart upload, an expired presigned URL | @node-service @node-service-sidecar (opt-in) | 15 | +| datasource/plugin-duckdb.spec.ts | D4: DuckDB through the app container, database `:memory:`, no network. D4a a query answers rows, D4b the published view shows the result after a click, D4c a BIGINT and a HUGEINT arrive as exact strings, D4d each run is a fresh database (a table created by one run is gone in the next), D4e a syntax error is a failed query (`success: false`, `queryCode: FAILED`; the field `code` is 1 either way). D4a to D4c assert the measured row shape, keys are the column positions (D-68 candidate) | @node-service | 5 | +| datasource/plugin-turso-slack.spec.ts | D5: Turso and Slack against the echo sidecar (the data source URL is the test's own echo target). D5a a Turso query sends one POST of `{requests: [execute, close]}` to `/v2/pipeline` with `Authorization: Bearer ` and answers the rows keyed by column name (an `integer` cell as a number), D5b `includeRaw` answers `{values, raw}`, D5c a 500 answer fails the query (`Endpoint returned 500`), D5d an `error` result fails the query with `Cannot parse result, received error: [object Object]` (D-66 candidate: the server's message is lost), D5e the published view shows the row after a click, D5f a Slack query posts `payload=` as `application/x-www-form-urlencoded;charset=UTF-8` to the webhook path and answers the webhook's text. Not covered: the `libsql://` rewrite (the echo does not speak TLS) | @node-service | 6 | +| datasource/plugin-graphql.spec.ts | D6: GitLab and Shopify against the echo sidecar (the endpoint is the test's own echo target plus `/api/graphql`). D6a a GitLab query posts one JSON body `{query, variables: {n: 3}, operationName}` (the variable's text `3` arrives as the number 3) with `PRIVATE-TOKEN`, the data source header and the query header, and answers the `data` member, D6b a `{"errors":[...]}` answer fails the query with `: `, D6c a Shopify query posts `{query, variables: {}}` and answers the `data` member (control), D6d the header the Shopify query sets reaches the echo neither as name nor as value (D-67 candidate), D6e the published view shows the GitLab answer after a click | @node-service | 5 | +| datasource/plugin-openapi.spec.ts | D7: the generic Open API plugin against the echo sidecar (spec URL `/spec.json`, server URL `/api`; the document is `OPEN_API_FIXTURE_SPEC`: `GET /items`, operation `listItems`, parameter `q`, API key header `X-E2E-Key`, placeholder server). D7a the dynamic config call (`path` `$.dataSourceConfig.extra`) answers `[{data: {spec}, extraParams}]` with the key field `E2EKeyAuth.value` labelled `X-E2E-Key` and fetches the document with exactly one GET, D7b `listItems` sends `GET /api/items?q=` with `x-e2e-key` and answers the canned `[{id: 1}]`, D7c a data source with an empty `dynamicParamsConfig` sends no key header, D7d a canned 404 `{"message":"e2e-missing"}` is answered as `success: true`, `queryCode: "OK"`, data the 404 body (D-69 candidate), D7e the published view shows the first item's id only after the click (echo 0 requests before, exactly 1 after), D7f the same dynamic config request answers from the cache after the document changed on the echo (one fetch), while a request with another body fetches again; the cache is an in-process object keyed on path, query and body with no expiry (observation) | @node-service | 6 | +| datasource/plugin-openapi-wrappers-data.spec.ts | D8: CouchDB, Jira, Datadog, WooCommerce and the Supabase Management API against the echo sidecar (server URL ``, one read-only operation of each bundled document). D8a couchdb `GET /_all_dbs` with `Authorization: Basic` of the configured user and password, D8b jira `GET /rest/api/3/myself` with Basic, D8c datadog `GET /api/v1/validate` with `dd-api-key` and `dd-application-key`, D8d woocommerce `GET /wp-json/wc/v3/products?context=view&order=asc&orderby=date&status=any&type=simple&stock_status=instock` with Basic, D8e supabaseApi `GET /v1/projects` with `Authorization: Bearer `; each asserts echo empty before, exactly one request (method, full path and query, no body, the complete header set) and the canned body as the query's data; D8f couchdb: a JWT credential alone is sent as `Authorization`, with a Basic credential too only the Basic one is (observation), each request asserted completely; D8g woocommerce: a plain, a slash-terminated and an already `/wp-json/wc/v3` server URL each give the API path once, `/wc/v1` and `/wc/v2` are refused with `only woocommerce api v3 is supported` and send nothing; D8h woocommerce: a server URL ending in `/wp-json/wc/v3/` gets the API path twice (D-70 candidate); D8i couchdb, woocommerce and datadog: 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 11 | +| datasource/plugin-openapi-wrappers-apps.spec.ts | D9: the Lowcoder API, OpenAI, APITemplate.io, Carbone and UiPath against the echo sidecar (server URL ``, one read-only operation of each bundled document). D9a lowcoder `GET /api/users/currentUser` with `Authorization: Bearer `, D9b OpenAI (spec version v2.3) `GET /models` with `Authorization: Bearer `, D9c apiTemplate `GET /v2/list-templates` with `x-api-key`, D9d carboneIo `GET /status` with NO credential header (observation: that operation lists no security scheme), D9e carboneIo `GET /template/` with `Authorization: Bearer ` and `carbone-version: 4`; each asserts echo empty before, exactly one request (method, full path and query, body, the complete header set) and the canned body as the query's data; D9f lowcoder: spec versions v1.0 to v1.3 send the same request; D9g OpenAI: a chat completion `POST /chat/completions` carries the JSON body, `content-type`, `content-length` and the key, and answers the canned completion; D9h OpenAI: spec version v1.0, chosen or by default, sends no `Authorization` header while v2.3 with the same key does (D-72 candidate); D9i apiTemplate: a canned 404 body is reported as a successful result (D-69 candidate); D9j uiPath: a query fails with the message `Maximum call stack size exceeded` and sends no request, after a control that another wrapper's query reaches the same echo target (D-71 candidate); D9k uiPath: the form's query configuration request for the UiPath document answers 500 / code 5000 `get dynamic config error`, while the identical request for apiTemplate answers success and lists its operations (D-71 candidate; the test asserts the failure and the control, not its cause); D9l uiPath (`@quarantine`, not counted in the default run): the folders query should reach `GET /odata/Folders` with `Bearer ` exactly and answer the canned data, fails today; D9m lowcoder, apiTemplate, carboneIo and OpenAI: 8, 8, 8 and 4 queries against two server URLs, with the echo withholding every answer (a barrier) until all of them are waiting, so the canned data reaches them only if all requests were waiting at the echo at the same time (nothing is claimed about node-service's internals); each then reaches only its own server with its full request (measured: no cross-over, so the tests run in parallel with no serial mode) | @node-service | 15 (+1 `@quarantine`) | +| datasource/plugin-aws-sdk.spec.ts | D10: DynamoDB and S3 against the echo sidecar (endpoints `/ddb` and `/s3`; bucket calls on the echo's IP address). Measured on 3.0.0-e2e and 3.0.1-e2e (the SDK version printed in its user agent is 3.668.0 on 3.0.0-e2e; the tests match the shape, not the version): the SDK keeps the endpoint's path, DynamoDB posts to `/ddb/`, S3 without a bucket gets `/s3/?x-id=ListBuckets`, and with a bucket on an IP-address endpoint it is path-style (`/s3//`, `Host` the IP address). Every request a D10 test makes is asserted completely: method, path and query, body, the whole header set (per-request values by shape: date, invocation id, user agents, signature), the credential scope (access key, date, region, service) and the signed-header list, and every D10 test that sends a request also asserts that the secret key is in no header, path or body of the echo's records (with a control that the access key is: it travels in the credential scope). The rows of D10q that send nothing assert that the echo holds no record, after which a control call with a bucket is asserted completely. The presigned URL of D10l is asserted by its stable query parameters and by shape, not by value. D10a DynamoDB ListTables (region `eu-central-1` in the scope, body `{TableName: "", Limit: 10}`, answer without `$metadata`), D10b GetItem wraps the key and unwraps a string, a number, a string set and a boolean, D10c PutItem wraps a number, a string and a boolean, D10d Query keeps the expression and unwraps the items, D10e a 400 `ResourceNotFoundException` fails the query (`Requested resource not found`, one request), D10f the published view after a click, D10g the connection test (`code` 1, `success`, `data` true; one `GET /s3/?x-id=ListBuckets`), D10h a 403 test answers HTTP 200 with `code` 500, `success` false and `Failed to connect data source: Access Denied.`, and the same body succeeds once the endpoint answers 200, D10i the form's Test Connection button shows that text, then `Connection Successful`, D10j listBuckets answers `[{name}]`, D10k listObjects is path-style on the IP with `delimiter`, `max-keys` and `prefix` and answers name, size, time, file URL, D10l `returnSignedUrl` adds a presigned URL (`X-Amz-Expires=300`, signed header `host`, no extra request), D10m readFile as text and base64, D10n uploadData of text and of base64 without a content type (`application/octet-stream`), D10o deleteFile, D10p a 403 and a 404 fail the query with the service's text, D10q a bucket call without a bucket sends nothing: listObjects says `Bucket is required`, readFile, uploadData and deleteFile say `Empty value provided for input HTTP label: Bucket.` (D-73 candidate), after a control that a call with a bucket reaches the echo. Not covered: a real DynamoDB or S3 service, the SDK's retry of a 5xx answer | @node-service | 19 | +| datasource/plugin-supabase-storage.spec.ts | D11: the Supabase Storage plugin against the echo sidecar (project URL `/sb`; the Storage API is `/sb/storage/v1/...`). Measured on 3.0.0-e2e and 3.0.1-e2e (same requests and answers; supabase-js 2.45.4 in `x-client-info`, matched by shape): the client keeps the project URL's path with or without a trailing slash and derives no host name; every request carries `apikey: `, `authorization: Bearer `, the `node-fetch` user agent, `accept-encoding: gzip,deflate` and `connection: close`. Every request a D11 test makes is asserted completely (method, path and query, body, the whole header set), and every test that sends one also asserts that the key is in no header besides those two, no path or body, and no answer of the query (the whole query answer; in D11q the view's whole `q.data` as text); control: it is in those two. D11a listBuckets `GET /bucket` and the buckets as the API answered, D11b the project URL with and without a trailing slash reach the same path, D11c listObjects `POST /object/list/` with `{limit: 10, offset: 0, sortBy: {column: name, order: asc}, prefix}` and the public URL of each file in the answer, D11d limit, offset and sort order of the query, D11e the `search` field is not sent (D-76 candidate), D11f `returnSignedUrl` adds `POST /object/sign/` with `{expiresIn, paths}` and the signed URL in the answer, D11g readFile as text and base64 (`GET /object//`, answer `{data, type}`), D11h readFile with a transform goes to `/render/image/authenticated//?width=10`, D11i uploadData of text `POST /object//` with the text, its content type, `cache-control: max-age=3600` and `x-upsert: false`, D11j base64 without a content type sends an empty `content-type` header (observation), D11k uploadData with `returnSignedUrl` uploads then signs, D11l deleteFile `DELETE /object/` with `{prefixes: [name]}`, D11m createSignedUrl sends `expiresIn` as an integer above 1e12, an epoch time in milliseconds computed once (the second query, asserted completely too, sends the same number; the bounds allow one hour of clock skew and a plugin load up to six hours old; D-75 candidate, also asserted in D11f and D11k), D11n a 400, a 404 and a 401 answer fail the query with `{"size":0,"timeout":0}` instead of the answer's message, each followed by a control that the same query succeeds once the API answers 200 (D-74 candidate), D11o the signing and the listing fail the same way, each followed by a control that both succeed once the API answers 200 on their paths, D11p an empty bucket: listObjects says `Bucket is required` and sends nothing, readFile, uploadData, deleteFile and createSignedUrl send requests with an empty bucket segment (D-77 candidate), D11q the published view shows the bucket name only after the click (echo empty before, one request after). Not covered: a real Supabase project; the connection test (none is wired up for this plugin) | @node-service | 21 | +| datasource/plugin-firebird.spec.ts | D12: the Firebird plugin against the opt-in Firebird sidecar (Firebird 3.0.12, `fixtures/firebird/init.sql`; host, port, database path and login of the sidecar written over the recorded form body). Measured on 3.0.0-e2e and 3.0.1-e2e. D12a the connection test answers `code` 1, `success` true, `data` true; D12b a wrong password answers `code` 500 with `Failed to connect data source: Your user name and password are not defined. Ask your database\nadministrator to set up a Firebird login\n.` and a missing database file with the server's `I/O error for file ...` (the right fields attach first); D12c `SELECT ID, NAME FROM FB_ITEMS WHERE ID = :id` with `{"id": 2}` answers `[{id: 2, name: "beta"}]`; D12d the three seeded rows with `price` as a number and a NULL as `null`; D12e parameters bind in the order the names appear in the SQL, not the key order of the parameter object (`CAST(:first AS INTEGER) - CAST(:second AS INTEGER)` with 10 and 3 answers 7 whichever order the object lists them); D12f an unknown name fails with `Named parameter "missing" not found in Query Parameters object.` (the same SQL with the name present runs); D12g an INSERT answers `{}` and is read back by the test's own owner (the owner has no row before); D12h a syntax error and an unknown table answer the server's text; D12i `lowercaseKeys: false` answers upper-case keys; D12j a query that fails after the attach leaves its attachment open on the server, a succeeding one does not: two failing runs of a statement that tags its attachment with a per-test context variable leave exactly two tagged attachments in `MON$CONTEXT_VARIABLES`, and a succeeding tagged run does not add a third (D-78 candidate, `defect` annotation); D12k the runner connects to the sidecar's port 3050, and a closed port of the same host is refused. Limits: `role`, `blobAsText` and Firebird 4 and 5 are not covered; the sidecar authenticates with Legacy_Auth (see the architecture bullet) | @node-service @node-service-sidecar (opt-in) | 11 | +| datasource/plugin-turso-libsql.spec.ts | D13: the Turso plugin against the opt-in libSQL sidecar (sqld 0.24.33 with a JWT key; the data source URL is `http://e2e-libsql:8080`, the recorded `turso` form body with the sidecar's URL and token written over it; each test makes its own table `e2e_t_`). Measured on 3.0.0-e2e and 3.0.1-e2e. D13a CREATE, two INSERTs and a SELECT: a CREATE and an INSERT answer `[]`, the empty table answers `[]` before the inserts, then `integer` is a number, `real` 2 stays 2, a `boolean` column written in lower case is `true`/`false`, a `datetime` text is the ISO text of a `Date` (`2024-01-02T03:04:05.000Z`), NULL is `null`; D13b `includeRaw` answers `values` and the server's `raw` (columns with their declared types, cells such as `{type:"integer", value:"7"}`, the counters; the timing is only checked to be a number); D13c an INSERT answers `[]` with and without `includeRaw`, its raw result has `affected_row_count` 1 and `last_insert_rowid` `"2"` (a string) for the second row; D13d a blob cell is missing from the row (`[{id: 1}]`) while `includeRaw` shows the server sent `{type:"blob", base64:"AP8Q"}` (D-79 candidate); D13e `SELECT 9007199254740993` answers 9007199254740992 while the raw cell is the exact string (D-80 candidate); D13f `SELEC 1`, an unknown column, a duplicate key and `SELECT 1; SELECT 2` are errors of the server with codes `SQL_PARSE_ERROR`, `SQL_INPUT_ERROR`, `SQLITE_CONSTRAINT` and `SQL_MANY_STATEMENTS` (read by direct calls), and every one of them reaches the app as `Cannot parse result, received error: [object Object]` (D-66 candidate; a valid query of the same app succeeds first); D13g a token signed by another key and a string that is no JWT fail with `Failed to execute query. Endpoint returned 401: Unauthorized.` (the sidecar's own token reads the row first; direct calls show the server's `The JWT is invalid` and, without a header, `Expected authorization header but none given`); D13h a read-only token reads, its INSERT fails with `Endpoint returned 403: Forbidden.` and writes nothing (the read-write token then inserts the same row); D13i the published view shows a row after a click; D13j a URL with a trailing slash fails with `Endpoint returned 404: Not Found.` (the plugin builds `//v2/pipeline`; the same URL without it works); D13k the runner reaches the sidecar over HTTP and TCP, a closed port of the same host is refused. Limits: the `libsql://` to `https://` rewrite, a stream with a baton, and Turso's cloud features are not covered | @node-service @node-service-sidecar (opt-in) | 11 | +| datasource/plugin-couchdb.spec.ts | D14: the CouchDB plugin against the opt-in CouchDB sidecar (Apache CouchDB 3.5.1; the data source URL is `http://e2e-couchdb:5984`; the recorded `couchdb` form body with the sidecar's URL and admin written over it; each test makes its own database `e2e_couch_` and removes it). Measured on 3.0.0-e2e and 3.0.1-e2e. D14a a database is created (`{ok: true}`), listed by a key range (`[]` before, `[]` after), described (`GET /`: the member set of 3.5.1, `doc_count` 0), and deleted, with direct reads of the server at each step; D14b a document is created (`{ok, id, rev: 1-...}`), read (`{_id, _rev, ...body}`), updated with `rev` as a query parameter (`2-...`), read at its first revision, listed with `include_docs`, and deleted (`3-...`; the server then answers `deleted`), and the server's own copy matches; D14c a stale revision (query parameter and `If-Match`, on write and delete) and a write without a revision answer `{error: "conflict", reason: "Document update conflict."}` as the data of a SUCCESSFUL query (the server's status is 409), change nothing, and the current revision is accepted by a write and by both kinds of delete (D-69 candidate); D14d a missing document, a document of a missing database, the information and the delete of a missing database (404 bodies) and a create of an existing database (412 `file_exists`) are successful queries with the error body as the data (D-69 candidate), with successful controls through the same operations (an existing document is read, an existing database is described and deleted, a new one is created); D14e a wrong password answers `{error: "unauthorized", reason: "Name or password is incorrect."}` as the data of a successful query and the refused create made no database, while the right password on the same queries lists and creates (D-69 candidate; the account is a second admin the test makes); D14f `docGet` with an empty `If-None-Match` fails with the plugin's own `Required parameter If-None-Match is not provided` (the server reads the same document without the header), a value that is not the current ETag reads the document, and the current ETag (the server answers 304) fails with `status: 304` (D-81 candidate); D14g `startkey`/`endkey`, `descending`, `skip` and `limit` give the lists the server gives, for databases and for the documents of a database (`total_rows` counts all of them), and an unscoped list holds the three system databases and the test's own; D14h the published view shows the document's title after a click; D14i the runner reaches the sidecar over HTTP and TCP (`Welcome`, version 3.5.1, `_all_dbs` needs credentials), a closed port of the same host is refused; D14j five wrong passwords of an account are 401 bodies, the sixth and the right password after them are the lockout's 403 body as the data of a successful query (the runner, another client address, is not locked until it fails five times itself, then the server's own status is 403) (D-69 candidate). Limits: JWT and cookie authentication, replication, design documents, partitions, attachments and bulk operations are not covered | @node-service @node-service-sidecar (opt-in) | 10 | +| datasource/plugin-dynamodb-local.spec.ts | D15: the DynamoDB plugin against the opt-in DynamoDB Local sidecar (DynamoDB Local 3.3.2, `-inMemory -sharedDb`; the endpoint is `http://e2e-dynamodb:8000`; the recorded `dynamodb` form body with the sidecar's endpoint and throw-away key written over it; each test makes its own tables `e2e_ddb_` and removes them). Measured on 3.0.0-e2e and 3.0.1-e2e. D15a to D15l as in the catalogue (D15): table create, list and paging, the typed round trip of every type, Query and Scan with pagination keys, UpdateItem and DeleteItem with conditions and `ReturnValues`, the server's error messages, sets, binary and big numbers, the plain `ExclusiveStartKey`, any access key and a closed port, the published view, and the runner's reach. D-82 to D-85 candidates are characterised and annotated. Not covered: indexes, transactions, batch operations, streams, TTL, the signature (the server does not verify it) | @node-service @node-service-sidecar (opt-in) | 12 | +| datasource/plugin-s3-server.spec.ts | D16: the S3 plugin against the opt-in S3 sidecar (versitygw v1.11.0 with its POSIX backend in tmpfs; the endpoint is the sidecar's IP address `http://:7070`, never a name; the recorded `s3` form body and the five recorded queries with the sidecar's endpoint and throw-away key pair written over them; each test makes its own bucket `e2e-s3-` INSIDE its `try` and removes its objects and the bucket in the `finally`; direct signed calls from the test process, `s3Direct`, are the controls that show what the server holds). Measured on 3.0.0-e2e and 3.0.1-e2e. D16a to D16o as in the catalogue (D16). D-73, D-86, D-87, D-88 and D-89 candidates are characterised and annotated. Not covered: a real AWS S3 (the server differs in limits, versioning, ACLs, storage classes and checksums), multipart upload, an expired presigned URL | @node-service @node-service-sidecar (opt-in) | 15 | | datasource/node-plugins-catalogue.spec.ts | D3: the catalogue serves exactly the 46 registered node plugins (measured on 3.0.0-e2e and 3.0.1-e2e, so `duckdb` loads), every definition has a form and a query config, all 14 Java-native types of the catalogue answer `definition: null` (an explicit list, so a dropped or renamed type fails) | @node-service | 3 | ### logic (22) @@ -575,30 +575,30 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | CD-7 | `setIn` with a bad path or on a scalar fails silently (query ends as success) | `logic/temporary-state.spec.ts` asserts today's behaviour, annotation `{type:"defect", description:"CD-7"}`, default run | | CD-8 | `transfer` list titles are in the wrong order: confirmed by code (`titles={[targetTitle, sourceTitle]}`, 2026-11-22 reading) | conditional `defect` annotation in `components/choices.spec.ts` (the annotation still says candidate) | | CD-9 | an icon switched from a name to an image URL keeps the old icon: confirmed (failed 3 of 3 on 3.0.1-e2e; code: the old icon is cached under the new URL and `undefined === undefined` keeps it) | `components/displays.spec.ts`, `@quarantine`, `defect` annotation (still named candidate there) | -| NSD-1 candidate | the Turso plugin prints a pipeline `error` result as `${result.error}`, an object: a failed statement reaches the app as `Cannot parse result, received error: [object Object]` and the server's own message is lost; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-turso-slack.spec.ts` D5d asserts today's message (characterisation, default run), annotation `{type:"defect", description:"NSD-1 candidate"}`; it changes when the plugin prints the message. Against the real libSQL sidecar the same text is printed for a syntax error, an unknown column, a constraint violation and a two-statement string, each of which the server answers with its own message and code (`datasource/plugin-turso-libsql.spec.ts` D13f, same annotation) | -| NSD-3 candidate | the DuckDB plugin answers rows keyed by the column position, not the column name (`SELECT 42 AS answer` arrives as `{"0": 42}`): `getRows()` answers arrays and `serializeBigInts` copies `Object.entries(row)`; measured on 3.0.0-e2e and 3.0.1-e2e. An app cannot read `row.answer`. The id is provisional until the owner assigns one | `datasource/plugin-duckdb.spec.ts` D4a to D4c assert today's keys (characterisation, default run), annotation `{type:"defect", description:"NSD-3 candidate"}`; they change when the plugin keys rows by name | -| NSD-2 candidate | the Shopify plugin reads the query's headers and passes `{}` on, and its data source has only `endpoint`: it cannot send Shopify's access token (`X-Shopify-Access-Token`); measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-graphql.spec.ts` D6d asserts today's behaviour after a control that the request did reach the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-2 candidate"}`; it changes when the query's headers are forwarded | -| NSD-4 candidate | the generic Open API plugin returns the body of an error status answer as the query result (`runOpenApi` catch, `e.response.body`): a canned 404 `{"message":"e2e-missing"}` is reported as `success: true`, `queryCode: "OK"`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi.spec.ts` D7d asserts today's behaviour after a control that the request reached the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-4 candidate"}`; it changes when an error status fails the query. `datasource/plugin-openapi-wrappers-apps.spec.ts` D9i shows the same for APITemplate (wrappers share `runOpenApi`). Against the real CouchDB sidecar `datasource/plugin-couchdb.spec.ts` D14c, D14d, D14e and D14j show it for the server's own 409 (stale revision), 404 (missing database or document), 412 (database exists), 401 (wrong password) and 403 (locked account) answers: each is `success: true`, `queryCode: "OK"` with the error body as the data and the status is lost; each test first shows the server's status by direct calls and has these successful controls: D14c the current revision accepted by a write and by a delete (as a query parameter and as `If-Match`); D14d an existing document read, the information of an existing database, the delete of an existing database and the create of a new one; D14e the same two queries with the right password; D14j the right password listing before the five failures, and the sidecar's own admin still working after them. Annotation `NSD-4 candidate` | -| NSD-5 candidate | the WooCommerce plugin appends `wp-json/wc/v3` to a server URL unless it ends exactly in `/wc/v3`, so a server URL copied with a trailing slash (`/wp-json/wc/v3/`) is requested at `/wp-json/wc/v3/wp-json/wc/v3/products`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-data.spec.ts` D8h asserts today's behaviour (characterisation, default run), annotation `{type:"defect", description:"NSD-5 candidate"}`; it changes when a trailing slash is accepted | -| NSD-6 candidate | the UiPath plugin cannot run: `getSchemaExample` (`plugins/openApi/util.ts`) recurses without end on a circular schema of the bundled document, so the query configuration (`POST /api/datasources/getPluginDynamicConfig`, path `$.queryConfig`) answers 500 / code 5000 `get dynamic config error` (the editor lists no operation and cannot save a UiPath query) and every query fails with `Maximum call stack size exceeded` before any request is sent; the cause (`RangeError: Maximum call stack size exceeded` at `getSchemaExample`, from a circular schema) was read in the app container's node-service log while recording, not asserted: the suite asserts only the HTTP 500 / code 5000 of the configuration request, the query's failure message and that no request is sent; measured on 3.0.0-e2e and 3.0.1-e2e. Whether UiPath sends its `Authorization` header (a doubled `Bearer`, or none) cannot be measured today. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9j and D9k assert today's behaviour after a control that another plugin reaches the echo / lists its operations (characterisation, default run), annotation `{type:"defect", description:"NSD-6 candidate"}`; D9l asserts the desired behaviour (`GET /odata/Folders` with `Authorization: Bearer ` exactly), `@quarantine`, same annotation; they change when the plugin runs | -| NSD-7 candidate | an OpenAI data source on spec version `v1.0` (the version an empty choice selects) sends no `Authorization` header: the plugin hands the key over as `ApiKeyAuth.value`, the security scheme of the `v2.3` document, while the `v1.0` document names its scheme `ApiKey`; with `v2.3` the same key is sent as `Authorization: Bearer `; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9h asserts today's behaviour after a control that v2.3 sends the key to the same echo (characterisation, default run), annotation `{type:"defect", description:"NSD-7 candidate"}`; it changes when the key reaches the `v1.0` document's scheme | -| NSD-8 candidate | the S3 plugin checks the bucket itself only for `listObjects` (`Bucket is required`); `readFile`, `uploadData` and `deleteFile` with an empty bucket reach the AWS SDK, which refuses before any request with its own text `Empty value provided for input HTTP label: Bucket.`, so the user sees an SDK message and the checks are inconsistent; no request is sent in any of the four cases; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-aws-sdk.spec.ts` D10q asserts today's messages after a control that a call with a bucket reaches the echo (characterisation, default run), annotation `{type:"defect", description:"NSD-8 candidate"}`; it changes when the three operations check the bucket like `listObjects`. The same four messages are asserted against the S3 sidecar by `datasource/plugin-s3-server.spec.ts` D16l, next to a control that a call with a real bucket works and that nothing was stored | -| NSD-9 candidate | a storage error answer of the Supabase Storage plugin (any status: 400, 401 and 404 measured) fails the query with `{"size":0,"timeout":0}`, the JSON of node-fetch's `Response`, not with the API's message (`e2e-storage-error` in the canned answer): storage-js recognises an HTTP error only as an instance of the global `Response`, and node-service's proxy fetch answers with node-fetch's class; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11n and D11o assert today's message after a control that the same query succeeds when the API answers 200 (characterisation, default run), annotation `{type:"defect", description:"NSD-9 candidate"}`; they change when the message of the answer reaches the user | -| NSD-10 candidate | the Supabase Storage plugin sends the signed-URL validity as `expiresIn: Date.now() + 5 minutes` in milliseconds (13 digits, about 1.8e12 when measured), computed once when node-service loads the plugin, where the API takes seconds: every signing request of one node-service process carries the same number; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11f, D11k and D11m assert the magnitude (above 1e12, and within clock-skew and plugin-age allowances of now plus five minutes) and, in D11m, that two queries send the same value (characterisation, default run), annotation `{type:"defect", description:"NSD-10 candidate"}`; they change when the validity is 300 | -| NSD-11 candidate | the `search` field of the Supabase Storage listObjects query is never sent: the request body is `{limit, offset, sortBy, prefix}` whatever the field holds; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11e asserts today's body after a positive control that the query's prefix travels (characterisation, default run), annotation `{type:"defect", description:"NSD-11 candidate"}`; it changes when the search text is sent | -| NSD-12 candidate | the Supabase Storage plugin checks the bucket itself only for listObjects (`Bucket is required`); readFile, uploadData, deleteFile and createSignedUrl with an empty bucket send a request whose path has an empty bucket segment (`GET /object//x.txt`, `POST /object//x.txt`, `DELETE /object/`, `POST /object/sign//x.txt`), and the queries succeed against a server that answers; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11p asserts today's requests next to listObjects refusing the same empty bucket and sending nothing (characterisation, default run), annotation `{type:"defect", description:"NSD-12 candidate"}`; it changes when the four operations check the bucket like listObjects | -| NSD-13 candidate | the Firebird plugin never detaches a connection when its query fails after the attach (`firebirdsql/run.ts`: `detachAsync()` comes after the awaited query, and the unknown-parameter check also runs after the attach), so the attachment stays open on the server; a succeeding query detaches. Measured on 3.0.0-e2e and 3.0.1-e2e against the Firebird sidecar: after two failing runs of a statement that tags its attachment (`RDB$SET_CONTEXT`, then a division by zero) `MON$CONTEXT_VARIABLES` holds exactly 2 attachments with the tag, and a succeeding tagged run leaves it at 2. The id is provisional until the owner assigns one | `datasource/plugin-firebird.spec.ts` D12j, `defect` annotation `NSD-13 candidate`; passes today, expect it to fail once the plugin detaches in `finally` | -| NSD-14 candidate | the Turso plugin drops a `blob` cell: the server answers it as `{type:"blob", base64}` with no `value`, `parseValue` returns `undefined` for it, and the key is missing from the row (`SELECT id, data` answers `[{id: 1}]`). Measured on 3.0.0-e2e and 3.0.1-e2e against the libSQL sidecar. The id is provisional until the owner assigns one | `datasource/plugin-turso-libsql.spec.ts` D13d, `defect` annotation `NSD-14 candidate`; passes today, expect it to fail once the plugin returns the bytes | -| NSD-15 candidate | the Turso plugin parses an `integer` cell (which the server sends as a string, exact) with `Number.parseInt`, so an integer above 2^53 is rounded: `SELECT 9007199254740993` answers 9007199254740992 while `includeRaw` shows the exact string. Measured on 3.0.0-e2e and 3.0.1-e2e against the libSQL sidecar. The id is provisional until the owner assigns one | `datasource/plugin-turso-libsql.spec.ts` D13e, `defect` annotation `NSD-15 candidate`; passes today, expect it to fail once the plugin keeps large integers exact | -| NSD-16 candidate | the CouchDB plugin cannot run `docGet` without an `If-None-Match` header: the bundled API document marks it required (the server treats it as optional: a read without it answers the document), and `runOpenApi` refuses the query with `Required parameter If-None-Match is not provided`; a value that is not the current ETag (`e2e-no-match` measured) reads the document, and a value equal to the document's current ETag (`""`) makes the server answer 304 with no body, which fails the query with `status: 304`. So a read of a document cannot be made without a header the user has no use for. Measured on 3.0.0-e2e and 3.0.1-e2e against the CouchDB sidecar. The id is provisional until the owner assigns one | `datasource/plugin-couchdb.spec.ts` D14f, `defect` annotation `NSD-16 candidate` (characterisation, passes today after controls that the server reads the document without the header and answers 304 to the current ETag); it changes when the header is optional | -| NSD-17 candidate | the DynamoDB plugin unwraps `Item` and `Items` of an answer (`processItems`) and nothing else: `Attributes` of a `ReturnValues` answer (`ALL_NEW`, `ALL_OLD`) and `LastEvaluatedKey` stay in DynamoDB's typed form (`{"age":{"N":"19"}}`), while the same item read by GetItem is plain (`{"age":19}`). `LastEvaluatedKey` staying typed is what a typed `ExclusiveStartKey` needs to continue; `Attributes` has no such use. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15d and D15e, `defect` annotation `NSD-17 candidate` (characterisation, passes today next to a direct read of the server's data and a plain GetItem of the same item); it changes when `Attributes` is unwrapped | -| NSD-18 candidate | the DynamoDB plugin writes every array of strings as a string set and every array of numbers as a number set (`dynamodb-data-types` `detectType`; only other arrays are lists), so a list of strings or numbers cannot be stored: the order is lost (`["zeta","alpha","mid"]` reads back `["alpha","mid","zeta"]`), duplicates fail the query (`Input collection [a, a] contains duplicates`) and an empty array fails with `An number set may not be empty` (sic, the server's text). An array of mixed values is a list and keeps its order. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15g, `defect` annotation `NSD-18 candidate` (characterisation, passes today next to the mixed array, which is a list); it changes when a list can be written | -| NSD-19 candidate | the DynamoDB plugin reads a number with `Number()`, so a number beyond a double loses digits (`12345678901234567890` reads `12345678901234567000`; the server holds it exactly), and a binary attribute (`B`, `BS`) is read as a byte array that the answer's JSON turns into an object with index keys (`{"0":104,"1":101,...}`); a binary cannot be written either: a typed `{"B":"..."}` inside `Item` is wrapped like any object and stored as a map. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15h, `defect` annotation `NSD-19 candidate` (characterisation, passes today next to a direct read that shows the exact number and the binary); it changes when numbers and binaries are returned exactly | -| NSD-20 candidate | an `ExclusiveStartKey` given in the plain form (`{"id": 1}`, as `Key` is written) is not wrapped (only `Key`, `Item` and `Items` are) and fails inside the SDK's serialiser with the JavaScript text `Cannot read properties of undefined (reading '0')` instead of a validation message; the typed form (`{"id": {"N": "1"}}`) works. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15i, `defect` annotation `NSD-20 candidate` (characterisation, passes today next to the typed form of the same key, which continues the read); it changes when the key is wrapped or refused with a message | -| NSD-21 candidate | `listObjects` cannot continue a listing: it sends ListObjects (version 1) with the prefix, the delimiter and `limit` as max-keys, no marker, and returns a bare array of objects, so when the bucket holds more keys than `limit` the user sees the first page without any sign that it was cut (the server answered `IsTruncated: true` and a continuation token, shown by a direct call). Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar. The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16f, `defect` annotation `NSD-21 candidate` (characterisation, passes today next to a control that the same query with a larger limit shows every key); it changes when a marker or a truncation flag is offered | -| NSD-22 candidate | `listObjects` with a delimiter returns only the `Contents` of the answer: the common prefixes ("folders") the server lists are dropped, so `delimiter: "/"` shows the keys of one level and none of the folders below it. Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar (control: a direct call answers one key and two common prefixes). The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16g, `defect` annotation `NSD-22 candidate` (characterisation, passes today); it changes when the common prefixes are returned | -| NSD-23 candidate | `uploadData` decodes `data` as base64 unless the encoding is `utf8` (the form's default is base64), and Node's decoder accepts text that is not base64: `hello world, this is not base64!` is stored as other bytes and the query succeeds, with no message (the same text with the text encoding is stored as typed). Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar. The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16n, `defect` annotation `NSD-23 candidate` (characterisation, passes today next to the text-encoding control); it changes when invalid base64 is refused | -| NSD-24 candidate | the `url` that `listObjects` and `uploadData` answer is the endpoint, the bucket and the key joined as they are (`getFileUrl`): a key with `?`, `#` or `%` names another resource, and a space or non-ASCII text is not a valid URL until a client encodes it (with the bucket private the plain `url` is refused anyway, 403 `AccessDenied`, while the presigned URL of the same object works). Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar. The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16j (the `url` of eight keys equals the unencoded join) and D16i (the plain `url` is refused, the presigned URL downloads), `defect` annotation `NSD-24 candidate` on D16j (characterisation, passes today); it changes when the key is encoded in the `url` | +| D-66 candidate | the Turso plugin prints a pipeline `error` result as `${result.error}`, an object: a failed statement reaches the app as `Cannot parse result, received error: [object Object]` and the server's own message is lost; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-turso-slack.spec.ts` D5d asserts today's message (characterisation, default run), annotation `{type:"defect", description:"D-66 candidate"}`; it changes when the plugin prints the message. Against the real libSQL sidecar the same text is printed for a syntax error, an unknown column, a constraint violation and a two-statement string, each of which the server answers with its own message and code (`datasource/plugin-turso-libsql.spec.ts` D13f, same annotation) | +| D-68 candidate | the DuckDB plugin answers rows keyed by the column position, not the column name (`SELECT 42 AS answer` arrives as `{"0": 42}`): `getRows()` answers arrays and `serializeBigInts` copies `Object.entries(row)`; measured on 3.0.0-e2e and 3.0.1-e2e. An app cannot read `row.answer`. The id is provisional until the owner assigns one | `datasource/plugin-duckdb.spec.ts` D4a to D4c assert today's keys (characterisation, default run), annotation `{type:"defect", description:"D-68 candidate"}`; they change when the plugin keys rows by name | +| D-67 candidate | the Shopify plugin reads the query's headers and passes `{}` on, and its data source has only `endpoint`: it cannot send Shopify's access token (`X-Shopify-Access-Token`); measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-graphql.spec.ts` D6d asserts today's behaviour after a control that the request did reach the echo (characterisation, default run), annotation `{type:"defect", description:"D-67 candidate"}`; it changes when the query's headers are forwarded | +| D-69 candidate | the generic Open API plugin returns the body of an error status answer as the query result (`runOpenApi` catch, `e.response.body`): a canned 404 `{"message":"e2e-missing"}` is reported as `success: true`, `queryCode: "OK"`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi.spec.ts` D7d asserts today's behaviour after a control that the request reached the echo (characterisation, default run), annotation `{type:"defect", description:"D-69 candidate"}`; it changes when an error status fails the query. `datasource/plugin-openapi-wrappers-apps.spec.ts` D9i shows the same for APITemplate (wrappers share `runOpenApi`). Against the real CouchDB sidecar `datasource/plugin-couchdb.spec.ts` D14c, D14d, D14e and D14j show it for the server's own 409 (stale revision), 404 (missing database or document), 412 (database exists), 401 (wrong password) and 403 (locked account) answers: each is `success: true`, `queryCode: "OK"` with the error body as the data and the status is lost; each test first shows the server's status by direct calls and has these successful controls: D14c the current revision accepted by a write and by a delete (as a query parameter and as `If-Match`); D14d an existing document read, the information of an existing database, the delete of an existing database and the create of a new one; D14e the same two queries with the right password; D14j the right password listing before the five failures, and the sidecar's own admin still working after them. Annotation `D-69 candidate` | +| D-70 candidate | the WooCommerce plugin appends `wp-json/wc/v3` to a server URL unless it ends exactly in `/wc/v3`, so a server URL copied with a trailing slash (`/wp-json/wc/v3/`) is requested at `/wp-json/wc/v3/wp-json/wc/v3/products`; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-data.spec.ts` D8h asserts today's behaviour (characterisation, default run), annotation `{type:"defect", description:"D-70 candidate"}`; it changes when a trailing slash is accepted | +| D-71 candidate | the UiPath plugin cannot run: `getSchemaExample` (`plugins/openApi/util.ts`) recurses without end on a circular schema of the bundled document, so the query configuration (`POST /api/datasources/getPluginDynamicConfig`, path `$.queryConfig`) answers 500 / code 5000 `get dynamic config error` (the editor lists no operation and cannot save a UiPath query) and every query fails with `Maximum call stack size exceeded` before any request is sent; the cause (`RangeError: Maximum call stack size exceeded` at `getSchemaExample`, from a circular schema) was read in the app container's node-service log while recording, not asserted: the suite asserts only the HTTP 500 / code 5000 of the configuration request, the query's failure message and that no request is sent; measured on 3.0.0-e2e and 3.0.1-e2e. Whether UiPath sends its `Authorization` header (a doubled `Bearer`, or none) cannot be measured today. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9j and D9k assert today's behaviour after a control that another plugin reaches the echo / lists its operations (characterisation, default run), annotation `{type:"defect", description:"D-71 candidate"}`; D9l asserts the desired behaviour (`GET /odata/Folders` with `Authorization: Bearer ` exactly), `@quarantine`, same annotation; they change when the plugin runs | +| D-72 candidate | an OpenAI data source on spec version `v1.0` (the version an empty choice selects) sends no `Authorization` header: the plugin hands the key over as `ApiKeyAuth.value`, the security scheme of the `v2.3` document, while the `v1.0` document names its scheme `ApiKey`; with `v2.3` the same key is sent as `Authorization: Bearer `; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-openapi-wrappers-apps.spec.ts` D9h asserts today's behaviour after a control that v2.3 sends the key to the same echo (characterisation, default run), annotation `{type:"defect", description:"D-72 candidate"}`; it changes when the key reaches the `v1.0` document's scheme | +| D-73 candidate | the S3 plugin checks the bucket itself only for `listObjects` (`Bucket is required`); `readFile`, `uploadData` and `deleteFile` with an empty bucket reach the AWS SDK, which refuses before any request with its own text `Empty value provided for input HTTP label: Bucket.`, so the user sees an SDK message and the checks are inconsistent; no request is sent in any of the four cases; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-aws-sdk.spec.ts` D10q asserts today's messages after a control that a call with a bucket reaches the echo (characterisation, default run), annotation `{type:"defect", description:"D-73 candidate"}`; it changes when the three operations check the bucket like `listObjects`. The same four messages are asserted against the S3 sidecar by `datasource/plugin-s3-server.spec.ts` D16l, next to a control that a call with a real bucket works and that nothing was stored | +| D-74 candidate | a storage error answer of the Supabase Storage plugin (any status: 400, 401 and 404 measured) fails the query with `{"size":0,"timeout":0}`, the JSON of node-fetch's `Response`, not with the API's message (`e2e-storage-error` in the canned answer): storage-js recognises an HTTP error only as an instance of the global `Response`, and node-service's proxy fetch answers with node-fetch's class; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11n and D11o assert today's message after a control that the same query succeeds when the API answers 200 (characterisation, default run), annotation `{type:"defect", description:"D-74 candidate"}`; they change when the message of the answer reaches the user | +| D-75 candidate | the Supabase Storage plugin sends the signed-URL validity as `expiresIn: Date.now() + 5 minutes` in milliseconds (13 digits, about 1.8e12 when measured), computed once when node-service loads the plugin, where the API takes seconds: every signing request of one node-service process carries the same number; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11f, D11k and D11m assert the magnitude (above 1e12, and within clock-skew and plugin-age allowances of now plus five minutes) and, in D11m, that two queries send the same value (characterisation, default run), annotation `{type:"defect", description:"D-75 candidate"}`; they change when the validity is 300 | +| D-76 candidate | the `search` field of the Supabase Storage listObjects query is never sent: the request body is `{limit, offset, sortBy, prefix}` whatever the field holds; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11e asserts today's body after a positive control that the query's prefix travels (characterisation, default run), annotation `{type:"defect", description:"D-76 candidate"}`; it changes when the search text is sent | +| D-77 candidate | the Supabase Storage plugin checks the bucket itself only for listObjects (`Bucket is required`); readFile, uploadData, deleteFile and createSignedUrl with an empty bucket send a request whose path has an empty bucket segment (`GET /object//x.txt`, `POST /object//x.txt`, `DELETE /object/`, `POST /object/sign//x.txt`), and the queries succeed against a server that answers; measured on 3.0.0-e2e and 3.0.1-e2e. The id is provisional until the owner assigns one | `datasource/plugin-supabase-storage.spec.ts` D11p asserts today's requests next to listObjects refusing the same empty bucket and sending nothing (characterisation, default run), annotation `{type:"defect", description:"D-77 candidate"}`; it changes when the four operations check the bucket like listObjects | +| D-78 candidate | the Firebird plugin never detaches a connection when its query fails after the attach (`firebirdsql/run.ts`: `detachAsync()` comes after the awaited query, and the unknown-parameter check also runs after the attach), so the attachment stays open on the server; a succeeding query detaches. Measured on 3.0.0-e2e and 3.0.1-e2e against the Firebird sidecar: after two failing runs of a statement that tags its attachment (`RDB$SET_CONTEXT`, then a division by zero) `MON$CONTEXT_VARIABLES` holds exactly 2 attachments with the tag, and a succeeding tagged run leaves it at 2. The id is provisional until the owner assigns one | `datasource/plugin-firebird.spec.ts` D12j, `defect` annotation `D-78 candidate`; passes today, expect it to fail once the plugin detaches in `finally` | +| D-79 candidate | the Turso plugin drops a `blob` cell: the server answers it as `{type:"blob", base64}` with no `value`, `parseValue` returns `undefined` for it, and the key is missing from the row (`SELECT id, data` answers `[{id: 1}]`). Measured on 3.0.0-e2e and 3.0.1-e2e against the libSQL sidecar. The id is provisional until the owner assigns one | `datasource/plugin-turso-libsql.spec.ts` D13d, `defect` annotation `D-79 candidate`; passes today, expect it to fail once the plugin returns the bytes | +| D-80 candidate | the Turso plugin parses an `integer` cell (which the server sends as a string, exact) with `Number.parseInt`, so an integer above 2^53 is rounded: `SELECT 9007199254740993` answers 9007199254740992 while `includeRaw` shows the exact string. Measured on 3.0.0-e2e and 3.0.1-e2e against the libSQL sidecar. The id is provisional until the owner assigns one | `datasource/plugin-turso-libsql.spec.ts` D13e, `defect` annotation `D-80 candidate`; passes today, expect it to fail once the plugin keeps large integers exact | +| D-81 candidate | the CouchDB plugin cannot run `docGet` without an `If-None-Match` header: the bundled API document marks it required (the server treats it as optional: a read without it answers the document), and `runOpenApi` refuses the query with `Required parameter If-None-Match is not provided`; a value that is not the current ETag (`e2e-no-match` measured) reads the document, and a value equal to the document's current ETag (`""`) makes the server answer 304 with no body, which fails the query with `status: 304`. So a read of a document cannot be made without a header the user has no use for. Measured on 3.0.0-e2e and 3.0.1-e2e against the CouchDB sidecar. The id is provisional until the owner assigns one | `datasource/plugin-couchdb.spec.ts` D14f, `defect` annotation `D-81 candidate` (characterisation, passes today after controls that the server reads the document without the header and answers 304 to the current ETag); it changes when the header is optional | +| D-82 candidate | the DynamoDB plugin unwraps `Item` and `Items` of an answer (`processItems`) and nothing else: `Attributes` of a `ReturnValues` answer (`ALL_NEW`, `ALL_OLD`) and `LastEvaluatedKey` stay in DynamoDB's typed form (`{"age":{"N":"19"}}`), while the same item read by GetItem is plain (`{"age":19}`). `LastEvaluatedKey` staying typed is what a typed `ExclusiveStartKey` needs to continue; `Attributes` has no such use. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15d and D15e, `defect` annotation `D-82 candidate` (characterisation, passes today next to a direct read of the server's data and a plain GetItem of the same item); it changes when `Attributes` is unwrapped | +| D-83 candidate | the DynamoDB plugin writes every array of strings as a string set and every array of numbers as a number set (`dynamodb-data-types` `detectType`; only other arrays are lists), so a list of strings or numbers cannot be stored: the order is lost (`["zeta","alpha","mid"]` reads back `["alpha","mid","zeta"]`), duplicates fail the query (`Input collection [a, a] contains duplicates`) and an empty array fails with `An number set may not be empty` (sic, the server's text). An array of mixed values is a list and keeps its order. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15g, `defect` annotation `D-83 candidate` (characterisation, passes today next to the mixed array, which is a list); it changes when a list can be written | +| D-84 candidate | the DynamoDB plugin reads a number with `Number()`, so a number beyond a double loses digits (`12345678901234567890` reads `12345678901234567000`; the server holds it exactly), and a binary attribute (`B`, `BS`) is read as a byte array that the answer's JSON turns into an object with index keys (`{"0":104,"1":101,...}`); a binary cannot be written either: a typed `{"B":"..."}` inside `Item` is wrapped like any object and stored as a map. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15h, `defect` annotation `D-84 candidate` (characterisation, passes today next to a direct read that shows the exact number and the binary); it changes when numbers and binaries are returned exactly | +| D-85 candidate | an `ExclusiveStartKey` given in the plain form (`{"id": 1}`, as `Key` is written) is not wrapped (only `Key`, `Item` and `Items` are) and fails inside the SDK's serialiser with the JavaScript text `Cannot read properties of undefined (reading '0')` instead of a validation message; the typed form (`{"id": {"N": "1"}}`) works. Measured on 3.0.0-e2e and 3.0.1-e2e against the DynamoDB Local sidecar. The id is provisional until the owner assigns one | `datasource/plugin-dynamodb-local.spec.ts` D15i, `defect` annotation `D-85 candidate` (characterisation, passes today next to the typed form of the same key, which continues the read); it changes when the key is wrapped or refused with a message | +| D-86 candidate | `listObjects` cannot continue a listing: it sends ListObjects (version 1) with the prefix, the delimiter and `limit` as max-keys, no marker, and returns a bare array of objects, so when the bucket holds more keys than `limit` the user sees the first page without any sign that it was cut (the server answered `IsTruncated: true` and a continuation token, shown by a direct call). Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar. The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16f, `defect` annotation `D-86 candidate` (characterisation, passes today next to a control that the same query with a larger limit shows every key); it changes when a marker or a truncation flag is offered | +| D-87 candidate | `listObjects` with a delimiter returns only the `Contents` of the answer: the common prefixes ("folders") the server lists are dropped, so `delimiter: "/"` shows the keys of one level and none of the folders below it. Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar (control: a direct call answers one key and two common prefixes). The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16g, `defect` annotation `D-87 candidate` (characterisation, passes today); it changes when the common prefixes are returned | +| D-88 candidate | `uploadData` decodes `data` as base64 unless the encoding is `utf8` (the form's default is base64), and Node's decoder accepts text that is not base64: `hello world, this is not base64!` is stored as other bytes and the query succeeds, with no message (the same text with the text encoding is stored as typed). Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar. The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16n, `defect` annotation `D-88 candidate` (characterisation, passes today next to the text-encoding control); it changes when invalid base64 is refused | +| D-89 candidate | the `url` that `listObjects` and `uploadData` answer is the endpoint, the bucket and the key joined as they are (`getFileUrl`): a key with `?`, `#` or `%` names another resource, and a space or non-ASCII text is not a valid URL until a client encodes it (with the bucket private the plain `url` is refused anyway, 403 `AccessDenied`, while the presigned URL of the same object works). Measured on 3.0.0-e2e and 3.0.1-e2e against the S3 sidecar. The id is provisional until the owner assigns one | `datasource/plugin-s3-server.spec.ts` D16j (the `url` of eight keys equals the unencoded join) and D16i (the plain `url` is refused, the presigned URL downloads), `defect` annotation `D-89 candidate` on D16j (characterisation, passes today); it changes when the key is encoded in the `url` | | CD-4 | npm components fail silently without internet; version is `latest` | `@npm`, render-only assertions | | O-11 | observation: back-to-back key presses on a slider are lost | `components/sliders-color.spec.ts` asserts the bound text after every press | | O-12 | observation: publishing an existing version tag of a module answers HTTP 500 / code 5000, not a tag-specific error | `modules/module-versions.spec.ts` asserts only that the call fails with the API error type and records the message in an `observation` annotation | diff --git a/e2e/tests/datasource/plugin-aws-sdk.spec.ts b/e2e/tests/datasource/plugin-aws-sdk.spec.ts index e549e18d3d..d6fc250d24 100644 --- a/e2e/tests/datasource/plugin-aws-sdk.spec.ts +++ b/e2e/tests/datasource/plugin-aws-sdk.spec.ts @@ -39,7 +39,7 @@ const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; * `uploadData` and `deleteFile` do not, so the SDK's own text (`Empty value provided for input HTTP label: Bucket.`) reaches the * user. No request is sent in either case. */ -const BUCKET_CHECK_DEFECT = { type: "defect", description: "NSD-8 candidate" } as const; +const BUCKET_CHECK_DEFECT = { type: "defect", description: "D-73 candidate" } as const; const BUCKET_CHECK_DETAILS = { annotation: BUCKET_CHECK_DEFECT }; const HTTP_OK = 200; @@ -722,7 +722,7 @@ test.describe("S3 data source against the echo", NODE_SERVICE_DETAILS, () => { const rows: Array<{ variant: string; action: Record; message: string }> = [ // the one operation that checks the bucket itself { variant: "ListObjects", action: { bucket: "" }, message: "Bucket is required" }, - // NSD-8 candidate: the others hand the SDK's own text to the user (measured) + // D-73 candidate: the others hand the SDK's own text to the user (measured) { variant: "ReadFile", action: { bucket: "", fileName: OBJECT_KEY }, message: sdkText }, { variant: "UploadData", action: { bucket: "", fileName: OBJECT_KEY, encoding: "utf8", data: "x" }, message: sdkText }, { variant: "DeleteFile", action: { bucket: "", fileName: OBJECT_KEY }, message: sdkText }, diff --git a/e2e/tests/datasource/plugin-couchdb.spec.ts b/e2e/tests/datasource/plugin-couchdb.spec.ts index f8396f4633..7020beca2e 100644 --- a/e2e/tests/datasource/plugin-couchdb.spec.ts +++ b/e2e/tests/datasource/plugin-couchdb.spec.ts @@ -24,11 +24,11 @@ import { expect, test } from "../../src/fixtures"; * Measured on the images `3.0.0-e2e` and `3.0.1-e2e` against CouchDB 3.5.1 (the plugin's bundled document is the 3.1.1 one): * - Every operation the plugin runs answers the JSON body of the server's answer as the query's data (`success: true`, `queryCode: "OK"`). * - An HTTP error answer that carries a body is ALSO reported as `success: true`, with the error body as the data: 412 (database exists), 404 - * (missing database or document), 409 (stale revision), 401 (wrong password) all arrive this way (NSD-4 candidate, the defect D7d shows + * (missing database or document), 409 (stale revision), 401 (wrong password) all arrive this way (D-69 candidate, the defect D7d shows * against a canned answer). The status code is lost; the body's `error` member is the only sign. * - An error answer WITHOUT a body fails the query: a conditional read whose ETag still matches is `304` and the query fails with `status: 304`. * - `docGet` cannot run without an `If-None-Match` header: the bundled document marks it required (the server treats it as optional: a read - * without it answers the document), and the plugin refuses the query with its own message (NSD-16 candidate). A value that is not the + * without it answers the document), and the plugin refuses the query with its own message (D-81 candidate). A value that is not the * current ETag (`e2e-no-match` here) reads the document; the current ETag is a 304. * - The plugin sends the Basic credentials of the data source (the admin of the sidecar); `_all_dbs` of a fresh node lists the three system * databases the run script creates, plus every database of the tests running at that time, so the exact lists below are scoped by a key range. @@ -38,9 +38,9 @@ import { expect, test } from "../../src/fixtures"; * rest of the document's operations (the query form offers them; these tests run the ones named below). */ /** Candidate defect: an HTTP error answer that carries a body is returned as the query's data with `success: true`. */ -const ERROR_BODY_DEFECT = { type: "defect", description: "NSD-4 candidate" } as const; +const ERROR_BODY_DEFECT = { type: "defect", description: "D-69 candidate" } as const; /** Candidate defect: the bundled document marks the `If-None-Match` header of `docGet` required, so the query cannot run without it, and a matching ETag (304) fails it. */ -const IF_NONE_MATCH_DEFECT = { type: "defect", description: "NSD-16 candidate" } as const; +const IF_NONE_MATCH_DEFECT = { type: "defect", description: "D-81 candidate" } as const; const HTTP_OK = 200; const HTTP_CREATED = 201; @@ -89,7 +89,7 @@ const SERVER_ERRORS = { const MISSING_HEADER_MESSAGE = "Required parameter If-None-Match is not provided"; const NOT_MODIFIED_MESSAGE = "status: 304"; -/** A header value that is not the current ETag of any document: the workaround that lets `docGet` run (NSD-16 candidate). */ +/** A header value that is not the current ETag of any document: the workaround that lets `docGet` run (D-81 candidate). */ const NO_MATCH_ETAG = "e2e-no-match"; /** The revision a first write answers (`1-` and the md5 of the body, 32 hex digits), and the one of an update or a delete. */ @@ -424,7 +424,7 @@ test.describe("CouchDB data source against a real CouchDB server", { tag: [TAGS. "the server's answers to the refused calls", ).toEqual(Array.from({ length: 4 }, () => ({ status: HTTP_CONFLICT, body: SERVER_ERRORS.CONFLICT }))); - // NSD-4 candidate: the plugin reports the 409 body as the data of a successful query + // D-69 candidate: the plugin reports the 409 body as the data of a successful query for (const query of ["staleWrite", "noRevisionWrite", "staleDelete", "staleIfMatchDelete"]) { expect(await runForData(page, appId, query), `${query}: the error body is the data`).toEqual(SERVER_ERRORS.CONFLICT); } @@ -486,7 +486,7 @@ test.describe("CouchDB data source against a real CouchDB server", { tag: [TAGS. ]); expect(await runForData(page, appId, "readPresent"), "positive control: the document that exists is read").toEqual({ _id: "present", _rev: expect.stringMatching(FIRST_REVISION), here: true }); - // NSD-4 candidate: each error body is the data of a successful query + // D-69 candidate: each error body is the data of a successful query expect(await runForData(page, appId, "readMissingDoc"), "a missing document").toEqual(SERVER_ERRORS.DOCUMENT_MISSING); expect(await runForData(page, appId, "readMissingDb"), "a document of a missing database").toEqual(SERVER_ERRORS.DATABASE_MISSING); expect(await runForData(page, appId, "infoMissingDb"), "the information of a missing database").toEqual(SERVER_ERRORS.DATABASE_MISSING); @@ -534,7 +534,7 @@ test.describe("CouchDB data source against a real CouchDB server", { tag: [TAGS. ]); expect((await couchdbDirect(sidecar, "GET", "/_all_dbs", { credentials: account })).status, "positive control: the account's own password is accepted by the server").toBe(HTTP_OK); - // NSD-4 candidate: the wrong password's 401 body is the data of a successful query + // D-69 candidate: the wrong password's 401 body is the data of a successful query expect(await runForData(page, wrongApp, "list"), "the listing with the wrong password").toEqual(SERVER_ERRORS.BAD_PASSWORD); expect(await runForData(page, wrongApp, "create"), "the create with the wrong password").toEqual(SERVER_ERRORS.BAD_PASSWORD); expect((await admin("GET", `/${db}`)).status, "the refused create made no database").toBe(HTTP_NOT_FOUND); @@ -561,7 +561,7 @@ test.describe("CouchDB data source against a real CouchDB server", { tag: [TAGS. expect(rightBefore, "before the failures the account's right password lists the databases").toEqual(expect.arrayContaining([...COUCHDB.SYSTEM_DATABASES])); const attempts: unknown[] = []; for (let attempt = 0; attempt < LOCKOUT_FAILURES + 1; attempt++) attempts.push(await runForData(page, wrongApp, "list")); - // NSD-4 candidate: every refusal is the data of a successful query; the sixth is the lockout's 403 body + // D-69 candidate: every refusal is the data of a successful query; the sixth is the lockout's 403 body expect(attempts, "five wrong passwords are 401 bodies, the next one is the lockout's body").toEqual([ ...Array.from({ length: LOCKOUT_FAILURES }, () => SERVER_ERRORS.BAD_PASSWORD), SERVER_ERRORS.ACCOUNT_LOCKED, @@ -602,7 +602,7 @@ test.describe("CouchDB data source against a real CouchDB server", { tag: [TAGS. const matchingDirect = await admin("GET", `/${db}/${docid}`, { headers: { "If-None-Match": `"${revision}"` } }); expect(matchingDirect.status, "the server answers 304 to the current ETag").toBe(HTTP_NOT_MODIFIED); - // NSD-16 candidate + // D-81 candidate expectFailed(await runDraft(page, appId, "withoutHeader"), MISSING_HEADER_MESSAGE); expect(await runForData(page, appId, "withHeader"), "positive control: with a header of any other value the document is read").toEqual({ _id: docid, _rev: revision, n: 1 }); expectFailed(await runDraft(page, appId, "matching"), NOT_MODIFIED_MESSAGE); diff --git a/e2e/tests/datasource/plugin-duckdb.spec.ts b/e2e/tests/datasource/plugin-duckdb.spec.ts index 55a30b9883..38778b1259 100644 --- a/e2e/tests/datasource/plugin-duckdb.spec.ts +++ b/e2e/tests/datasource/plugin-duckdb.spec.ts @@ -22,7 +22,7 @@ import { expect, test } from "../../src/fixtures"; */ /** Candidate defect: rows are keyed by the column's position, so `SELECT 42 AS answer` cannot be read as `row.answer` in an app. */ -const COLUMN_KEY_DEFECT = { type: "defect", description: "NSD-3 candidate" } as const; +const COLUMN_KEY_DEFECT = { type: "defect", description: "D-68 candidate" } as const; const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; const COLUMN_KEY_DETAILS = { annotation: COLUMN_KEY_DEFECT }; @@ -96,14 +96,14 @@ test.describe("DuckDB data source", NODE_SERVICE_DETAILS, () => { expect({ status: answer.status, code: answer.code }, "the query ran").toEqual({ status: HTTP_OK, code: API_OK }); expect(envelopeOf(answer).success, "the query succeeded").toBe(true); expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); - // An INTEGER column reaches the app as a JSON number; the keys are the column positions (NSD-3 candidate, see the file comment). + // An INTEGER column reaches the app as a JSON number; the keys are the column positions (D-68 candidate, see the file comment). expect(envelopeOf(answer).data, "the rows, keyed by column position").toEqual([{ [FIRST_COLUMN]: 42, [SECOND_COLUMN]: `e2e-${marker}` }]); }); test("D4b: the published view shows the DuckDB result after a click", COLUMN_KEY_DETAILS, async ({ page, apiUser }) => { const marker = uniqueMarker(); const datasourceId = await duckdbDatasource(page, apiUser); - // The text reads the second column by its position key (NSD-3 candidate); before the first run `q.data` is not a list. + // The text reads the second column by its position key (D-68 candidate); before the first run `q.data` is not a list. const expression = `{{${QUERY_NAME}.data ? ${QUERY_NAME}.data[0]["${SECOND_COLUMN}"] : ""}}`; const view = await openSeededView( page, @@ -139,7 +139,7 @@ test.describe("DuckDB data source", NODE_SERVICE_DETAILS, () => { expect({ status: answer.status, code: answer.code }, "the query ran").toEqual({ status: HTTP_OK, code: API_OK }); expect(envelopeOf(answer).success, "the query succeeded").toBe(true); expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_OK); - // `serializeBigInts` turns a `bigint` into a string (designed behaviour), a HUGEINT included (measured); the keys are the column positions (NSD-3 candidate). + // `serializeBigInts` turns a `bigint` into a string (designed behaviour), a HUGEINT included (measured); the keys are the column positions (D-68 candidate). expect(envelopeOf(answer).data, "the BIGINT and the HUGEINT as exact strings").toEqual([{ [FIRST_COLUMN]: BIGINT_VALUE, [SECOND_COLUMN]: HUGEINT_VALUE }]); }); diff --git a/e2e/tests/datasource/plugin-dynamodb-local.spec.ts b/e2e/tests/datasource/plugin-dynamodb-local.spec.ts index 1afef294ab..6979572a37 100644 --- a/e2e/tests/datasource/plugin-dynamodb-local.spec.ts +++ b/e2e/tests/datasource/plugin-dynamodb-local.spec.ts @@ -38,13 +38,13 @@ import { expect, test } from "../../src/fixtures"; * indexes, transactions, batch operations, streams, TTL, and the signature (the server does not verify it; D10a to D10f assert the signed request). */ /** Candidate defect: the answer of `ReturnValues` (`Attributes`) and `LastEvaluatedKey` stay in the typed form while `Item` and `Items` are unwrapped. */ -const TYPED_ANSWER_DEFECT = { type: "defect", description: "NSD-17 candidate" } as const; +const TYPED_ANSWER_DEFECT = { type: "defect", description: "D-82 candidate" } as const; /** Candidate defect: an array of strings or numbers is always written as a set (SS or NS): never a list, duplicates and an empty array are refused. */ -const ARRAY_SETS_DEFECT = { type: "defect", description: "NSD-18 candidate" } as const; +const ARRAY_SETS_DEFECT = { type: "defect", description: "D-83 candidate" } as const; /** Candidate defect: a binary attribute is read as a byte array, which the answer's JSON turns into an object with index keys; a number beyond a double loses digits. */ -const VALUE_FIDELITY_DEFECT = { type: "defect", description: "NSD-19 candidate" } as const; +const VALUE_FIDELITY_DEFECT = { type: "defect", description: "D-84 candidate" } as const; /** Candidate defect: an `ExclusiveStartKey` in the plain form (as `Key` is written) fails with a JavaScript `TypeError` of the SDK instead of a validation message. */ -const PLAIN_START_KEY_DEFECT = { type: "defect", description: "NSD-20 candidate" } as const; +const PLAIN_START_KEY_DEFECT = { type: "defect", description: "D-85 candidate" } as const; const HTTP_OK = 200; const HTTP_BAD_REQUEST = 400; @@ -480,7 +480,7 @@ test.describe("DynamoDB data source against a real DynamoDB Local server", { tag expect(await runForData(page, appId, "update"), "an update answers an empty object").toEqual({}); expect(await runForData(page, appId, "get"), "the item as the plugin reads it after the update").toEqual({ Item: { id: 1, name: "Alice", age: 18, tags: ["x", "y"] } }); expect(await directItem(table, { id: { N: "1" } }), "the server's own copy").toEqual({ id: { N: "1" }, name: { S: "Alice" }, age: { N: "18" }, tags: { SS: ["x", "y"] } }); - // NSD-17 candidate: Attributes of ReturnValues stays typed while Item is unwrapped + // D-82 candidate: Attributes of ReturnValues stays typed while Item is unwrapped expect(await runForData(page, appId, "updateNew"), "ALL_NEW: the attributes are NOT unwrapped").toEqual({ Attributes: { id: { N: "1" }, name: { S: "Alice" }, age: { N: "19" }, tags: { SS: ["x", "y"] } }, }); @@ -516,7 +516,7 @@ test.describe("DynamoDB data source against a real DynamoDB Local server", { tag expect(await directItem(table, { id: { N: "1" } }), "before the delete the server holds the item").toEqual({ id: { N: "1" }, name: { S: "item-1" } }); expect(await runForData(page, appId, "remove"), "a delete answers an empty object").toEqual({}); expect(await directItem(table, { id: { N: "1" } }), "the server no longer holds the item").toBeUndefined(); - // NSD-17 candidate: Attributes of ReturnValues stays typed + // D-82 candidate: Attributes of ReturnValues stays typed expect(await runForData(page, appId, "removeOld"), "ALL_OLD: the deleted item's attributes, NOT unwrapped").toEqual({ Attributes: { id: { N: "2" }, name: { S: "item-2" } } }); expect(await directItem(table, { id: { N: "2" } }), "the item with ALL_OLD is gone too").toBeUndefined(); expect(await runForData(page, appId, "removeAbsent"), "an item that was never there: success, and the server reports the capacity it used (the delete of an existing item above reports none)").toEqual({ diff --git a/e2e/tests/datasource/plugin-firebird.spec.ts b/e2e/tests/datasource/plugin-firebird.spec.ts index e06beba96e..2b630b3ce5 100644 --- a/e2e/tests/datasource/plugin-firebird.spec.ts +++ b/e2e/tests/datasource/plugin-firebird.spec.ts @@ -39,7 +39,7 @@ import { expect, test } from "../../src/fixtures"; * Candidate defect: a query that fails after the attach (a SQL error or an unknown named parameter) never detaches (`run.ts`: `detachAsync` * comes after the awaited query and is skipped when it throws), so the attachment stays open on the server. A successful query does detach. */ -const LEAKED_ATTACHMENT_DEFECT = { type: "defect", description: "NSD-13 candidate" } as const; +const LEAKED_ATTACHMENT_DEFECT = { type: "defect", description: "D-78 candidate" } as const; const HTTP_OK = 200; const CODE_CONNECT_FAILED = 500; diff --git a/e2e/tests/datasource/plugin-graphql.spec.ts b/e2e/tests/datasource/plugin-graphql.spec.ts index 99b0340d57..65487b007d 100644 --- a/e2e/tests/datasource/plugin-graphql.spec.ts +++ b/e2e/tests/datasource/plugin-graphql.spec.ts @@ -15,12 +15,12 @@ import { recordsContain, type EchoRecord, type EchoTarget } from "../../src/secu * path of the canned answer into the app. They are NOT a fidelity test of GitLab or Shopify. * * Shopify: the plugin reads the query's headers and passes none on, and its data source has no token field, so it cannot send - * Shopify's access token (D6d, NSD-2 candidate). + * Shopify's access token (D6d, D-67 candidate). */ const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; /** Candidate defect: the Shopify plugin drops every header of the query and has no access token field. */ -const SHOPIFY_HEADERS_DEFECT = { type: "defect", description: "NSD-2 candidate" } as const; +const SHOPIFY_HEADERS_DEFECT = { type: "defect", description: "D-67 candidate" } as const; const SHOPIFY_HEADERS_DETAILS = { annotation: SHOPIFY_HEADERS_DEFECT }; /** The path below the target that the endpoint points at. */ @@ -226,7 +226,7 @@ test.describe("Shopify data source against the echo", NODE_SERVICE_DETAILS, () = const shopifyRecords = await echo.received(); const record = onlyRecord(shopifyRecords); expect(JSON.parse(record.body), "the request body is the query").toEqual({ query: SHOPIFY_QUERY, variables: {} }); - // The plugin reads the query's headers and passes `{}` on (NSD-2 candidate, see SHOPIFY_HEADERS_DEFECT): neither the header name nor its value arrives. + // The plugin reads the query's headers and passes `{}` on (D-67 candidate, see SHOPIFY_HEADERS_DEFECT): neither the header name nor its value arrives. expect(recordsContain(shopifyRecords, marker), "the header value reached the endpoint").toBe(false); expect(Object.keys(record.headers).map((name) => name.toLowerCase()), "the header name reached the endpoint").not.toContain(SHOPIFY_TOKEN_HEADER.toLowerCase()); diff --git a/e2e/tests/datasource/plugin-openapi-wrappers-apps.spec.ts b/e2e/tests/datasource/plugin-openapi-wrappers-apps.spec.ts index c57b83725f..d26f508df5 100644 --- a/e2e/tests/datasource/plugin-openapi-wrappers-apps.spec.ts +++ b/e2e/tests/datasource/plugin-openapi-wrappers-apps.spec.ts @@ -30,14 +30,14 @@ import type { EchoRecord, EchoTarget } from "../../src/security/echo"; const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; /** Candidate defect: an error status answer with a body is returned as the query's successful result (the generic plugin's D7d shows the same). */ -const ERROR_STATUS_SUCCESS_DEFECT = { type: "defect", description: "NSD-4 candidate" } as const; +const ERROR_STATUS_SUCCESS_DEFECT = { type: "defect", description: "D-69 candidate" } as const; const ERROR_STATUS_DETAILS = { annotation: ERROR_STATUS_SUCCESS_DEFECT }; /** * Candidate defect: the UiPath plugin cannot run: `getSchemaExample` (`plugins/openApi/util.ts`) recurses without end on a circular schema of * the bundled document, so its query configuration (what the editor lists) and every query fail with `Maximum call stack size exceeded`. */ -const UIPATH_DEFECT = { type: "defect", description: "NSD-6 candidate" } as const; +const UIPATH_DEFECT = { type: "defect", description: "D-71 candidate" } as const; const UIPATH_DETAILS = { annotation: UIPATH_DEFECT }; /** The desired behaviour of the UiPath plugin: it fails today, so it is quarantined (the enclosing describe adds `@node-service`). */ const UIPATH_QUARANTINE_DETAILS = { tag: [TAGS.QUARANTINE], annotation: UIPATH_DEFECT }; @@ -46,7 +46,7 @@ const UIPATH_QUARANTINE_DETAILS = { tag: [TAGS.QUARANTINE], annotation: UIPATH_D * Candidate defect: an OpenAI data source on the spec version `v1.0` (the default when none is chosen) sends no `Authorization` header: the * plugin hands the key over as `ApiKeyAuth.value`, the scheme of the `v2.3` document, while the `v1.0` document names its scheme `ApiKey`. */ -const OPENAI_V1_AUTH_DEFECT = { type: "defect", description: "NSD-7 candidate" } as const; +const OPENAI_V1_AUTH_DEFECT = { type: "defect", description: "D-72 candidate" } as const; const OPENAI_V1_AUTH_DETAILS = { annotation: OPENAI_V1_AUTH_DEFECT }; /** Observation: a Carbone data source sends its token only with the operations whose document entry lists the `bearerAuth` scheme; `get_status` does not. */ @@ -363,7 +363,7 @@ test.describe("OpenAI", NODE_SERVICE_DETAILS, () => { expect(records, "one request per data source").toHaveLength(sides.length); // control: with the same key on the same server the v2.3 document sends it, so the missing header below is the plugin's, not the echo's expectRequest(onlyRecord(recordsUnder(records, echo, "/v2"), "v2.3 sent one request"), echo, { path: `${echo.path}/v2/models`, headers: { authorization: `Bearer ${key}` } }, "v2.3"); - // Measured on the images `3.0.0-e2e` and `3.0.1-e2e`: the v1.0 document names its scheme `ApiKey`, the plugin hands the key over as `ApiKeyAuth.value`, so no header is sent (NSD-7 candidate, see OPENAI_V1_AUTH_DEFECT). + // Measured on the images `3.0.0-e2e` and `3.0.1-e2e`: the v1.0 document names its scheme `ApiKey`, the plugin hands the key over as `ApiKeyAuth.value`, so no header is sent (D-72 candidate, see OPENAI_V1_AUTH_DEFECT). expectRequest(onlyRecord(recordsUnder(records, echo, "/default"), "the default version sent one request"), echo, { path: `${echo.path}/default/models` }, "default version"); expectRequest(onlyRecord(recordsUnder(records, echo, "/v1"), "v1.0 sent one request"), echo, { path: `${echo.path}/v1/models` }, "v1.0"); expect(JSON.stringify([records[0], records[1]]).includes(key), "the key is on no part of the v1.0 and default requests").toBe(false); @@ -386,7 +386,7 @@ test.describe("an error answer", NODE_SERVICE_DETAILS, () => { const record = onlyRecord(await echo.received(), "the request reached the echo"); expectRequest(record, echo, { path: `${echo.path}${requestPathOf(row, marker, "")}`, headers: auth.headers }, row.plugin); expectRan(answer); - // Measured on the images `3.0.0-e2e` and `3.0.1-e2e`: `runOpenApi` returns the body of an error answer as the result (NSD-4 candidate, see ERROR_STATUS_SUCCESS_DEFECT), so the 404 is reported as a successful query. + // Measured on the images `3.0.0-e2e` and `3.0.1-e2e`: `runOpenApi` returns the body of an error answer as the result (D-69 candidate, see ERROR_STATUS_SUCCESS_DEFECT), so the 404 is reported as a successful query. expect(envelopeOf(answer).success, "the 404 is reported as success").toBe(true); expect(envelopeOf(answer).queryCode, "the query code of the 404").toBe(QUERY_CODE_OK); expect(envelopeOf(answer).data, "the result is the error body").toEqual(body); @@ -414,7 +414,7 @@ test.describe("UiPath", NODE_SERVICE_DETAILS, () => { const answer = await runDraft(page, appId); expectRan(answer); - // Measured on the images `3.0.0-e2e` and `3.0.1-e2e` (NSD-6 candidate, see UIPATH_DEFECT). + // Measured on the images `3.0.0-e2e` and `3.0.1-e2e` (D-71 candidate, see UIPATH_DEFECT). expect(envelopeOf(answer).success, "the query failed").toBe(false); expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_FAILED); expect(envelopeOf(answer).message, "node-service's message").toBe(UIPATH_FAILURE_MESSAGE); @@ -430,7 +430,7 @@ test.describe("UiPath", NODE_SERVICE_DETAILS, () => { const answer = await pluginDynamicConfigRaw(page.request, [{ pluginName: "uiPath", path: QUERY_CONFIG_PATH, dataSourceConfig }]); - // Measured on the images `3.0.0-e2e` and `3.0.1-e2e` (NSD-6 candidate, see UIPATH_DEFECT): the request for the UiPath document fails, so the editor + // Measured on the images `3.0.0-e2e` and `3.0.1-e2e` (D-71 candidate, see UIPATH_DEFECT): the request for the UiPath document fails, so the editor // cannot list a single operation. The test asserts the failure of this request and, below, that the same request shape succeeds for another // plugin; the cause (a `RangeError: Maximum call stack size exceeded` in `getSchemaExample`) was seen in node-service's log while recording, the suite cannot read that log. expect(answer.status, "the HTTP status").toBe(HTTP_SERVER_ERROR); diff --git a/e2e/tests/datasource/plugin-openapi-wrappers-data.spec.ts b/e2e/tests/datasource/plugin-openapi-wrappers-data.spec.ts index bac38021e8..331c893b8a 100644 --- a/e2e/tests/datasource/plugin-openapi-wrappers-data.spec.ts +++ b/e2e/tests/datasource/plugin-openapi-wrappers-data.spec.ts @@ -42,7 +42,7 @@ const COUCHDB_AUTH_DETAILS = { annotation: COUCHDB_AUTH_OBSERVATION }; * Candidate defect: a WooCommerce server URL that already ends in `/wp-json/wc/v3/` (with the trailing slash) is not recognised by * `prepareServerUrl`, which then appends `wp-json/wc/v3` a second time. */ -const WOO_TRAILING_SLASH_DEFECT = { type: "defect", description: "NSD-5 candidate" } as const; +const WOO_TRAILING_SLASH_DEFECT = { type: "defect", description: "D-70 candidate" } as const; const WOO_TRAILING_SLASH_DETAILS = { annotation: WOO_TRAILING_SLASH_DEFECT }; const HTTP_OK = 200; @@ -369,7 +369,7 @@ test.describe("WooCommerce server URL", NODE_SERVICE_DETAILS, () => { expectSucceeded(answer); const record = onlyRecord(await echo.received(), "the request reached the echo"); // Measured on the images `3.0.0-e2e` and `3.0.1-e2e`: `prepareServerUrl` recognises `/wc/v3` only at the very end of the URL, so - // the trailing slash makes it append `wp-json/wc/v3` again (NSD-5 candidate, see WOO_TRAILING_SLASH_DEFECT). + // the trailing slash makes it append `wp-json/wc/v3` again (D-70 candidate, see WOO_TRAILING_SLASH_DEFECT). expectRequest(record, echo, { path: `${echo.path}${doubled}/products?${WOO_QUERY}`, basic: auth.basic }, "doubled API path"); expect(envelopeOf(answer).data, "the canned answer of the doubled path").toEqual(body); }); diff --git a/e2e/tests/datasource/plugin-openapi.spec.ts b/e2e/tests/datasource/plugin-openapi.spec.ts index b40990b9bd..79ed94643b 100644 --- a/e2e/tests/datasource/plugin-openapi.spec.ts +++ b/e2e/tests/datasource/plugin-openapi.spec.ts @@ -30,7 +30,7 @@ import type { EchoRecord, EchoTarget } from "../../src/security/echo"; const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; /** Candidate defect: an error status answer with a body is returned as the query's successful result. */ -const ERROR_STATUS_SUCCESS_DEFECT = { type: "defect", description: "NSD-4 candidate" } as const; +const ERROR_STATUS_SUCCESS_DEFECT = { type: "defect", description: "D-69 candidate" } as const; const ERROR_STATUS_DETAILS = { annotation: ERROR_STATUS_SUCCESS_DEFECT }; /** @@ -207,7 +207,7 @@ test.describe("generic openApi data source against the echo", NODE_SERVICE_DETAI const record = onlyRecord(await echo.received()); expect(record.path, "the operation's request reached the echo").toBe(`${echo.path}${ITEMS_PATH}?q=${marker}`); expectRan(answer); - // Measured on the images `3.0.0-e2e` and `3.0.1-e2e`: `runOpenApi` returns the body of an error answer as the result (NSD-4 + // Measured on the images `3.0.0-e2e` and `3.0.1-e2e`: `runOpenApi` returns the body of an error answer as the result (D-69 // candidate, see ERROR_STATUS_SUCCESS_DEFECT), so the 404 is reported as a successful query. expect(envelopeOf(answer).success, "the 404 is reported as success").toBe(true); expect(envelopeOf(answer).queryCode, "the query code of the 404").toBe(QUERY_CODE_OK); diff --git a/e2e/tests/datasource/plugin-s3-server.spec.ts b/e2e/tests/datasource/plugin-s3-server.spec.ts index d2510c0a91..90ee718614 100644 --- a/e2e/tests/datasource/plugin-s3-server.spec.ts +++ b/e2e/tests/datasource/plugin-s3-server.spec.ts @@ -26,7 +26,7 @@ import { DatasourcePage } from "../../src/pages/DatasourcePage"; * Measured on the images `3.0.0-e2e` and `3.0.1-e2e` against versitygw v1.11.0 (the AWS SDK of the plugin is the one D10 measures, version 3.668.0 in its user agent): * - Every answer of the plugin is `success: true, queryCode: "OK"` with the data below, or `success: false, queryCode: "FAILED"` with the server's own message and no data. * - `listBuckets`: `[{ name }]`. `listObjects`: `[{ name, size, lastModified, signedUrl, url }]`: it sends ListObjects (version 1) with the prefix, the delimiter and `limit` as - * max-keys and nothing else, so the keys that a delimiter folds into prefixes are dropped (NSD-22) and a truncated listing cannot be continued (NSD-21). + * max-keys and nothing else, so the keys that a delimiter folds into prefixes are dropped (D-87) and a truncated listing cannot be continued (D-86). * - `readFile`: `{ contentType, length, lastModified, data }` (the echo scenarios saw neither `length` nor `lastModified`: its canned answers carry no such headers). * - `uploadData`: `{ fileName, signedUrl, url }`; `deleteFile`: `{ success: true }` for a key that exists and for one that does not. * - A service error fails the query with the server's message: `NoSuchBucket`, `NoSuchKey`, `InvalidAccessKeyId`, `SignatureDoesNotMatch`. @@ -36,13 +36,13 @@ import { DatasourcePage } from "../../src/pages/DatasourcePage"; * (it lives 300 s), and a presigned URL fetched from inside the app container (hand-measured, README). */ /** Candidate defect: `listObjects` has no continuation: it sends no marker and returns neither `IsTruncated` nor a next marker, so a bucket with more keys than `limit` silently shows its first page. */ -const NO_CONTINUATION_DEFECT = { type: "defect", description: "NSD-21 candidate" } as const; +const NO_CONTINUATION_DEFECT = { type: "defect", description: "D-86 candidate" } as const; /** Candidate defect: `listObjects` with a delimiter returns only `Contents`: the common prefixes ("folders") the server answers are dropped. */ -const COMMON_PREFIXES_DEFECT = { type: "defect", description: "NSD-22 candidate" } as const; +const COMMON_PREFIXES_DEFECT = { type: "defect", description: "D-87 candidate" } as const; /** Candidate defect: the `url` of `listObjects` and `uploadData` is the endpoint, the bucket and the key joined as they are: a key with `?`, `#` or `%` names another resource, and a space or non-ASCII text is not a valid URL until a client encodes it. */ -const UNENCODED_URL_DEFECT = { type: "defect", description: "NSD-24 candidate" } as const; +const UNENCODED_URL_DEFECT = { type: "defect", description: "D-89 candidate" } as const; /** Candidate defect: `uploadData` decodes the data as base64 by default and Node's decoder accepts text that is not base64, so plain text typed into the form is stored as other bytes without a message. */ -const LENIENT_BASE64_DEFECT = { type: "defect", description: "NSD-23 candidate" } as const; +const LENIENT_BASE64_DEFECT = { type: "defect", description: "D-88 candidate" } as const; const HTTP_OK = 200; const HTTP_FORBIDDEN = 403; @@ -80,10 +80,10 @@ const SERVER_MESSAGES = { SIGNATURE_MISMATCH: "The request signature we calculated does not match the signature you provided. Check your key and signing method.", } as const; -/** What the plugin answers for an empty bucket name: `listObjects` checks it itself, the other actions hand the SDK's own text to the user (NSD-8 candidate, as in D10). */ +/** What the plugin answers for an empty bucket name: `listObjects` checks it itself, the other actions hand the SDK's own text to the user (D-73 candidate, as in D10). */ const BUCKET_REQUIRED_MESSAGE = "Bucket is required"; const SDK_EMPTY_BUCKET_MESSAGE = "Empty value provided for input HTTP label: Bucket."; -const BUCKET_CHECK_DEFECT = { type: "defect", description: "NSD-8 candidate" } as const; +const BUCKET_CHECK_DEFECT = { type: "defect", description: "D-73 candidate" } as const; /** The shapes of values the server generates. */ const ISO_DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; @@ -603,7 +603,7 @@ test.describe("S3 data source against a real S3-compatible server", { tag: [TAGS listReal: listObjects(bucket), }); - // the one operation that checks the bucket itself; NSD-8 candidate: the others hand the SDK's own text to the user (measured) + // the one operation that checks the bucket itself; D-73 candidate: the others hand the SDK's own text to the user (measured) expectFailed(await runDraft(page, appId, "listEmpty"), BUCKET_REQUIRED_MESSAGE); expectFailed(await runDraft(page, appId, "readEmpty"), SDK_EMPTY_BUCKET_MESSAGE); expectFailed(await runDraft(page, appId, "uploadEmpty"), SDK_EMPTY_BUCKET_MESSAGE); diff --git a/e2e/tests/datasource/plugin-supabase-storage.spec.ts b/e2e/tests/datasource/plugin-supabase-storage.spec.ts index 0f2cca5e43..ba0f735f09 100644 --- a/e2e/tests/datasource/plugin-supabase-storage.spec.ts +++ b/e2e/tests/datasource/plugin-supabase-storage.spec.ts @@ -31,16 +31,16 @@ const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; * `Response`, not with the message of the answer: storage-js recognises an HTTP error only as an instance of the global `Response`, and * the proxy fetch answers with node-fetch's class. */ -const ERROR_TEXT_DEFECT = { type: "defect", description: "NSD-9 candidate" } as const; +const ERROR_TEXT_DEFECT = { type: "defect", description: "D-74 candidate" } as const; /** * Candidate defect: the signed-URL validity the plugin sends as `expiresIn` is `Date.now() + 5 minutes` in milliseconds (a 13-digit number * of the order of 1.8e12), computed once when node-service loads the plugin, while the API takes seconds. */ -const EXPIRY_DEFECT = { type: "defect", description: "NSD-10 candidate" } as const; +const EXPIRY_DEFECT = { type: "defect", description: "D-75 candidate" } as const; /** Candidate defect: the `search` field of listObjects is read by the query form and never sent. */ -const SEARCH_DEFECT = { type: "defect", description: "NSD-11 candidate" } as const; +const SEARCH_DEFECT = { type: "defect", description: "D-76 candidate" } as const; /** Candidate defect: only listObjects checks the bucket (`Bucket is required`); the other operations send a request for an empty bucket name. */ -const EMPTY_BUCKET_DEFECT = { type: "defect", description: "NSD-12 candidate" } as const; +const EMPTY_BUCKET_DEFECT = { type: "defect", description: "D-77 candidate" } as const; /** Observation: an upload without a content type sends an empty `content-type` header (the editor's default is an empty text). */ const EMPTY_CONTENT_TYPE_OBSERVATION = { type: "observation", description: "an upload without a content type sends an empty content-type header" } as const; @@ -78,7 +78,7 @@ const SHAPE_BAD = ""; const UPLOAD_CACHE_CONTROL = "max-age=3600"; const UPLOAD_UPSERT = "false"; -/** The message of every failed storage call today: the JSON of node-fetch's `Response` (NSD-9). */ +/** The message of every failed storage call today: the JSON of node-fetch's `Response` (D-74). */ const LOST_ERROR_TEXT = '{"size":0,"timeout":0}'; const CANNED_ERROR_MESSAGE = "e2e-storage-error"; const BUCKET_REQUIRED = "Bucket is required"; @@ -205,7 +205,7 @@ function expectKeyOnlyInItsHeaders(records: EchoRecord[], key: string, answers: for (const answer of answers) expect(JSON.stringify(answer.json).includes(key), `${label}: the key is in no answer of the query`).toBe(false); } -/** Asserts a signed-URL body's `expiresIn` (NSD-10) and returns it; the rest of the body is asserted by the caller. */ +/** Asserts a signed-URL body's `expiresIn` (D-75) and returns it; the rest of the body is asserted by the caller. */ function expiresInOf(record: EchoRecord, label: string): number { const value = (JSON.parse(record.body) as { expiresIn?: unknown }).expiresIn; expect(typeof value === "number" && Number.isInteger(value), `${label}: expiresIn is an integer number`).toBe(true); @@ -344,7 +344,7 @@ test.describe("Supabase Storage data source against the echo", NODE_SERVICE_DETA expectSucceeded(answer); const records = await echo.received(); - // NSD-11 candidate: the body is exactly the one of a query with no search, the other fields travel (positive control inside the same body) + // D-76 candidate: the body is exactly the one of a query with no search, the other fields travel (positive control inside the same body) expectStorageRequest( onlyRecord(records), echo, @@ -369,7 +369,7 @@ test.describe("Supabase Storage data source against the echo", NODE_SERVICE_DETA const records = await echo.received(); expect(records, "the echo holds the listing and the signing").toHaveLength(2); expectStorageRequest(records[0] as EchoRecord, echo, { method: "POST", path: `/object/list/${BUCKET}`, key, json: { limit: 10, offset: 0, sortBy: { column: "name", order: "asc" }, prefix: PREFIX } }, "the listing"); - // NSD-10 candidate: an epoch time in milliseconds where the API takes seconds + // D-75 candidate: an epoch time in milliseconds where the API takes seconds const expiresIn = expiresInOf(records[1] as EchoRecord, "the signing"); expectStorageRequest(records[1] as EchoRecord, echo, { method: "POST", path: `/object/sign/${BUCKET}`, key, json: { expiresIn, paths: [`${PREFIX}/${FILE}`] } }, "the signing"); expectKeyOnlyInItsHeaders(records, key, [answer], "listObjects with signed URLs"); @@ -504,7 +504,7 @@ test.describe("Supabase Storage data source against the echo", NODE_SERVICE_DETA expectSucceeded(answer); const records = await echo.received(); const firstRecord = onlyRecord(records); - // NSD-10 candidate: the value is an epoch time in milliseconds, not a number of seconds + // D-75 candidate: the value is an epoch time in milliseconds, not a number of seconds const expiresIn = expiresInOf(firstRecord, "the first signing"); expectStorageRequest(firstRecord, echo, { method: "POST", path: `/object/sign/${BUCKET}/${FILE}`, key, json: { expiresIn } }, "createSignedUrl"); expectKeyOnlyInItsHeaders(records, key, [answer], "createSignedUrl"); @@ -563,7 +563,7 @@ test.describe("Supabase Storage data source against the echo", NODE_SERVICE_DETA const failed = await runDraft(page, appId); - // NSD-9 candidate: the message of the answer is lost, node-fetch's Response is printed instead + // D-74 candidate: the message of the answer is lost, node-fetch's Response is printed instead expectFailed(failed, LOST_ERROR_TEXT); const afterFailure = await echo.received(); expectStorageRequest(onlyRecord(afterFailure), echo, { ...row.request, key }, `the failing ${row.title}`); @@ -627,7 +627,7 @@ test.describe("Supabase Storage data source against the echo", NODE_SERVICE_DETA expectFailed(refused, BUCKET_REQUIRED); expect(await echo.received(), "listObjects sent nothing").toEqual([]); - // NSD-12 candidate: the other four send a request whose path has an empty bucket segment + // D-77 candidate: the other four send a request whose path has an empty bucket segment const rows: Array<{ variant: string; action: Record; request: Omit }> = [ { variant: "ReadFile", action: { bucket: "", fileName: "x.txt", encoding: "utf8" }, request: { method: "GET", path: "/object//x.txt" } }, { diff --git a/e2e/tests/datasource/plugin-turso-libsql.spec.ts b/e2e/tests/datasource/plugin-turso-libsql.spec.ts index c460986ab8..cf867f71aa 100644 --- a/e2e/tests/datasource/plugin-turso-libsql.spec.ts +++ b/e2e/tests/datasource/plugin-turso-libsql.spec.ts @@ -26,9 +26,9 @@ import { expect, test } from "../../src/fixtures"; * `null` for an expression. * - The plugin makes an `integer` a number (a `boolean` column, written in lower case, a boolean), a `float` a number, a `datetime` or `date` * column's text a `Date` (an ISO string in the answer), a `null` `null`. A blob cell becomes a value of `undefined`, so the key is - * missing from the row (NSD-14 candidate). An integer beyond 2^53 is parsed with `parseInt` and loses its low digits (NSD-15 candidate). + * missing from the row (D-79 candidate). An integer beyond 2^53 is parsed with `parseInt` and loses its low digits (D-80 candidate). * - A SQL error is answered by the server with HTTP 200 and `results[0] = { type: "error", error: { message, code } }`; the plugin prints it - * as `[object Object]` (NSD-1 candidate, the defect D5d shows against a canned answer). + * as `[object Object]` (D-66 candidate, the defect D5d shows against a canned answer). * - A bad token is HTTP 401 `Unauthorized`; a read-only token that writes is HTTP 403 `Forbidden`; both fail the query with the plugin's * `Endpoint returned : .` * @@ -36,11 +36,11 @@ import { expect, test } from "../../src/fixtures"; * be exercised here); Turso's cloud features (branches, groups, per-database tokens); a stream with a baton (the plugin always closes). */ /** Candidate defect: an `error` result of the pipeline is printed as `${result.error}` (an object): the server's own message never reaches the app. */ -const ERROR_TEXT_DEFECT = { type: "defect", description: "NSD-1 candidate" } as const; +const ERROR_TEXT_DEFECT = { type: "defect", description: "D-66 candidate" } as const; /** Candidate defect: the cell of a `blob` has `base64` and no `value`, so the plugin answers the column as `undefined`: the key is missing from the row. */ -const BLOB_DEFECT = { type: "defect", description: "NSD-14 candidate" } as const; +const BLOB_DEFECT = { type: "defect", description: "D-79 candidate" } as const; /** Candidate defect: an `integer` cell is parsed with `Number.parseInt`, so an integer the JavaScript number cannot hold exactly is rounded. */ -const BIG_INTEGER_DEFECT = { type: "defect", description: "NSD-15 candidate" } as const; +const BIG_INTEGER_DEFECT = { type: "defect", description: "D-80 candidate" } as const; /** What the plugin prints for an `error` result (measured): the error object is printed as `[object Object]`. */ const MEASURED_ERROR_TEXT = "Cannot parse result, received error: [object Object]"; @@ -286,7 +286,7 @@ test.describe("Turso data source against a real libSQL server", { tag: [TAGS.NOD const rawData = envelopeOf(raw).data as { raw: { rows: unknown } }; expect(rawData.raw.rows, "the server's cells").toEqual([[{ type: "integer", value: "1" }, { type: "blob", base64: "AP8Q" }]]); expectSucceeded(values); - // NSD-14 candidate: the blob has no `value`, so the column is `undefined` and the key is missing + // D-79 candidate: the blob has no `value`, so the column is `undefined` and the key is missing expect(envelopeOf(values).data, "the row holds the id and not the blob").toEqual([{ id: 1 }]); }); @@ -303,7 +303,7 @@ test.describe("Turso data source against a real libSQL server", { tag: [TAGS.NOD const rawData = envelopeOf(raw).data as { raw: { rows: unknown } }; expect(rawData.raw.rows, "positive control: the server holds the exact integer, as a string").toEqual([[{ type: "integer", value: BEYOND_SAFE }]]); expectSucceeded(values); - // NSD-15 candidate: 9007199254740993 is not a JavaScript number; parseInt rounds it + // D-80 candidate: 9007199254740993 is not a JavaScript number; parseInt rounds it expect(envelopeOf(values).data, "the plugin's number").toEqual([{ big: BEYOND_SAFE_AS_PARSED }]); }); @@ -335,7 +335,7 @@ test.describe("Turso data source against a real libSQL server", { tag: [TAGS.NOD }); expectSucceeded(await runDraft(page, appId, "control")); - // NSD-1 candidate: whatever the server said, the app gets the same text + // D-66 candidate: whatever the server said, the app gets the same text for (const name of ["syntax", "column", "duplicate", "many"]) { expectFailed(await runDraft(page, appId, name), MEASURED_ERROR_TEXT); } diff --git a/e2e/tests/datasource/plugin-turso-slack.spec.ts b/e2e/tests/datasource/plugin-turso-slack.spec.ts index 418d5beafe..f684690dab 100644 --- a/e2e/tests/datasource/plugin-turso-slack.spec.ts +++ b/e2e/tests/datasource/plugin-turso-slack.spec.ts @@ -18,7 +18,7 @@ import type { EchoRecord, EchoTarget } from "../../src/security/echo"; const NODE_SERVICE_DETAILS = { tag: [TAGS.NODE_SERVICE] }; /** Candidate defect: an `error` result of the pipeline is printed as `${result.error}` (an object), so the server's own message never reaches the app. */ -const ERROR_TEXT_DEFECT = { type: "defect", description: "NSD-1 candidate" } as const; +const ERROR_TEXT_DEFECT = { type: "defect", description: "D-66 candidate" } as const; const ERROR_TEXT_DETAILS = { annotation: ERROR_TEXT_DEFECT }; /** The message of the canned error result. */ const ERROR_MESSAGE = "e2e-boom"; @@ -186,7 +186,7 @@ test.describe("Turso data source against the echo", NODE_SERVICE_DETAILS, () => expect(answer.status, "the request itself is answered").toBe(HTTP_OK); expect(envelopeOf(answer).success, "the query failed").toBe(false); expect(envelopeOf(answer).queryCode, "the query code").toBe(QUERY_CODE_FAILED); - // The plugin prints `result.error`, which is an object: the server's message is lost (NSD-1 candidate, see ERROR_TEXT_DEFECT). + // The plugin prints `result.error`, which is an object: the server's message is lost (D-66 candidate, see ERROR_TEXT_DEFECT). expect(envelopeOf(answer).message, "the measured message").toBe(MEASURED_ERROR_TEXT); expect((await echo.received()).length, "positive control: the request did reach the echo").toBe(1); });