diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 6a6290b51e..de8189953b 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -37,7 +37,7 @@ jobs: uses: actions/setup-java@v5 with: distribution: temurin - java-version: 17 + java-version: 25 - name: Initialize CodeQL uses: github/codeql-action/init@v4 diff --git a/.github/workflows/sonarcloud-build.yml b/.github/workflows/sonarcloud-build.yml index ac89ce9418..5e8d1adb08 100644 --- a/.github/workflows/sonarcloud-build.yml +++ b/.github/workflows/sonarcloud-build.yml @@ -31,7 +31,7 @@ jobs: uses: actions/setup-java@c1e323688fd81a25caa38c78aa6df2d33d3e20d9 # v4.8.0 with: distribution: zulu - java-version: "17" + java-version: "25" - name: Self-test sonar helper scripts run: python3 -I -m unittest discover -s .github/scripts/tests -v diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index 8c9d40976d..d1b8211918 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -1,7 +1,7 @@ ## ## Build Lowcoder api-service application ## -FROM maven:3.9-eclipse-temurin-17 AS build-api-service +FROM maven:3.9-eclipse-temurin-25 AS build-api-service # Build lowcoder-api COPY ./server/api-service /lowcoder-server @@ -26,7 +26,7 @@ RUN chmod +x /lowcoder/api-service/*.sh ## To create a separate image out of it, build it with: ## DOCKER_BUILDKIT=1 docker build -f deploy/docker/Dockerfile -t lowcoderorg/lowcoder-ce-api-service --target lowcoder-ce-api-service . ## -FROM eclipse-temurin:17.0.21_9-jdk-jammy AS lowcoder-ce-api-service +FROM eclipse-temurin:25-jdk-jammy AS lowcoder-ce-api-service LABEL maintainer="lowcoder" RUN apt-get update && apt-get install -y --no-install-recommends gosu \ @@ -377,7 +377,7 @@ RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get -y install --no-ins supervisor \ gosu \ nodejs=22.23.5-1nodesource1 \ - openjdk-17-jdk-headless=17.0.21.1+2-1~22.04.1 \ + openjdk-25-jdk-headless \ && npm install -g yarn \ && rm -rf /var/cache/apt/lists /var/lib/apt/lists/* /var/log/dpkg.log \ && apt-get clean \ diff --git a/deploy/docker/api-service/entrypoint.sh b/deploy/docker/api-service/entrypoint.sh index 0dacfa3f30..775e1ebee2 100644 --- a/deploy/docker/api-service/entrypoint.sh +++ b/deploy/docker/api-service/entrypoint.sh @@ -44,6 +44,7 @@ exec $GOSU "${JAVA_HOME}/bin/java" \ -Dspring.config.location="file:///lowcoder/api-service/config/application.yaml" \ --add-opens java.base/java.nio=ALL-UNNAMED \ -XX:-UseBASE64Intrinsics \ + --enable-native-access=ALL-UNNAMED \ ${JAVA_OPTS} \ -Dpf4j.pluginsDir=/lowcoder/api-service/plugins \ -jar "${APP_JAR}" --spring.webflux.base-path="${CONTEXT_PATH}" ${CUSTOM_APP_PROPERTIES} diff --git a/docs/lowcoder-extension/opensource-contribution/README.md b/docs/lowcoder-extension/opensource-contribution/README.md index 53456febf9..549541012e 100644 --- a/docs/lowcoder-extension/opensource-contribution/README.md +++ b/docs/lowcoder-extension/opensource-contribution/README.md @@ -201,7 +201,7 @@ Vite keeps the Browser for all changes current. That means you can see the effec #### Preparation -To develop with us in the API-Service, you need to have Java - OpenJDK 17 Maven - Version 3+ (preferably 3.8+) installed. Also, it is helpful if you have knowledge of [Spring Webflux](https://docs.spring.io/spring-framework/reference/web/webflux.html) +To develop with us in the API-Service, you need to have Java - OpenJDK 25 Maven - Version 3+ (preferably 3.8+) installed. Also, it is helpful if you have knowledge of [Spring Webflux](https://docs.spring.io/spring-framework/reference/web/webflux.html) You would need to have a MongoDB and a RedisDB ready and accessible. @@ -279,7 +279,7 @@ This is the main class. Now you can use the IDE to "run" it or "debug it". Configure the Run/Debug configuration as shown below. -| JDK version | Java 17 | +| JDK version | Java 25 | | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | -cp | lowcoder-server | | VM options | -Dpf4j.mode=development -Dpf4j.pluginsDir=lowcoder-plugins -Dspring.profiles.active=lowcoder -XX:+AllowRedefinitionToAddDeleteMethods --add-opens java.base/java.nio=ALL-UNNAMED | diff --git a/e2e/README.md b/e2e/README.md index aaff6acd98..fcf7d15563 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -311,14 +311,14 @@ Test titles carry these ids. ## 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 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`: +Counts (re-measured 2026-11-26 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 **862 tests in 115 files**; with `E2E_INCLUDE_QUARANTINE=1` **875 in 116**; with `E2E_INCLUDE_SUPERADMIN=1` **867 in 115**; with both of those **880 in 116**; +with `E2E_INCLUDE_INSERT_ALL=1` **974 in 116**; with all three opt-in variables **992 in 117** (the takeover variable changes nothing on the default stack); with `E2E_INCLUDE_NODE_SERVICE_SIDECARS=1` **921 in 120** (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 **1051 in 122** 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; 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. +Default-run tag counts (`--list --reporter=list --grep `): `@smoke` 7, `@core` 57, `@slow` 39, `@npm` 32, `@security` 157, `@lifecycle` 112, `@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` 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-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: 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) +### smoke (6) | File | Proves | Tags | Tests | |---|---|---|---| @@ -326,6 +326,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | smoke/published-view.spec.ts | an API-seeded app renders in the published view | @smoke | 1 | | 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 | +| smoke/api-docs.spec.ts | the springdoc OpenAPI document is served anonymously, and the Swagger UI page renders one operation block per operation of it | @smoke | 2 | ### auth, workspace, apps (88 default, 95 with the quarantined), account (25 default, 27 with the quarantined) @@ -341,7 +342,7 @@ Since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` the | 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) | +| 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-AK08 passes: D-51 fixed) | @lifecycle | 8 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 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) | @@ -438,7 +439,7 @@ Access-control tests, API level plus UI checks in SEC-R01a, R01e, R02a, R04a+, R 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 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. +of `src/security/quarantine.ts` (`OPEN_DEFECTS`; `FIXED_ON_BRANCH` is empty); 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 server and the client of the image under test (3.0.0-e2e or 3.0.1-e2e), not a pull request's client. @@ -575,6 +576,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) | +| CD-11 candidate | a carousel's `change` event is lost when its slider list resizes while a slide is running: react-slick (`@ant-design/react-slick` 1.1.2) answers a resize 50 ms later with `resizeWindow`, which cancels the pending `afterChange` without calling it; the slide still moves. The carousel resizes its list once after every mount (it sets the slides' height from `useResizeDetector`), so a dot click in the first moments after the carousel shows can lose the event too. Measured on lowcoder-ce:asu-full-e2e: a viewport 40 px narrower right after a dot click lost `change` in 40 of 40 runs (0 of 40 with the same resize 1 s before the click); a click right after the first slide showed lost it in 17 of 80. The id is provisional until the owner assigns one | `components/media.spec.ts` (S12 carousel) waits for the slides' height and `CAROUSEL_RESIZE_SETTLE_MS` before the dot click (workaround), annotation `{type:"defect", description:"CD-11 candidate"}`; no test asserts the desired behaviour yet | | 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 | @@ -607,7 +609,7 @@ SEC-R09d (D-38) left the quarantine: the check took the workspace of the first i | 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 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-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 in the default run: it reloaded the page while its DELETE was still in flight, which aborted the request (a test defect, 15 of 100 runs failed on asu-full-e2e); it now waits for the row to leave the list first (0 of 40 failed) | | 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 @@ -659,7 +661,7 @@ and passes. | 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-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 in the default run (its intermittent failure was the test reloading during the delete) | 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 | diff --git a/e2e/src/constants.ts b/e2e/src/constants.ts index 6d83ce07d6..bb3ad1f7fa 100644 --- a/e2e/src/constants.ts +++ b/e2e/src/constants.ts @@ -154,6 +154,18 @@ export const UI_PATHS = { ADMIN_LOGIN: "/admin/login", } as const; +/** + * The springdoc routes of api-service, open to anonymous callers (`GET /api/docs/**` in `SecurityConfig.java`); the paths are + * `springdoc.api-docs.path` and `springdoc.swagger-ui.path` in `application.yaml`. + */ +export const API_DOCS_PATHS = { + OPENAPI_JSON: "/api/docs/openapi.json", + SWAGGER_UI: "/api/docs/swagger-ui", +} as const; + +/** `info.title` of the OpenAPI document (`OpenAPIDocsConfiguration.customizeOpenAPI`), the heading Swagger UI shows. */ +export const API_DOCS_TITLE = "Lowcoder Open Rest API"; + /** Meets the password rules of the sign-up form. */ export const TEST_PASSWORD = "Passw0rd-e2e"; diff --git a/e2e/src/pages/AppListPage.ts b/e2e/src/pages/AppListPage.ts index 37b2f14735..d1b88a5183 100644 --- a/e2e/src/pages/AppListPage.ts +++ b/e2e/src/pages/AppListPage.ts @@ -50,14 +50,22 @@ export class AppListPage { * Imports an app from a JSON file through "New" > "Import". The app takes the name stored in the file; returns it. */ async importFile(path: string): Promise { - await this.page.getByRole("button", { name: "New" }).click(); + const newButton = this.newButton; + // The visible "Import" text of the menu item is covered by the Upload of `AppImport` (CreateDropdown.tsx), which takes + // the click: Playwright refuses a click on the text ("intercepts pointer events") and a click on the menu item's centre + // does not reach the Upload, so click the Upload wrapper itself. The item holds two `.ant-upload` elements (this div and + // a span inside it); no role or test id names the Upload. + const importTrigger = this.page.getByRole("menuitem", { name: "Import" }).locator(".ant-upload-select"); // The menu animates open, and a click that lands while it moves does not start the upload; try again until the // file chooser opens. let chooser: FileChooser | undefined; await expect(async () => { + if (!(await importTrigger.isVisible())) { + await newButton.click({ timeout: IMPORT_ATTEMPT_TIMEOUT_MS }); + } [chooser] = await Promise.all([ this.page.waitForEvent("filechooser", { timeout: IMPORT_ATTEMPT_TIMEOUT_MS }), - this.page.getByText("Import", { exact: true }).filter({ visible: true }).click({ timeout: IMPORT_ATTEMPT_TIMEOUT_MS }), + importTrigger.click({ timeout: IMPORT_ATTEMPT_TIMEOUT_MS }), ]); }).toPass({ timeout: IMPORT_TIMEOUT_MS }); await chooser!.setFiles(path); @@ -75,9 +83,13 @@ export class AppListPage { await this.page.goto(`/invite/${inviteCode}`); } - /** The "New" button of the app list (the page has two "New" buttons: the first one): the client shows it to developers and admins only (`orgDev` gate). */ + /** + * The "New" button of the app list, by its exact name (the sidebar's "News" button would match a substring); the page can + * hold two "New" buttons (measured on a developer's list, SEC-R07c), so the first one. The client shows it to developers and + * admins only (`orgDev` gate). + */ get newButton(): Locator { - return this.page.getByRole("button", { name: "New" }).first(); + return this.page.getByRole("button", { name: "New", exact: true }).first(); } get emptyState(): Locator { diff --git a/e2e/src/security/quarantine.ts b/e2e/src/security/quarantine.ts index 040bb405ca..60cfa65574 100644 --- a/e2e/src/security/quarantine.ts +++ b/e2e/src/security/quarantine.ts @@ -23,18 +23,14 @@ export const DEFECT_ANNOTATION_TYPE = "defect"; /** * 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. + * defect id. Empty: since the reassessment of 2026-11-22 on `lowcoderorg/lowcoder-ce:3.0.1-e2e` every entry has left the map + * (its test passes and runs by default). LC-AK04 (D-45) was the last one: its UI test reloaded the page while the DELETE was + * still in flight; it now waits for the row to leave the list first. * * 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> = { - "LC-AK04": "D-45", -}; +export const FIXED_ON_BRANCH: Readonly> = {}; /** * Scenarios that still fail on this branch's server (open defects, listed in the table "Security findings" of diff --git a/e2e/tests/account/api-keys.spec.ts b/e2e/tests/account/api-keys.spec.ts index 6b76e97f16..0f16120071 100644 --- a/e2e/tests/account/api-keys.spec.ts +++ b/e2e/tests/account/api-keys.spec.ts @@ -120,6 +120,10 @@ test.describe("lifecycle: API keys", () => { expectAnswer(await answerWithKey(anonymous, token), ALLOWED, "before: the key works"); await keys.deleteKey(KEY_NAME); + // The confirm click returns while the DELETE is still in flight, and a reload at that moment aborts it: the server then + // keeps the key. The card fetches the list again only after the DELETE succeeded (`UserApiKeysCard.tsx`, + // `handleDeleteApiKey`), so the row leaving the list means the server has answered; the reload then shows what it stored. + await expect(keys.rowOf(KEY_NAME), "the deleted key leaves the list").toHaveCount(0); await user.session.page.reload(); await expect(keys.title, "the card is back after the reload").toBeVisible(); diff --git a/e2e/tests/components/media.spec.ts b/e2e/tests/components/media.spec.ts index a4b3ccd0cb..9ae92e5e95 100644 --- a/e2e/tests/components/media.spec.ts +++ b/e2e/tests/components/media.spec.ts @@ -35,6 +35,19 @@ const PDF_DATA_URI_PREFIX = "data:application/pdf;base64,"; const FILE_VIEWER_ERROR = "Please Enter a Valid URL or Base64 String"; const FIRST_COMMENT = "Has anyone tried using Lowcode for our new internal tool yet?"; const STATE_TEXT_ITEM: DslItem = text({ id: "t0", name: "tState", testId: STATE_TEXT_ID, text: STATE_TEXT }); +/** + * How long to wait, after the carousel's slides got their height, before a dot click. The carousel sets the + * slides' height after it mounts (`useResizeDetector` in client/packages/lowcoder/src/comps/comps/carouselComp.tsx), + * so its slider list resizes once on every load; react-slick (`@ant-design/react-slick` 1.1.2, + * `lib/inner-slider.js`, `onWindowResized`/`resizeWindow`) answers that 50 ms later, and `resizeWindow` cancels the + * pending end of a slide already running, whose `afterChange` is the `change` event (CD-11 candidate). No page + * signal shows the debounced call. Measured on lowcoder-ce:asu-full-e2e, 4 workers, 40 runs per variant: the call + * ran 50 to 56 ms after the list's resize; a click as soon as the first slide was current lost `change` in 8 of 40 + * runs, a click as soon as the slides had their height in 1 of 40, a click this long after the height in 0 of 40. + */ +const CAROUSEL_RESIZE_SETTLE_MS = 250; +/** The image box of the current slide (react-slick wraps each child in two divs; it has no role or test id). */ +const CAROUSEL_CURRENT_IMAGE = ".slick-slide.slick-current > div > div > div"; /** Waits until the browser has decoded the image: its natural width is the 8 px of the PNG fixtures. */ async function expectDecodedPng(image: Locator, message: string): Promise { @@ -70,7 +83,9 @@ test.describe("S12 media components", () => { await expect(view.byTestId(STATE_TEXT_ID), "the click event set the state").toHaveText("s=image-clicked"); }); - test("carousel shows its two slides and the second dot fires change", async ({ page, apiUser }) => { + test("carousel shows its two slides and the second dot fires change", { + annotation: { type: "defect", description: "CD-11 candidate" }, + }, async ({ page, apiUser }) => { const dsl = mediaApp([ component("carousel", { id: "c1", @@ -83,6 +98,13 @@ test.describe("S12 media components", () => { const carousel = view.byTestId(COMPONENT_ID); await expect(carousel.locator(".slick-slide:not(.slick-cloned)"), "one slide per image").toHaveCount(2); await expect(carousel.locator(".slick-slide.slick-current"), "the first slide is current").toHaveAttribute("data-index", "0"); + await expect + .poll(() => carousel.locator(CAROUSEL_CURRENT_IMAGE).evaluate((element) => element.getBoundingClientRect().height), { + message: "the slides got their height", + }) + .toBeGreaterThan(0); + // CD-11 candidate: a click before the slider's debounced resize has run loses the change event. + await page.waitForTimeout(CAROUSEL_RESIZE_SETTLE_MS); await carousel.locator(".slick-dots li").nth(1).locator("button").click(); diff --git a/e2e/tests/components/npm-components.spec.ts b/e2e/tests/components/npm-components.spec.ts index d15ea0f23f..3e181ff9a3 100644 --- a/e2e/tests/components/npm-components.spec.ts +++ b/e2e/tests/components/npm-components.spec.ts @@ -30,8 +30,18 @@ interface NpmComponent { exactlyOnceText?: string; /** Number of canvases the component draws, where it is known (the image editor has two). */ canvasCount?: number; + /** The page clock, for a component whose default content depends on today's date. */ + pinnedNow?: Date; } +/** + * Inside the recorded default events of `fixtures/dsl/calendar.json` (2026-11-20 to 2026-11-22). The calendar opens on the + * week of today, and its only SVG is the delete icon each event carries (`CalendarDeleteIcon`, + * client/packages/lowcoder-comps/src/comps/calendarComp/calendarComp.tsx), so without a pinned clock the SVG is there only + * in the week the fixture was recorded. + */ +const CALENDAR_FIXTURE_NOW = new Date("2026-11-20T12:00:00Z"); + /** The 17 ECharts charts (S15) draw on a canvas; `barChart`, `lineChart` and `pieChart` were the first three built. */ const CHART_TYPES = [ "chart", @@ -56,7 +66,7 @@ const CHART_TYPES = [ const COMPONENTS: NpmComponent[] = [ ...CHART_TYPES.map((type): NpmComponent => ({ type, draws: "canvas" })), { type: "mermaid", draws: "svg", text: "Is it working?" }, - { type: "calendar", draws: "svg" }, + { type: "calendar", draws: "svg", pinnedNow: CALENDAR_FIXTURE_NOW }, { type: "ganttChart", draws: "svg" }, { type: "bpmnEditor", draws: "svg" }, { type: "pivotTable", draws: "text" }, @@ -82,6 +92,9 @@ test.describe("components loaded from npm", () => { const dsl = JSON.parse(readFileSync(join(FIXTURE_DIR, `${component.type}.json`), "utf8")); const { appId } = await createApp(page.request, { orgId: apiUser.orgId, name: `e2e-npm-${component.type}`, dsl }); await publishApp(page.request, appId); + if (component.pinnedNow) { + await page.clock.install({ time: component.pinnedNow }); + } await new AppViewPage(page).open(appId); diff --git a/e2e/tests/foundation/security-quarantine.spec.ts b/e2e/tests/foundation/security-quarantine.spec.ts index f109baa085..22d76f0e98 100644 --- a/e2e/tests/foundation/security-quarantine.spec.ts +++ b/e2e/tests/foundation/security-quarantine.spec.ts @@ -16,7 +16,7 @@ import { securityTestDetails, } from "../../src/security/quarantine"; -/** Sizes of the two maps: 1 fixed-on-branch scenario (the lifecycle id LC-AK04, an intermittent UI test), and 4 open ones +/** Sizes of the two maps: no fixed-on-branch scenario (LC-AK04 left it: its UI test no longer reloads during the delete), 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: @@ -38,7 +38,7 @@ import { * 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 FIXED_ON_BRANCH_COUNT = 0; 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"; @@ -48,8 +48,8 @@ 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"; -/** 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"; +/** The last id that left `FIXED_ON_BRANCH` (its test passes, so it is in neither map). */ +const LEFT_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"; @@ -62,10 +62,6 @@ 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(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], annotation: { type: DEFECT_ANNOTATION_TYPE, description: OPEN_DEFECTS[OPEN_ID] }, @@ -109,7 +105,7 @@ test.describe("security quarantine list", () => { }); test("quarantinedDefect names the defect of a listed id and nothing for an unlisted one", () => { - expect(quarantinedDefect(FIXED_LC_ID)).toBe(FIXED_ON_BRANCH[FIXED_LC_ID]); + expect(quarantinedDefect(LEFT_FIXED_LC_ID), "an id that left FIXED_ON_BRANCH").toBeUndefined(); expect(quarantinedDefect(OPEN_ID)).toBe(OPEN_DEFECTS[OPEN_ID]); expect(quarantinedDefect(PASSING_ID)).toBeUndefined(); }); @@ -142,6 +138,7 @@ test.describe("security quarantine list", () => { expect(details.tag).toEqual([TAGS.LIFECYCLE]); expect(details, "no annotation key at all").not.toHaveProperty("annotation"); + expect(lifecycleTestDetails(LEFT_FIXED_LC_ID), "the lifecycle id that left FIXED_ON_BRANCH").toEqual({ tag: [TAGS.LIFECYCLE] }); }); test("a lifecycle id the lookup lists gets the lifecycle and quarantine tags and the defect annotation", () => { diff --git a/e2e/tests/smoke/api-docs.spec.ts b/e2e/tests/smoke/api-docs.spec.ts new file mode 100644 index 0000000000..4949fa0574 --- /dev/null +++ b/e2e/tests/smoke/api-docs.spec.ts @@ -0,0 +1,86 @@ +import { API_DOCS_PATHS, API_DOCS_TITLE, TAGS } from "../../src/constants"; +import { expect, test } from "../../src/fixtures"; + +/** The HTTP methods of an OpenAPI path item that Swagger UI renders as one operation block each. */ +const OPERATION_METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"]; + +/** Major version of the OpenAPI specification the document declares (its `openapi` field). */ +const OPENAPI_VERSION_PREFIX = "3."; + +/** The page springdoc redirects the Swagger UI path to. */ +const DOCS_INDEX_URL = /\/api\/docs\/.*index\.html/; + +interface OpenApiDocument { + openapi: string; + info: { title: string; version: string }; + tags?: { name: string }[]; + paths: Record>; +} + +function operationCountOf(document: OpenApiDocument): number { + return Object.values(document.paths).reduce( + (count, pathItem) => count + OPERATION_METHODS.filter((method) => method in pathItem).length, + 0, + ); +} + +/** Every tag name the document declares or its operations carry. */ +function tagNamesOf(document: OpenApiDocument): Set { + const names = new Set((document.tags ?? []).map((tag) => tag.name)); + for (const pathItem of Object.values(document.paths)) { + for (const operation of Object.values(pathItem)) { + for (const tag of (operation as { tags?: string[] }).tags ?? []) { + names.add(tag); + } + } + } + return names; +} + +test.describe("springdoc API documentation", () => { + test("the OpenAPI document is served to an anonymous caller", { tag: TAGS.SMOKE }, async ({ page }) => { + const response = await page.request.get(API_DOCS_PATHS.OPENAPI_JSON); + expect(response.status(), "status of the OpenAPI document").toBe(200); + + const document = (await response.json()) as OpenApiDocument; + expect(document.openapi.startsWith(OPENAPI_VERSION_PREFIX), `openapi version ${document.openapi}`).toBe(true); + expect(document.info.title, "info.title").toBe(API_DOCS_TITLE); + expect(operationCountOf(document), "operations in the document").toBeGreaterThan(0); + }); + + test("the Swagger UI page renders the operations of the document", { tag: TAGS.SMOKE }, async ({ + page, + networkGuard, + }) => { + const document = (await (await page.request.get(API_DOCS_PATHS.OPENAPI_JSON)).json()) as OpenApiDocument; + expect(operationCountOf(document), "operations in the document").toBeGreaterThan(0); + + await page.goto(API_DOCS_PATHS.SWAGGER_UI); + + // springdoc redirects the configured path to the index.html it bundles; where that lives depends on its version + // (3.0.0 image: /api/docs/webjars/swagger-ui/index.html), so only the page name is asserted + await expect(page, "Swagger UI page").toHaveURL(DOCS_INDEX_URL); + await expect(page.getByRole("heading", { name: API_DOCS_TITLE }), "title of the API").toBeVisible(); + // Swagger UI exposes no role or test id for its operation blocks, so these use its own CSS classes and data attributes. + // The newer Swagger UI renders only the blocks near the viewport (6 of 176 measured), the 3.0.0 one renders all of + // them, so the rendered blocks are checked against the document instead of counted. + const operations = page.locator(".swagger-ui .opblock"); + await expect(operations.first(), "an operation block").toBeVisible(); + const renderedPaths = await page.locator(".swagger-ui .opblock-summary-path").evaluateAll((elements) => + elements.map((element) => element.getAttribute("data-path")), + ); + const renderedTags = await page.locator(".swagger-ui .opblock-tag").evaluateAll((elements) => + elements.map((element) => element.getAttribute("data-tag")), + ); + expect(renderedPaths.length, "rendered operation paths").toBeGreaterThan(0); + expect(renderedTags.length, "rendered tag headers").toBeGreaterThan(0); + for (const renderedPath of renderedPaths) { + expect(Object.keys(document.paths), `path ${renderedPath} of a rendered block`).toContain(renderedPath); + } + for (const renderedTag of renderedTags) { + expect([...tagNamesOf(document)], `tag ${renderedTag} of a rendered header`).toContain(renderedTag); + } + await expect(page.locator(".swagger-ui .errors-wrapper"), "Swagger UI load errors").toHaveCount(0); + expect(networkGuard.blockedUrls, "requests the page made to a blocked host").toEqual([]); + }); +}); diff --git a/e2e/tests/workspace/leave-removal.spec.ts b/e2e/tests/workspace/leave-removal.spec.ts index 062b309832..fdccbddfdf 100644 --- a/e2e/tests/workspace/leave-removal.spec.ts +++ b/e2e/tests/workspace/leave-removal.spec.ts @@ -258,16 +258,25 @@ test.describe("lifecycle: leaving, removal and deletion", () => { expectAnswer(await deleteOrganizationRaw(admin.request, doomed), OK, "the deletion"); await expect.poll(async () => (await currentUser(member.request)).orgAndRoles.some((entry) => entry.org.id === doomed), { message: "the clean-up ran", ...POLL }).toBe(false); - const adminView = await viewAppRaw(admin.request, appId); + // The org-deleted listener marks the workspace's apps DELETED after its members and groups + // (OrgAndGroupEventListener.onOrgDeleted); the creator keeps READ (createdBy), so its view reaches the status check. + await expect + .poll( + async () => { + const answer = await viewAppRaw(admin.request, appId); + return { status: answer.status, code: answer.code }; + }, + { message: "the admin's view: the app is marked deleted", ...POLL }, + ) + .toEqual(API_ERRORS.UNSUPPORTED_OPERATION); const adminEdit = await editAppRaw(admin.request, appId); const memberView = await viewAppRaw(member.request, appId); const memberEdit = await editAppRaw(member.request, appId); - expect({ status: adminView.status, code: adminView.code }, "the admin's view").toEqual(API_ERRORS.UNABLE_TO_FIND_VALID_ORG); - expect({ status: adminEdit.status, code: adminEdit.code }, "the admin's editing view").toEqual(API_ERRORS.UNABLE_TO_FIND_VALID_ORG); - expect({ status: memberView.status, code: memberView.code }, "the former member's view").toEqual(API_ERRORS.UNABLE_TO_FIND_VALID_ORG); + expect({ status: adminEdit.status, code: adminEdit.code }, "the admin's editing view").toEqual(API_ERRORS.NO_PERMISSION_TO_REQUEST_APP); + expect({ status: memberView.status, code: memberView.code }, "the former member's view").toEqual(API_ERRORS.NO_PERMISSION_TO_REQUEST_APP); expect({ status: memberEdit.status, code: memberEdit.code }, "the former member's editing view").toEqual(API_ERRORS.NO_PERMISSION_TO_REQUEST_APP); - testInfo.annotations.push({ type: "observation", description: "the apps of a deleted workspace are not deleted (nothing removes them) but no call opens them" }); + testInfo.annotations.push({ type: "observation", description: "the apps of a deleted workspace are marked DELETED (still stored) and no call opens them; the creator's view answers 400 / 5003 'Bad request.'" }); }); test("LC-DL11 an invitation of a deleted workspace admits nobody", lifecycleTestDetails("LC-DL11"), async ({ actor }) => { diff --git a/server/api-service/README.md b/server/api-service/README.md index 403a16d82d..a3d774794e 100644 --- a/server/api-service/README.md +++ b/server/api-service/README.md @@ -4,7 +4,7 @@ This document explains how to start Lowcoder server locally. ## System Prerequisites -Java - OpenJDK 17 Maven - Version 3+ (preferably 3.8+) +Java - OpenJDK 25 Maven - Version 3+ (preferably 3.8+) ### MongoDB @@ -50,7 +50,7 @@ The contents should look like this: "request": "launch", "mainClass": "org.lowcoder.api.ServerApplication", "projectName": "lowcoder-server", - "vmArgs": "-Dpf4j.mode=development -Dpf4j.pluginsDir=server/api-service/lowcoder-plugins -Dspring.profiles.active=lowcoder-local-dev -XX:+AllowRedefinitionToAddDeleteMethods --add-opens java.base/java.nio=ALL-UNNAMED" + "vmArgs": "-Dpf4j.mode=development -Dpf4j.pluginsDir=server/api-service/lowcoder-plugins -Dspring.profiles.active=lowcoder-local-dev -XX:+AllowRedefinitionToAddDeleteMethods --add-opens java.base/java.nio=ALL-UNNAMED --enable-native-access=ALL-UNNAMED" } ], } @@ -96,7 +96,7 @@ Configure the Run/Debug configuration as shown below. - + @@ -104,7 +104,7 @@ Configure the Run/Debug configuration as shown below. - + @@ -112,6 +112,8 @@ Configure the Run/Debug configuration as shown below.
JDK versionJava 17 Java 25
-cp
VM options -Dpf4j.mode=development -Dpf4j.pluginsDir=lowcoder-plugins -Dspring.profiles.active=lowcoder -XX:+AllowRedefinitionToAddDeleteMethods --add-opens java.base/java.nio=ALL-UNNAMED-Dpf4j.mode=development -Dpf4j.pluginsDir=lowcoder-plugins -Dspring.profiles.active=lowcoder -XX:+AllowRedefinitionToAddDeleteMethods --add-opens java.base/java.nio=ALL-UNNAMED --enable-native-access=ALL-UNNAMED
Main class
+`-XX:+AllowRedefinitionToAddDeleteMethods` is deprecated on Java 25 and prints a warning at start. It is only needed when BlockHound is enabled. + ## Build locally Next action is to build the project, so all lowcoder-plugins are built. This is a precondition for the lowcoder-server to start. diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/_remote.repositories b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/_remote.repositories deleted file mode 100644 index db303e7abe..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/_remote.repositories +++ /dev/null @@ -1,4 +0,0 @@ -#NOTE: This is a Maven Resolver internal implementation file, its format can be changed without prior notice. -#Sat Sep 21 00:11:37 CEST 2024 -rjson-1.3.1-20210724.182155-1.jar>vault-proxy= -rjson-1.3.1-20210724.182155-1.pom>vault-proxy= diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/maven-metadata-vault-proxy.xml b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/maven-metadata-vault-proxy.xml deleted file mode 100644 index c47f1b1e15..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/maven-metadata-vault-proxy.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - tv.twelvetone.rjson - rjson - 1.3.1-SNAPSHOT - - - 20210724.182155 - 1 - - 20210724182155 - - - pom - 1.3.1-20210724.182155-1 - 20210724182155 - - - jar - 1.3.1-20210724.182155-1 - 20210724182155 - - - - diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/maven-metadata-vault-proxy.xml.7536061247895154110.tmp b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/maven-metadata-vault-proxy.xml.7536061247895154110.tmp deleted file mode 100644 index c47f1b1e15..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/maven-metadata-vault-proxy.xml.7536061247895154110.tmp +++ /dev/null @@ -1,25 +0,0 @@ - - - tv.twelvetone.rjson - rjson - 1.3.1-SNAPSHOT - - - 20210724.182155 - 1 - - 20210724182155 - - - pom - 1.3.1-20210724.182155-1 - 20210724182155 - - - jar - 1.3.1-20210724.182155-1 - 20210724182155 - - - - diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/maven-metadata-vault-proxy.xml.sha1 b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/maven-metadata-vault-proxy.xml.sha1 deleted file mode 100644 index b19dd9b683..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/maven-metadata-vault-proxy.xml.sha1 +++ /dev/null @@ -1 +0,0 @@ -f102838e293f93813c3cd40d32d0266dec77e664 \ No newline at end of file diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/resolver-status.properties b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/resolver-status.properties deleted file mode 100644 index 3cc83f9bc0..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/resolver-status.properties +++ /dev/null @@ -1,3 +0,0 @@ -#NOTE: This is a Maven Resolver internal implementation file, its format can be changed without prior notice. -#Tue Sep 30 10:51:07 CEST 2025 -maven-metadata-vault-proxy.xml.lastUpdated=1759222267613 diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.jar b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.jar deleted file mode 100644 index db939773c6..0000000000 Binary files a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.jar and /dev/null differ diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.jar.sha1 b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.jar.sha1 deleted file mode 100644 index b5ec94e070..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.jar.sha1 +++ /dev/null @@ -1 +0,0 @@ -33eff182d4ddc80f75e7a5cc34564a01e70a6881 \ No newline at end of file diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.pom b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.pom deleted file mode 100644 index dbe1e2aad3..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.pom +++ /dev/null @@ -1,8 +0,0 @@ - - - 4.0.0 - tv.twelvetone.rjson - rjson - 1.3.1-SNAPSHOT - diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.pom.sha1 b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.pom.sha1 deleted file mode 100644 index f2ec62472f..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-20210724.182155-1.pom.sha1 +++ /dev/null @@ -1 +0,0 @@ -7d3c2960bb2d14b9ca280d73a35cf11314b871f7 \ No newline at end of file diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-SNAPSHOT.jar b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-SNAPSHOT.jar deleted file mode 100644 index db939773c6..0000000000 Binary files a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-SNAPSHOT.jar and /dev/null differ diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-SNAPSHOT.pom b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-SNAPSHOT.pom deleted file mode 100644 index dbe1e2aad3..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/1.3.1-SNAPSHOT/rjson-1.3.1-SNAPSHOT.pom +++ /dev/null @@ -1,8 +0,0 @@ - - - 4.0.0 - tv.twelvetone.rjson - rjson - 1.3.1-SNAPSHOT - diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/maven-metadata-vault-proxy.xml b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/maven-metadata-vault-proxy.xml deleted file mode 100644 index 5f71bffbef..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/maven-metadata-vault-proxy.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - tv.twelvetone.rjson - rjson - - 1.3.1-SNAPSHOT - - 1.0-SNAPSHOT - 1.3.1-SNAPSHOT - - 20210724182156 - - diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/maven-metadata-vault-proxy.xml.sha1 b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/maven-metadata-vault-proxy.xml.sha1 deleted file mode 100644 index 19f923ae5f..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/maven-metadata-vault-proxy.xml.sha1 +++ /dev/null @@ -1 +0,0 @@ -c560949fd4404bbf2f643ec320e9d077c3b06934 \ No newline at end of file diff --git a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/resolver-status.properties b/server/api-service/local-repo/tv/twelvetone/rjson/rjson/resolver-status.properties deleted file mode 100644 index 4c30d89698..0000000000 --- a/server/api-service/local-repo/tv/twelvetone/rjson/rjson/resolver-status.properties +++ /dev/null @@ -1,3 +0,0 @@ -#NOTE: This is a Maven Resolver internal implementation file, its format can be changed without prior notice. -#Fri Sep 19 18:14:48 CEST 2025 -maven-metadata-vault-proxy.xml.lastUpdated=1758298488456 diff --git a/server/api-service/lombok.config b/server/api-service/lombok.config index 4190a3ac95..abb88782c2 100644 --- a/server/api-service/lombok.config +++ b/server/api-service/lombok.config @@ -6,3 +6,6 @@ lombok.copyableAnnotations += org.springframework.context.annotation.Lazy # Mark Lombok-generated methods with @lombok.Generated, which JaCoCo leaves out of coverage (T11.1) lombok.addLombokGeneratedAnnotation = true + +# Since Lombok 1.18.44 @Jacksonized asks which Jackson to generate for; generate for Jackson 3 (annotations in tools.jackson.databind.annotation) +lombok.jacksonized.jacksonVersion += 3 diff --git a/server/api-service/lowcoder-coverage-report/pom.xml b/server/api-service/lowcoder-coverage-report/pom.xml index ede26f05c1..5088598980 100644 --- a/server/api-service/lowcoder-coverage-report/pom.xml +++ b/server/api-service/lowcoder-coverage-report/pom.xml @@ -174,7 +174,7 @@ org.apache.maven.plugins maven-antrun-plugin - 3.1.0 + 3.2.0 org.jacoco diff --git a/server/api-service/lowcoder-dependencies/pom.xml b/server/api-service/lowcoder-dependencies/pom.xml index 30e2b52819..fd4a0d79e3 100644 --- a/server/api-service/lowcoder-dependencies/pom.xml +++ b/server/api-service/lowcoder-dependencies/pom.xml @@ -13,28 +13,12 @@ lowcoder-dependencies pom - - 2.0.5 - - - - - org.testcontainers - testcontainers-bom - ${testcontainers.version} - pom - import - org.springframework.boot spring-boot-dependencies - 3.2.4 + 4.1.3 pom import @@ -48,30 +32,30 @@ org.pf4j pf4j - 3.11.0 + 3.16.1 org.json json - 20240303 + 20260814 org.projectlombok lombok - 1.18.32 + 1.18.48 org.apache.commons commons-text - 1.11.0 + 1.15.0 commons-io commons-io - 2.16.0 + 2.22.0 org.glassfish @@ -81,51 +65,33 @@ jakarta.el jakarta.el-api - 5.0.1 + 6.0.1 org.eclipse.jgit org.eclipse.jgit - 6.9.0.202403050737-r - - - - jakarta.persistence - jakarta.persistence-api - 3.1.0 + 7.8.1.202611041320-r org.apache.commons commons-collections4 - 4.4 + 4.6.0 com.google.guava guava - 33.1.0-jre + 33.8.0-jre + tv.twelvetone.rjson rjson - 1.3.1-SNAPSHOT - - - org.jetbrains.kotlin - kotlin-stdlib-jdk7 - 1.9.23 - - - - com.jayway.jsonpath - json-path - 2.9.0 - - - com.github.ben-manes.caffeine - caffeine - 3.1.8 + 1.3.1 es.moki.ratelimitj @@ -135,7 +101,7 @@ com.github.spullara.mustache.java compiler - 0.9.11 + 0.9.14 @@ -144,16 +110,10 @@ 0.7.0 - - io.projectreactor - reactor-core - 3.6.4 - - org.pf4j pf4j-spring - 0.8.0 + 0.10.0 @@ -173,91 +133,46 @@ com.querydsl querydsl-mongodb - 5.0.0 + 5.1.0 jakarta io.sentry - sentry-spring-boot-starter-jakarta - 7.6.0 + sentry-spring-boot-4 + 8.66.0 org.jgrapht jgrapht-core - 1.5.2 + 1.5.3 - - jakarta.xml.bind - jakarta.xml.bind-api - 4.0.2 - - - jakarta.activation - jakarta.activation-api - 2.1.3 - org.glassfish.jaxb jaxb-runtime - 2.3.3 - - - - io.mongock - mongock-bom - 5.4.0 - pom - import - - - io.mongock - mongock-springboot - 5.4.0 + 4.0.9 io.projectreactor.tools blockhound - 1.0.8.RELEASE + 1.0.19.RELEASE - - jakarta.servlet - jakarta.servlet-api - 6.0.0 - - - - io.projectreactor - reactor-test - 3.6.4 - org.apache.httpcomponents httpclient 4.5.14 - - org.mockito - mockito-inline - 5.2.0 - test - - - jakarta.validation - jakarta.validation-api - 3.0.2 - org.springdoc springdoc-openapi-starter-webflux-ui - 2.5.0 + 3.2.1 diff --git a/server/api-service/lowcoder-domain/pom.xml b/server/api-service/lowcoder-domain/pom.xml index 28c7391748..b0301726a0 100644 --- a/server/api-service/lowcoder-domain/pom.xml +++ b/server/api-service/lowcoder-domain/pom.xml @@ -21,7 +21,7 @@ org.springframework.boot spring-boot-starter-data-mongodb-reactive - + org.springframework.boot spring-boot-starter-data-mongodb @@ -63,28 +63,6 @@ spring-boot-starter-mail - - io.mongock - mongock-springboot - - - com.google.guava - guava - - - javax.inject - javax.inject - - - org.springframework.boot - spring-boot-autoconfigure - - - - - io.mongock - mongodb-springdata-v4-driver - org.projectlombok lombok @@ -182,7 +160,7 @@ io.sentry - sentry-spring-boot-starter-jakarta + sentry-spring-boot-4 @@ -251,11 +229,6 @@ reactor-test test - - org.mockito - mockito-inline - test - org.mockito mockito-core @@ -279,7 +252,7 @@ com.github.f4b6a3 uuid-creator - 5.2.0 + 6.1.1 @@ -305,7 +278,7 @@ org.apache.maven.plugins maven-antrun-plugin - 3.1.0 + 3.2.0 generate-sources diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/configurations/MongoConfig.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/configurations/MongoConfig.java index b3adbcbfb2..2a0dc816e5 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/configurations/MongoConfig.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/configurations/MongoConfig.java @@ -1,18 +1,12 @@ package org.lowcoder.domain.configurations; -import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; -import com.mongodb.WriteConcern; -import io.mongock.driver.mongodb.springdata.v4.SpringDataMongoV4Driver; -import io.mongock.runner.springboot.MongockSpringboot; -import io.mongock.runner.springboot.base.MongockApplicationRunner; import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.lowcoder.domain.user.model.User; import org.lowcoder.sdk.config.MaterialProperties; import org.lowcoder.sdk.models.HasIdAndAuditing; -import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @@ -27,8 +21,6 @@ import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories; import org.springframework.security.core.context.ReactiveSecurityContextHolder; -import java.util.List; - @Slf4j @Configuration @RequiredArgsConstructor @@ -44,19 +36,6 @@ public void init() { mappingMongoConverter.setMapKeyDotReplacement("##OB_REPLACE##"); } - @Bean - public MongockApplicationRunner mongockApplicationRunner(ApplicationContext springContext, MongoTemplate mongoTemplate) { - SpringDataMongoV4Driver driver = SpringDataMongoV4Driver.withDefaultLock(mongoTemplate); - driver.setWriteConcern(WriteConcern.JOURNALED.withJournal(false)); - driver.setReadConcern(ReadConcern.LOCAL); - - return MongockSpringboot.builder() - .setDriver(driver) - .addMigrationScanPackages(List.of("org.lowcoder.runner.migrations")) - .setSpringContext(springContext) - .buildApplicationRunner(); - } - /** * inject {@link HasIdAndAuditing#setCreatedBy}}/{@link HasIdAndAuditing#setModifiedBy}} for JPA */ @@ -92,7 +71,7 @@ public ReactiveGridFsTemplate reactiveGridFsTemplate(ReactiveMongoDatabaseFactor } /** - * used by mongock + * The blocking template of the database migrations ({@code org.lowcoder.runner.migrations}). */ @Bean public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDbFactory, MappingMongoConverter mappingMongoConverter) { diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/configurations/RedisConfig.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/configurations/RedisConfig.java deleted file mode 100644 index 0b61a3843b..0000000000 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/configurations/RedisConfig.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.lowcoder.domain.configurations; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; -import org.springframework.data.redis.core.ReactiveRedisOperations; -import org.springframework.data.redis.core.ReactiveRedisTemplate; -import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.RedisSerializationContext; -import org.springframework.data.redis.serializer.StringRedisSerializer; - -import lombok.extern.slf4j.Slf4j; - -@Configuration -@Slf4j -public class RedisConfig { - - @Primary - @Bean - ReactiveRedisOperations reactiveRedisOperations(ReactiveRedisConnectionFactory factory) { - - var context = RedisSerializationContext. newSerializationContext(new StringRedisSerializer()) - .value(new Jackson2JsonRedisSerializer<>(String.class)) - .build(); - - return new ReactiveRedisTemplate<>(factory, context); - } -} diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/OrganizationDomain.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/OrganizationDomain.java index 65663808f7..e02f94d23b 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/OrganizationDomain.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/organization/model/OrganizationDomain.java @@ -1,6 +1,6 @@ package org.lowcoder.domain.organization.model; -import com.fasterxml.jackson.core.type.TypeReference; +import tools.jackson.core.type.TypeReference; import lombok.Getter; import lombok.Setter; import org.lowcoder.domain.mongodb.MongodbInterceptorContext; diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/model/ResourceRole.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/model/ResourceRole.java index ae9018f2f9..90ee34673d 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/model/ResourceRole.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/permission/model/ResourceRole.java @@ -1,5 +1,6 @@ package org.lowcoder.domain.permission.model; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.google.common.collect.Streams; import jakarta.annotation.Nullable; @@ -31,6 +32,7 @@ public enum ResourceRole { private final String value; private final int roleWeight; // used for sorting roles + @JsonCreator ResourceRole(String value, int roleWeight) { this.value = value; this.roleWeight = roleWeight; diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/plugin/client/DatasourcePluginClient.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/plugin/client/DatasourcePluginClient.java index aba0cacc09..c482d58f84 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/plugin/client/DatasourcePluginClient.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/plugin/client/DatasourcePluginClient.java @@ -1,5 +1,5 @@ package org.lowcoder.domain.plugin.client; - +import tools.jackson.databind.json.JsonMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; @@ -15,6 +15,7 @@ import org.lowcoder.sdk.exception.ServerException; import org.lowcoder.sdk.models.DatasourceTestResult; import org.lowcoder.sdk.models.QueryExecutionResult; +import org.lowcoder.sdk.webclient.JacksonClientCodecs; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.server.reactive.ServerHttpRequest; @@ -32,7 +33,7 @@ import static org.lowcoder.sdk.constants.GlobalContext.REQUEST; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.databind.ObjectMapper; @Slf4j @RequiredArgsConstructor @@ -41,7 +42,10 @@ public class DatasourcePluginClient implements NodeServerClient { private static final ExchangeStrategies EXCHANGE_STRATEGIES = ExchangeStrategies .builder() - .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) + .codecs(configurer -> { + JacksonClientCodecs.apply(configurer); + configurer.defaultCodecs().maxInMemorySize(-1); + }) .build(); private static final WebClient WEB_CLIENT = WebClient.builder() @@ -58,7 +62,7 @@ public class DatasourcePluginClient implements NodeServerClient { private static final String VALIDATE_PLUGIN_DATA_SOURCE_CONFIG = "validatePluginDataSourceConfig"; private static final String GET_PLUGIN_DYNAMIC_CONFIG = "getPluginDynamicConfig"; - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private static final ObjectMapper OBJECT_MAPPER = JsonMapper.builderWithJackson2Defaults().build(); public Mono> getPluginDynamicConfigSafely(List getPluginDynamicConfigRequestDTOS) { return getPluginDynamicConfig(getPluginDynamicConfigRequestDTOS) diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/serversetting/service/ServerSettingServiceImpl.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/serversetting/service/ServerSettingServiceImpl.java index 64e1847ab6..a627b78ac2 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/serversetting/service/ServerSettingServiceImpl.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/serversetting/service/ServerSettingServiceImpl.java @@ -10,7 +10,7 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.*; import java.util.stream.Collectors; import java.util.stream.StreamSupport; diff --git a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/model/User.java b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/model/User.java index 60f444edb8..678688d7b0 100644 --- a/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/model/User.java +++ b/server/api-service/lowcoder-domain/src/main/java/org/lowcoder/domain/user/model/User.java @@ -3,7 +3,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.type.TypeReference; +import tools.jackson.core.type.TypeReference; import lombok.*; import lombok.experimental.SuperBuilder; import lombok.extern.jackson.Jacksonized; diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/asset/service/AssetServiceImplTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/asset/service/AssetServiceImplTest.java index 44c689f02a..1e8c4c8550 100644 --- a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/asset/service/AssetServiceImplTest.java +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/asset/service/AssetServiceImplTest.java @@ -395,7 +395,7 @@ void anAssetWithoutContentTypeIsServedWithoutAContentTypeHeader() { StepVerifier.create(service.makeImageResponse(exchange, ASSET_ID)).verifyComplete(); - assertThat(exchange.getResponse().getHeaders().containsKey(HttpHeaders.CONTENT_TYPE)).isFalse(); + assertThat(exchange.getResponse().getHeaders().containsHeader(HttpHeaders.CONTENT_TYPE)).isFalse(); assertThat(exchange.getResponse().getBodyAsString().block(TIMEOUT)).isEqualTo("x"); } @@ -415,7 +415,7 @@ void anUnknownAssetIsCompletedAsA404WithNoBodyBF129() { + " committed=" + exchange.getResponse().isCommitted()); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(exchange.getResponse().isCommitted()).isTrue(); - assertThat(exchange.getResponse().getHeaders().containsKey(HttpHeaders.CONTENT_TYPE)).isFalse(); + assertThat(exchange.getResponse().getHeaders().containsHeader(HttpHeaders.CONTENT_TYPE)).isFalse(); assertThat(exchange.getResponse().getBodyAsString().block(TIMEOUT)).isEmpty(); } } 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 index fae27a9cfb..ae4a7837fd 100644 --- 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 @@ -16,8 +16,8 @@ import org.lowcoder.sdk.config.JsonViews; import org.lowcoder.sdk.util.JsonUtils; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; /** * {@link Organization#getAuthConfigs()} must never reach JSON (D-14): the configs hold OAuth client secrets, and diff --git a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/plugin/client/DatasourcePluginClientContractTest.java b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/plugin/client/DatasourcePluginClientContractTest.java index e57acf4974..deb380f35c 100644 --- a/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/plugin/client/DatasourcePluginClientContractTest.java +++ b/server/api-service/lowcoder-domain/src/test/java/org/lowcoder/domain/plugin/client/DatasourcePluginClientContractTest.java @@ -45,9 +45,10 @@ * dynamic-config {@code List}, the plugin definitions, the {@code QueryExecutionResult} as a §4.6 producer * report ({@link QueryResults#report}), and the {@code DatasourceTestResult} ({@link FieldTree}). * - * {@code runPluginQuery} is sent plain and encrypted; its encrypted body is written by the client's bare - * {@code new ObjectMapper()} (E11, O10), the plain one by the client codecs, and a {@code queryDsl} holding an - * {@link Instant} pins how each treats a {@code java.time} value. Pinned in {@value #REPORT}. + * {@code runPluginQuery} is sent plain and encrypted; its encrypted body is written by the client's own + * {@code OBJECT_MAPPER} (Jackson 2 defaults), the plain one by the client codecs, and a {@code queryDsl} holding an + * {@link Instant} pins how each treats a {@code java.time} value: both write it as the epoch-seconds number, where + * Jackson 2 without its time module failed the call. Pinned in {@value #REPORT}. * *

Limits: the node service is a recording stand-in answering fixed bodies; the {@code Accept-Language} header is * empty, as no request is in the reactor context; the body of {@code runPluginQuery} is a {@code Map.of}, whose member @@ -91,7 +92,7 @@ static void stopServers() { @BoundarySites({ "lowcoder-domain/src/main/java/org/lowcoder/domain/plugin/client/DatasourcePluginClient.java##import#1", - "lowcoder-domain/src/main/java/org/lowcoder/domain/plugin/client/DatasourcePluginClient.java#DatasourcePluginClient.OBJECT_MAPPER#new ObjectMapper#1", + "lowcoder-domain/src/main/java/org/lowcoder/domain/plugin/client/DatasourcePluginClient.java#DatasourcePluginClient.OBJECT_MAPPER#JsonMapper.builder#1", "lowcoder-domain/src/main/java/org/lowcoder/domain/plugin/client/DatasourcePluginClient.java#DatasourcePluginClient.getPluginDynamicConfig#bodyValue#1", "lowcoder-domain/src/main/java/org/lowcoder/domain/plugin/client/DatasourcePluginClient.java#DatasourcePluginClient.getPluginDynamicConfig#bodyToMono#1", "lowcoder-domain/src/main/java/org/lowcoder/domain/plugin/client/DatasourcePluginClient.java#DatasourcePluginClient.getDatasourcePluginDefinitions#bodyToMono#1", @@ -157,7 +158,7 @@ private static Map request(Request request) { report.putAll(encrypted ? Map.of(RecordingHttpServer.CONTENT_TYPE_KEY, request.header(RecordingHttpServer.CONTENT_TYPE)) : request.jsonBodyReport()); if (encrypted) { - report.put(DECRYPTED_KEY, new com.fasterxml.jackson.databind.util.RawValue( + report.put(DECRYPTED_KEY, new tools.jackson.databind.util.RawValue( Encryptors.text(NODE_PASSWORD, Hex.encodeHexString(NODE_SALT.getBytes(StandardCharsets.UTF_8))).decrypt(request.bodyText()))); } } diff --git a/server/api-service/lowcoder-domain/src/test/resources/json-contract/node-service/DatasourcePluginClient.calls.json b/server/api-service/lowcoder-domain/src/test/resources/json-contract/node-service/DatasourcePluginClient.calls.json index 8a1cb6d188..3964957451 100644 --- a/server/api-service/lowcoder-domain/src/test/resources/json-contract/node-service/DatasourcePluginClient.calls.json +++ b/server/api-service/lowcoder-domain/src/test/resources/json-contract/node-service/DatasourcePluginClient.calls.json @@ -102,7 +102,7 @@ "path" : "/node-service/api/runPluginQuery", "X-Encrypted" : [ ], "contentType" : [ "application/json" ], - "body" : {"pluginName":"contractPlugin","dsl":{"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ůň \uD83D\uDC0E 中文","escapes":"é \u0000 \n \t \" \\ / \uD83D\uDE00","key with escaped name":"escaped key","alpha":"last key"},"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}]} + "body" : {"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}],"pluginName":"contractPlugin","dsl":{"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ůň \uD83D\uDC0E 中文","escapes":"é \u0000 \n \t \" \\ / \uD83D\uDE00","key with escaped name":"escaped key","alpha":"last key"}} }, "result" : { "queryCode" : "OK", @@ -172,7 +172,7 @@ "path" : "/node-service/api/runPluginQuery", "X-Encrypted" : [ "true" ], "contentType" : [ "text/plain;charset=UTF-8" ], - "decrypted" : {"pluginName":"contractPlugin","dsl":{"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"},"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}]} + "decrypted" : {"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}],"pluginName":"contractPlugin","dsl":{"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"}} }, "result" : { "queryCode" : "OK", @@ -237,15 +237,143 @@ } }, "executeQueryWithInstant" : { - "request" : null, + "request" : { + "method" : "POST", + "path" : "/node-service/api/runPluginQuery", + "X-Encrypted" : [ ], + "contentType" : [ "application/json" ], + "body" : {"dataSourceConfig":{},"context":[],"pluginName":"contractPlugin","dsl":{"at":0.0}} + }, "result" : { - "error" : "org.lowcoder.sdk.exception.ServerException: Encryption error" + "queryCode" : "OK", + "dataShape" : { + "classes" : { + "" : "java.util.LinkedHashMap", + "/zeta" : "java.lang.String", + "/int" : "java.lang.Integer", + "/negativeInt" : "java.lang.Integer", + "/intMax" : "java.lang.Integer", + "/intMaxPlusOne" : "java.lang.Long", + "/intMinMinusOne" : "java.lang.Long", + "/longMax" : "java.lang.Long", + "/longMaxPlusOne" : "java.math.BigInteger", + "/longMinMinusOne" : "java.math.BigInteger", + "/decimal" : "java.lang.Double", + "/trailingZeroDecimal" : "java.lang.Double", + "/zeroPointZero" : "java.lang.Double", + "/negativeZero" : "java.lang.Integer", + "/exponent" : "java.lang.Double", + "/exponentUpperCase" : "java.lang.Double", + "/negativeExponent" : "java.lang.Double", + "/longDecimal" : "java.lang.Double", + "/true" : "java.lang.Boolean", + "/false" : "java.lang.Boolean", + "/null" : "null", + "/emptyObject" : "java.util.LinkedHashMap", + "/emptyArray" : "java.util.ArrayList", + "/nested" : "java.util.LinkedHashMap", + "/nested/array" : "java.util.ArrayList", + "/nested/array/0" : "java.lang.Integer", + "/nested/array/1" : "java.lang.String", + "/nested/array/2" : "java.util.ArrayList", + "/nested/array/2/0" : "java.lang.Integer", + "/nested/array/2/1" : "java.util.LinkedHashMap", + "/nested/array/2/1/four" : "java.lang.Double", + "/nested/array/3" : "null", + "/nested/array/4" : "java.lang.Boolean", + "/nested/array/5" : "java.lang.Long", + "/nested/object" : "java.util.LinkedHashMap", + "/nested/object/z" : "java.lang.Integer", + "/nested/object/a" : "java.util.LinkedHashMap", + "/nested/object/a/deeper" : "java.util.ArrayList", + "/nested/object/a/deeper/0" : "java.util.ArrayList", + "/nested/object/a/deeper/1" : "java.util.LinkedHashMap", + "/unicode" : "java.lang.String", + "/escapes" : "java.lang.String", + "/key with escaped name" : "java.lang.String", + "/alpha" : "java.lang.String" + }, + "keyOrder" : { + "/emptyObject" : [ ], + "/nested/array/2/1" : [ "four" ], + "/nested/object/a/deeper/1" : [ ], + "/nested/object/a" : [ "deeper" ], + "/nested/object" : [ "z", "a" ], + "/nested" : [ "array", "object" ], + "" : [ "zeta", "int", "negativeInt", "intMax", "intMaxPlusOne", "intMinMinusOne", "longMax", "longMaxPlusOne", "longMinMinusOne", "decimal", "trailingZeroDecimal", "zeroPointZero", "negativeZero", "exponent", "exponentUpperCase", "negativeExponent", "longDecimal", "true", "false", "null", "emptyObject", "emptyArray", "nested", "unicode", "escapes", "key with escaped name", "alpha" ] + } + }, + "written" : {"queryCode":"OK","data":{"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"},"success":true} } }, "executeQueryEncryptedWithInstant" : { - "request" : null, + "request" : { + "method" : "POST", + "path" : "/node-service/api/runPluginQuery", + "X-Encrypted" : [ "true" ], + "contentType" : [ "text/plain;charset=UTF-8" ], + "decrypted" : {"dataSourceConfig":{},"context":[],"pluginName":"contractPlugin","dsl":{"at":0.0}} + }, "result" : { - "error" : "org.lowcoder.sdk.exception.ServerException: Encryption error" + "queryCode" : "OK", + "dataShape" : { + "classes" : { + "" : "java.util.LinkedHashMap", + "/zeta" : "java.lang.String", + "/int" : "java.lang.Integer", + "/negativeInt" : "java.lang.Integer", + "/intMax" : "java.lang.Integer", + "/intMaxPlusOne" : "java.lang.Long", + "/intMinMinusOne" : "java.lang.Long", + "/longMax" : "java.lang.Long", + "/longMaxPlusOne" : "java.math.BigInteger", + "/longMinMinusOne" : "java.math.BigInteger", + "/decimal" : "java.lang.Double", + "/trailingZeroDecimal" : "java.lang.Double", + "/zeroPointZero" : "java.lang.Double", + "/negativeZero" : "java.lang.Integer", + "/exponent" : "java.lang.Double", + "/exponentUpperCase" : "java.lang.Double", + "/negativeExponent" : "java.lang.Double", + "/longDecimal" : "java.lang.Double", + "/true" : "java.lang.Boolean", + "/false" : "java.lang.Boolean", + "/null" : "null", + "/emptyObject" : "java.util.LinkedHashMap", + "/emptyArray" : "java.util.ArrayList", + "/nested" : "java.util.LinkedHashMap", + "/nested/array" : "java.util.ArrayList", + "/nested/array/0" : "java.lang.Integer", + "/nested/array/1" : "java.lang.String", + "/nested/array/2" : "java.util.ArrayList", + "/nested/array/2/0" : "java.lang.Integer", + "/nested/array/2/1" : "java.util.LinkedHashMap", + "/nested/array/2/1/four" : "java.lang.Double", + "/nested/array/3" : "null", + "/nested/array/4" : "java.lang.Boolean", + "/nested/array/5" : "java.lang.Long", + "/nested/object" : "java.util.LinkedHashMap", + "/nested/object/z" : "java.lang.Integer", + "/nested/object/a" : "java.util.LinkedHashMap", + "/nested/object/a/deeper" : "java.util.ArrayList", + "/nested/object/a/deeper/0" : "java.util.ArrayList", + "/nested/object/a/deeper/1" : "java.util.LinkedHashMap", + "/unicode" : "java.lang.String", + "/escapes" : "java.lang.String", + "/key with escaped name" : "java.lang.String", + "/alpha" : "java.lang.String" + }, + "keyOrder" : { + "/emptyObject" : [ ], + "/nested/array/2/1" : [ "four" ], + "/nested/object/a/deeper/1" : [ ], + "/nested/object/a" : [ "deeper" ], + "/nested/object" : [ "z", "a" ], + "/nested" : [ "array", "object" ], + "" : [ "zeta", "int", "negativeInt", "intMax", "intMaxPlusOne", "intMinMinusOne", "longMax", "longMaxPlusOne", "longMinMinusOne", "decimal", "trailingZeroDecimal", "zeroPointZero", "negativeZero", "exponent", "exponentUpperCase", "negativeExponent", "longDecimal", "true", "false", "null", "emptyObject", "emptyArray", "nested", "unicode", "escapes", "key with escaped name", "alpha" ] + } + }, + "written" : {"queryCode":"OK","data":{"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"},"success":true} } }, "test" : { @@ -254,7 +382,7 @@ "path" : "/node-service/api/validatePluginDataSourceConfig", "X-Encrypted" : [ ], "contentType" : [ "application/json" ], - "body" : {"pluginName":"contractPlugin","dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]}} + "body" : {"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"pluginName":"contractPlugin"} }, "result" : { "values" : { @@ -300,7 +428,7 @@ "path" : "/node-service/api/runPluginQuery", "X-Encrypted" : [ ], "contentType" : [ "application/json" ], - "body" : {"pluginName":"contractPlugin","dsl":{"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ůň \uD83D\uDC0E 中文","escapes":"é \u0000 \n \t \" \\ / \uD83D\uDE00","key with escaped name":"escaped key","alpha":"last key"},"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}]} + "body" : {"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}],"pluginName":"contractPlugin","dsl":{"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ůň \uD83D\uDC0E 中文","escapes":"é \u0000 \n \t \" \\ / \uD83D\uDE00","key with escaped name":"escaped key","alpha":"last key"}} }, "result" : { "queryCode" : "FAILED", @@ -319,7 +447,7 @@ "path" : "/node-service/api/runPluginQuery", "X-Encrypted" : [ "true" ], "contentType" : [ "text/plain;charset=UTF-8" ], - "decrypted" : {"pluginName":"contractPlugin","dsl":{"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"},"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}]} + "decrypted" : {"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}],"pluginName":"contractPlugin","dsl":{"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"}} }, "result" : { "queryCode" : "FAILED", @@ -333,15 +461,41 @@ } }, "executeQueryWithInstant" : { - "request" : null, + "request" : { + "method" : "POST", + "path" : "/node-service/api/runPluginQuery", + "X-Encrypted" : [ ], + "contentType" : [ "application/json" ], + "body" : {"dataSourceConfig":{},"context":[],"pluginName":"contractPlugin","dsl":{"at":0.0}} + }, "result" : { - "error" : "org.lowcoder.sdk.exception.ServerException: Encryption error" + "queryCode" : "FAILED", + "dataShape" : { + "classes" : { + "" : "null" + }, + "keyOrder" : { } + }, + "written" : {"queryCode":"FAILED","message":"bad \"q\" žluť","success":false} } }, "executeQueryEncryptedWithInstant" : { - "request" : null, + "request" : { + "method" : "POST", + "path" : "/node-service/api/runPluginQuery", + "X-Encrypted" : [ "true" ], + "contentType" : [ "text/plain;charset=UTF-8" ], + "decrypted" : {"dataSourceConfig":{},"context":[],"pluginName":"contractPlugin","dsl":{"at":0.0}} + }, "result" : { - "error" : "org.lowcoder.sdk.exception.ServerException: Encryption error" + "queryCode" : "FAILED", + "dataShape" : { + "classes" : { + "" : "null" + }, + "keyOrder" : { } + }, + "written" : {"queryCode":"FAILED","message":"bad \"q\" žluť","success":false} } }, "test" : { @@ -350,7 +504,7 @@ "path" : "/node-service/api/validatePluginDataSourceConfig", "X-Encrypted" : [ ], "contentType" : [ "application/json" ], - "body" : {"pluginName":"contractPlugin","dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]}} + "body" : {"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"pluginName":"contractPlugin"} }, "result" : { "values" : { @@ -403,7 +557,7 @@ "path" : "/node-service/api/runPluginQuery", "X-Encrypted" : [ ], "contentType" : [ "application/json" ], - "body" : {"pluginName":"contractPlugin","dsl":{"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ůň \uD83D\uDC0E 中文","escapes":"é \u0000 \n \t \" \\ / \uD83D\uDE00","key with escaped name":"escaped key","alpha":"last key"},"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}]} + "body" : {"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}],"pluginName":"contractPlugin","dsl":{"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ůň \uD83D\uDC0E 中文","escapes":"é \u0000 \n \t \" \\ / \uD83D\uDE00","key with escaped name":"escaped key","alpha":"last key"}} }, "result" : { "queryCode" : "OK", @@ -422,7 +576,7 @@ "path" : "/node-service/api/runPluginQuery", "X-Encrypted" : [ "true" ], "contentType" : [ "text/plain;charset=UTF-8" ], - "decrypted" : {"pluginName":"contractPlugin","dsl":{"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"},"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}]} + "decrypted" : {"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"context":[{"key":"limit","value":3000000001}],"pluginName":"contractPlugin","dsl":{"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"}} }, "result" : { "queryCode" : "OK", @@ -436,15 +590,41 @@ } }, "executeQueryWithInstant" : { - "request" : null, + "request" : { + "method" : "POST", + "path" : "/node-service/api/runPluginQuery", + "X-Encrypted" : [ ], + "contentType" : [ "application/json" ], + "body" : {"dataSourceConfig":{},"context":[],"pluginName":"contractPlugin","dsl":{"at":0.0}} + }, "result" : { - "error" : "org.lowcoder.sdk.exception.ServerException: Encryption error" + "queryCode" : "OK", + "dataShape" : { + "classes" : { + "" : "java.lang.String" + }, + "keyOrder" : { } + }, + "written" : {"queryCode":"OK","data":"text","success":true} } }, "executeQueryEncryptedWithInstant" : { - "request" : null, + "request" : { + "method" : "POST", + "path" : "/node-service/api/runPluginQuery", + "X-Encrypted" : [ "true" ], + "contentType" : [ "text/plain;charset=UTF-8" ], + "decrypted" : {"dataSourceConfig":{},"context":[],"pluginName":"contractPlugin","dsl":{"at":0.0}} + }, "result" : { - "error" : "org.lowcoder.sdk.exception.ServerException: Encryption error" + "queryCode" : "OK", + "dataShape" : { + "classes" : { + "" : "java.lang.String" + }, + "keyOrder" : { } + }, + "written" : {"queryCode":"OK","data":"text","success":true} } }, "test" : { @@ -453,7 +633,7 @@ "path" : "/node-service/api/validatePluginDataSourceConfig", "X-Encrypted" : [ ], "contentType" : [ "application/json" ], - "body" : {"pluginName":"contractPlugin","dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]}} + "body" : {"dataSourceConfig":{"host":"žluť \"db\"","port":5432,"ratio":1.50,"tags":["a",null]},"pluginName":"contractPlugin"} }, "result" : { "values" : { diff --git a/server/api-service/lowcoder-infra/pom.xml b/server/api-service/lowcoder-infra/pom.xml index 0f04964c99..9a54a2336f 100644 --- a/server/api-service/lowcoder-infra/pom.xml +++ b/server/api-service/lowcoder-infra/pom.xml @@ -89,11 +89,6 @@ commons-collections4 - - com.fasterxml.jackson.module - jackson-module-parameter-names - - com.google.guava guava diff --git a/server/api-service/lowcoder-infra/src/main/java/org/lowcoder/infra/localcache/ReloadableCache.java b/server/api-service/lowcoder-infra/src/main/java/org/lowcoder/infra/localcache/ReloadableCache.java index 64171ada3e..c64a147fa3 100644 --- a/server/api-service/lowcoder-infra/src/main/java/org/lowcoder/infra/localcache/ReloadableCache.java +++ b/server/api-service/lowcoder-infra/src/main/java/org/lowcoder/infra/localcache/ReloadableCache.java @@ -7,7 +7,7 @@ import org.lowcoder.sdk.destructor.DestructorUtil; import reactor.core.publisher.Mono; -import javax.annotation.CheckReturnValue; +import com.google.errorprone.annotations.CheckReturnValue; import java.time.Duration; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; diff --git a/server/api-service/lowcoder-infra/src/main/java/org/lowcoder/infra/util/NetworkUtils.java b/server/api-service/lowcoder-infra/src/main/java/org/lowcoder/infra/util/NetworkUtils.java index d912f08523..39ca6e5109 100644 --- a/server/api-service/lowcoder-infra/src/main/java/org/lowcoder/infra/util/NetworkUtils.java +++ b/server/api-service/lowcoder-infra/src/main/java/org/lowcoder/infra/util/NetworkUtils.java @@ -2,6 +2,7 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; +import org.lowcoder.sdk.util.HttpHeaderMaps; import org.lowcoder.sdk.util.JsonUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.server.reactive.ServerHttpRequest; @@ -23,14 +24,14 @@ public static String getRemoteIp(ServerWebExchange serverWebExchange) { /** Try to find remote id in headers **/ String foundHeader; for (String header : CLIENT_IP_HEADERS) { - foundHeader = getMatchingKey(header, headers.keySet()); + foundHeader = getMatchingKey(header, headers.headerNames()); if (foundHeader != null) { log.debug("Found client IP in header: {}", foundHeader); return headers.getFirst(foundHeader); } } - log.debug("get remote ip from remoteAddress , header {}", JsonUtils.toJson(headers)); + log.debug("get remote ip from remoteAddress , header {}", JsonUtils.toJson(HttpHeaderMaps.copyOf(headers))); return Optional.ofNullable(serverWebExchange.getRequest().getRemoteAddress()) .map(InetSocketAddress::getAddress) .map(InetAddress::getHostAddress) diff --git a/server/api-service/lowcoder-plugins/clickHousePlugin/pom.xml b/server/api-service/lowcoder-plugins/clickHousePlugin/pom.xml index 6942d0d5e3..da56d29611 100644 --- a/server/api-service/lowcoder-plugins/clickHousePlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/clickHousePlugin/pom.xml @@ -15,9 +15,6 @@ UTF-8 - 17 - ${java.version} - ${java.version} clickHouse-plugin org.lowcoder.plugin.clickhouse.ClickHousePlugin ${revision} @@ -29,7 +26,7 @@ com.zaxxer HikariCP - 5.0.1 + 7.1.0 org.slf4j @@ -42,7 +39,7 @@ com.clickhouse clickhouse-jdbc - 0.3.2-patch11 + 0.11.2 all @@ -68,7 +65,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/clickHousePlugin/src/main/java/org/lowcoder/plugin/clickhouse/ClickHouseConnector.java b/server/api-service/lowcoder-plugins/clickHousePlugin/src/main/java/org/lowcoder/plugin/clickhouse/ClickHouseConnector.java index 6bb47a2f1f..6cf83f7658 100644 --- a/server/api-service/lowcoder-plugins/clickHousePlugin/src/main/java/org/lowcoder/plugin/clickhouse/ClickHouseConnector.java +++ b/server/api-service/lowcoder-plugins/clickHousePlugin/src/main/java/org/lowcoder/plugin/clickhouse/ClickHouseConnector.java @@ -3,6 +3,9 @@ import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.pool.HikariPool.PoolInitializationException; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; import jakarta.annotation.Nonnull; import org.apache.commons.lang3.StringUtils; import org.lowcoder.plugin.clickhouse.model.ClickHouseDatasourceConfig; @@ -28,6 +31,7 @@ @Extension public class ClickHouseConnector implements DatasourceConnector { + private static final String VALIDATION_QUERY = "SELECT 1"; private static final String JDBC_DRIVER = "com.clickhouse.jdbc.ClickHouseDriver"; private static final long LEAK_DETECTION_THRESHOLD_MS = Duration.ofSeconds(30).toMillis(); private static final long MAX_LIFETIME_MS = TimeUnit.HOURS.toMillis(2); @@ -159,9 +163,8 @@ private HikariDataSource createHikariDataSource(ClickHouseDatasourceConfig datas String url = "jdbc:clickhouse:" + scheme + host + ":" + port + "/" + database; config.setJdbcUrl(url); - config.addDataSourceProperty("characterEncoding", "UTF-8"); - config.addDataSourceProperty("useUnicode", "true"); - + // No characterEncoding / useUnicode: they are MySQL driver properties that the 0.3 ClickHouse driver ignored and + // the 0.11 driver refuses ("Unknown and unmapped config properties"); the HTTP interface is UTF-8 anyway. config.setReadOnly(datasourceConfig.isReadonly()); HikariDataSource datasource; @@ -171,6 +174,15 @@ private HikariDataSource createHikariDataSource(ClickHouseDatasourceConfig datas throw new PluginException(DATASOURCE_ARGUMENT_ERROR, "DATASOURCE_ARGUMENT_ERROR", e.getMessage()); } + // The 0.11 driver connects lazily: a wrong password, a closed port or https against the HTTP port no longer fails + // the pool initialization, so the data source is checked with one query here, as the pool initialization did before. + try (Connection connection = datasource.getConnection(); Statement statement = connection.createStatement()) { + statement.execute(VALIDATION_QUERY); + } catch (SQLException | RuntimeException e) { + datasource.close(); + throw new PluginException(DATASOURCE_ARGUMENT_ERROR, "DATASOURCE_ARGUMENT_ERROR", e.getMessage()); + } + return datasource; } diff --git a/server/api-service/lowcoder-plugins/clickHousePlugin/src/main/java/org/lowcoder/plugin/clickhouse/ClickHouseQueryExecutor.java b/server/api-service/lowcoder-plugins/clickHousePlugin/src/main/java/org/lowcoder/plugin/clickhouse/ClickHouseQueryExecutor.java index b1b57ac9a0..6e4b722ef6 100644 --- a/server/api-service/lowcoder-plugins/clickHousePlugin/src/main/java/org/lowcoder/plugin/clickhouse/ClickHouseQueryExecutor.java +++ b/server/api-service/lowcoder-plugins/clickHousePlugin/src/main/java/org/lowcoder/plugin/clickhouse/ClickHouseQueryExecutor.java @@ -153,7 +153,7 @@ private QueryExecutionResult executeQuery0(HikariDataSource hikariDataSource, St resultSet = preparedQuery.getResultSet(); } else { statement = connection.createStatement(); - isResultSet = statement.execute(renderMustacheString(query, requestParams), Statement.RETURN_GENERATED_KEYS); + isResultSet = statement.execute(renderMustacheString(query, requestParams)); resultSet = statement.getResultSet(); } diff --git a/server/api-service/lowcoder-plugins/elasticSearchPlugin/pom.xml b/server/api-service/lowcoder-plugins/elasticSearchPlugin/pom.xml index 9cb60c2951..8c78f044e3 100644 --- a/server/api-service/lowcoder-plugins/elasticSearchPlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/elasticSearchPlugin/pom.xml @@ -16,9 +16,6 @@ UTF-8 - 17 - ${java.version} - ${java.version} es-plugin org.lowcoder.plugin.es.EsPlugin ${revision} @@ -31,7 +28,7 @@ org.elasticsearch.client elasticsearch-rest-client - 8.2.3 + 9.5.7 @@ -50,7 +47,7 @@ io.projectreactor.tools blockhound - 1.0.6.RELEASE + 1.0.19.RELEASE test @@ -61,7 +58,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/googleSheetsPlugin/pom.xml b/server/api-service/lowcoder-plugins/googleSheetsPlugin/pom.xml index e50a0dbe63..4cc7f9c4c1 100644 --- a/server/api-service/lowcoder-plugins/googleSheetsPlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/googleSheetsPlugin/pom.xml @@ -16,9 +16,6 @@ UTF-8 - 17 - ${java.version} - ${java.version} googleSheets-plugin org.lowcoder.plugin.googlesheets.GoogleSheetsPlugin ${revision} @@ -31,17 +28,17 @@ com.google.api-client google-api-client - 1.31.2 + 2.9.2 com.google.oauth-client google-oauth-client-jetty - 1.30.6 + 1.39.0 com.google.auth google-auth-library-oauth2-http - 1.3.0 + 1.58.0 com.google.apis @@ -54,20 +51,19 @@ org.assertj assertj-core - 3.13.2 + 3.27.7 test org.springframework.boot spring-boot-starter-webflux - 3.0.6 test com.google.guava guava - 31.1-jre + 33.8.0-jre compile @@ -79,7 +75,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/graphqlPlugin/pom.xml b/server/api-service/lowcoder-plugins/graphqlPlugin/pom.xml index c99123a1c2..fb18e5e9f6 100644 --- a/server/api-service/lowcoder-plugins/graphqlPlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/graphqlPlugin/pom.xml @@ -16,9 +16,6 @@ UTF-8 - 17 - ${java.version} - ${java.version} graphql-plugin org.lowcoder.plugin.graphql.GraphQLPlugin ${revision} @@ -47,32 +44,20 @@ - com.fasterxml.jackson.core + tools.jackson.core jackson-databind provided - - com.fasterxml.jackson.datatype - jackson-datatype-jdk8 - provided - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - provided - - io.jsonwebtoken jjwt-api - 0.11.2 + 0.13.0 io.jsonwebtoken jjwt-impl - 0.11.2 + 0.13.0 io.jsonwebtoken @@ -83,20 +68,18 @@ org.assertj assertj-core - 3.13.2 + 3.27.7 test org.springframework.boot spring-boot-starter-webflux - 3.0.6 test org.springframework spring-test - 6.0.10 test @@ -117,7 +100,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/GraphQLExecutor.java b/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/GraphQLExecutor.java index 1ba1886a71..4145e20a9b 100644 --- a/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/GraphQLExecutor.java +++ b/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/GraphQLExecutor.java @@ -1,8 +1,7 @@ package org.lowcoder.plugin.graphql; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableMap; import jakarta.annotation.Nullable; import lombok.Builder; @@ -28,24 +27,25 @@ import org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType; import org.lowcoder.sdk.query.QueryVisitorContext; import org.lowcoder.sdk.util.CookieForwarding; +import org.lowcoder.sdk.util.HttpHeaderMaps; import org.lowcoder.sdk.util.JsonUtils; import org.lowcoder.sdk.util.MoreMapUtils; import org.lowcoder.sdk.util.MustacheHelper; import org.lowcoder.sdk.webclient.WebClientBuildHelper; import org.lowcoder.sdk.webclient.WebClientRedirects; +import org.lowcoder.sdk.webclient.JacksonClientCodecs; import org.pf4j.Extension; import org.springframework.http.*; import org.springframework.http.client.reactive.ClientHttpRequest; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserter; import org.springframework.web.reactive.function.BodyInserters; -import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.ExchangeStrategies; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; +import tools.jackson.core.JacksonException; -import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; @@ -53,6 +53,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -87,7 +88,10 @@ public class GraphQLExecutor implements QueryExecutor configurer.defaultCodecs().maxInMemorySize(10 * 1024 * 1024)) + .codecs(configurer -> { + JacksonClientCodecs.apply(configurer); + configurer.defaultCodecs().maxInMemorySize(10 * 1024 * 1024); + }) .build(); private final Scheduler scheduler = QueryExecutionUtils.querySharedScheduler(); private final DataUtils dataUtils = DataUtils.getInstance(); @@ -278,7 +282,6 @@ public Mono executeQuery(Object o, GraphQLQueryExecutionCo context.getQueryBody(), context.getBodyParams()); return httpCall(client, context.getHttpMethod(), uri, bodyInserter, 0, authConfig, DEFAULT_HEADERS_CONSUMER, false) - .flatMap(clientResponse -> clientResponse.toEntity(byte[].class)) .map(this::convertToQueryExecutionResult) .onErrorResume(error -> { if (error instanceof TimeoutException) { @@ -309,7 +312,7 @@ private Consumer> injectCookies(GraphQLQueryExecut * Limits: the flag is not kept per URI, so a redirect back to an answered URI is answered again (within MAX_REDIRECTS); * a challenge with {@code stale=true} (an expired nonce, right credentials) is not answered a second time; it gets the 401. */ - private Mono httpCall(WebClient webClient, HttpMethod httpMethod, + private Mono> httpCall(WebClient webClient, HttpMethod httpMethod, URI uri, BodyInserter requestBody, int iteration, @@ -320,44 +323,49 @@ private Mono httpCall(WebClient webClient, HttpMethod httpMethod return Mono.error(new PluginException(QUERY_EXECUTION_ERROR, "REACH_REDIRECT_LIMIT", MAX_REDIRECTS)); } - return webClient - .method(httpMethod) - .uri(uri) - .headers(headersConsumer) - .body(requestBody) - .exchange() - .onErrorMap(e -> new PluginException(QUERY_EXECUTION_ERROR, "QUERY_EXECUTION_ERROR", e.getMessage())) - .flatMap(response -> { - String redirectUrl = WebClientRedirects.redirectLocation(response); // BF-113: null for a 3xx without a Location - if (redirectUrl != null) { - URI redirectUri; - try { - redirectUri = WebClientRedirects.resolveLocation(uri, redirectUrl); - } catch (URISyntaxException e) { - return Mono.error(new PluginException(QUERY_EXECUTION_ERROR, "QUERY_EXECUTION_ERROR", - e.getMessage())); + // Only a failure before the response arrives is wrapped; what follows (a redirect, a digest answer, reading the + // body) reports its own error, as the nested call has already wrapped its own. + return Mono.defer(() -> { + AtomicBoolean responseReceived = new AtomicBoolean(); + return webClient + .method(httpMethod) + .uri(uri) + .headers(headersConsumer) + .body(requestBody) + .exchangeToMono(response -> { + responseReceived.set(true); + String redirectUrl = WebClientRedirects.redirectLocation(response); // BF-113: null for a 3xx without a Location + if (redirectUrl != null) { + URI redirectUri; + try { + redirectUri = WebClientRedirects.resolveLocation(uri, redirectUrl); + } catch (URISyntaxException e) { + return Mono.>error(new PluginException(QUERY_EXECUTION_ERROR, + "QUERY_EXECUTION_ERROR", e.getMessage())); + } + if (WebClientRedirects.isSameOrigin(uri, redirectUri)) { + return httpCall(webClient, httpMethod, redirectUri, requestBody, iteration + 1, authConfig, headersConsumer, false); + } + // another origin: only content headers, no forwarded cookies, no digest answer + return httpCall(WebClientRedirects.forAnotherOrigin(webClient), httpMethod, redirectUri, requestBody, + iteration + 1, null, DEFAULT_HEADERS_CONSUMER, false); } - if (WebClientRedirects.isSameOrigin(uri, redirectUri)) { - return httpCall(webClient, httpMethod, redirectUri, requestBody, iteration + 1, authConfig, headersConsumer, false); + //digest auth + if (!digestAnswered && authConfig != null && authConfig.getType() == DIGEST_AUTH && AuthHelper.shouldDigestAuth(response)) { + try { + return httpCall(webClient, httpMethod, uri, requestBody, iteration + 1, authConfig, + headersConsumer.andThen( + AuthHelper.digestAuth((BasicAuthConfig) authConfig, response, httpMethod, uri.getPath())), true); + } catch (ParseException e) { + return Mono.>error(new PluginException(QUERY_EXECUTION_ERROR, + "QUERY_EXECUTION_ERROR", e.getMessage())); + } } - // another origin: only content headers, no forwarded cookies, no digest answer - return httpCall(WebClientRedirects.forAnotherOrigin(webClient), httpMethod, redirectUri, requestBody, - iteration + 1, null, DEFAULT_HEADERS_CONSUMER, false); - } - //digest auth - if (!digestAnswered && authConfig != null && authConfig.getType() == DIGEST_AUTH && AuthHelper.shouldDigestAuth(response)) { - try { - return httpCall(webClient, httpMethod, uri, requestBody, iteration + 1, authConfig, - headersConsumer.andThen( - AuthHelper.digestAuth((BasicAuthConfig) authConfig, response, httpMethod, uri.getPath())), true); - } catch (ParseException e) { - return Mono.error(new PluginException(QUERY_EXECUTION_ERROR, "QUERY_EXECUTION_ERROR", - e.getMessage())); - } - } - return Mono.just(response); - }) - .subscribeOn(scheduler); + return response.toEntity(byte[].class); + }) + .onErrorMap(e -> !responseReceived.get(), + e -> new PluginException(QUERY_EXECUTION_ERROR, "QUERY_EXECUTION_ERROR", e.getMessage())); + }).subscribeOn(scheduler); } private QueryExecutionResult convertToQueryExecutionResult(ResponseEntity stringResponseEntity) { @@ -383,15 +391,15 @@ private JsonNode parseExecuteResultHeaders(HttpHeaders headers) { // Convert the headers into json tree to store in the results String headerInJsonString; try { - headerInJsonString = toJsonThrows(headers); - } catch (JsonProcessingException e) { + headerInJsonString = toJsonThrows(HttpHeaderMaps.copyOf(headers)); + } catch (JacksonException e) { throw new PluginException(QUERY_EXECUTION_ERROR, "QUERY_EXECUTION_ERROR", e.getMessage()); } // Set headers in the result now try { return (readTree(headerInJsonString)); - } catch (IOException e) { + } catch (JacksonException e) { throw new PluginException(JSON_PARSE_ERROR, "JSON_PARSE_ERROR", headerInJsonString, e.getMessage()); } } @@ -405,7 +413,7 @@ private ResponseBodyData parseResponseDataInfo(byte[] body, MediaType contentTyp .dataType(ResponseDataType.JSON) .build(); - } catch (IOException e) { + } catch (JacksonException e) { throw new PluginException(GRAPHQL_EXECUTION_ERROR, "INVALID_JSON_FROM_RESPONSE"); } } diff --git a/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/model/GraphQLQueryExecutionContext.java b/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/model/GraphQLQueryExecutionContext.java index f3f10d4d3e..2840b822a8 100644 --- a/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/model/GraphQLQueryExecutionContext.java +++ b/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/model/GraphQLQueryExecutionContext.java @@ -1,6 +1,6 @@ package org.lowcoder.plugin.graphql.model; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import jakarta.annotation.Nullable; import lombok.Builder; import lombok.Getter; diff --git a/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/utils/GraphQLBodyUtils.java b/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/utils/GraphQLBodyUtils.java index b4768334a1..16173cde94 100644 --- a/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/utils/GraphQLBodyUtils.java +++ b/server/api-service/lowcoder-plugins/graphqlPlugin/src/main/java/org/lowcoder/plugin/graphql/utils/GraphQLBodyUtils.java @@ -5,7 +5,7 @@ import org.lowcoder.plugin.graphql.model.GraphQLQueryExecutionContext; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; public class GraphQLBodyUtils { diff --git a/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/java/org/lowcoder/plugin/graphql/GraphQLConnectionFailureTest.java b/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/java/org/lowcoder/plugin/graphql/GraphQLConnectionFailureTest.java new file mode 100644 index 0000000000..2bd910d3eb --- /dev/null +++ b/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/java/org/lowcoder/plugin/graphql/GraphQLConnectionFailureTest.java @@ -0,0 +1,40 @@ +package org.lowcoder.plugin.graphql; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.lowcoder.sdk.contract.RecordingHttpServer; +import org.lowcoder.sdk.exception.PluginException; +import org.lowcoder.sdk.plugin.graphql.GraphQLDatasourceConfig; + +/** + * A request that fails before any answer arrives (the connection is refused) is reported as a {@link PluginException} + * with the message key {@code QUERY_EXECUTION_ERROR} and the cause's text, which {@code executeQuery} rethrows as it is. + * An error after an answer (an unreadable body) is not wrapped: {@code GraphQLUnreadableAnswerTest} pins that case. + */ +class GraphQLConnectionFailureTest { + + private static final String PATH = "/graphql"; + private static final String QUERY_EXECUTION_ERROR_KEY = "QUERY_EXECUTION_ERROR"; + + private final GraphQLCallSupport support = new GraphQLCallSupport(); + + @Test + void aRefusedConnectionIsAQueryExecutionPluginException() { + String closedUrl; + try (RecordingHttpServer server = RecordingHttpServer.start(Map.of())) { + closedUrl = server.baseUrl() + PATH; + } + GraphQLDatasourceConfig datasource = GraphQLDatasourceConfig.builder().url(closedUrl).build(); + + Throwable failure = support.failureOf(datasource, GraphQLCallSupport.query(), GraphQLCallSupport.visitor(null, null)); + + System.out.println("[GraphQLConnectionFailureTest] " + closedUrl + " -> " + failure); + assertThat(failure).as("the error of a refused connection to " + closedUrl).isInstanceOf(PluginException.class); + PluginException pluginException = (PluginException) failure; + assertThat(pluginException.getMessageKey()).as("message key of the wrapped connection error").isEqualTo(QUERY_EXECUTION_ERROR_KEY); + assertThat(pluginException.getMessage()).as("the cause's text is in the message").isNotBlank(); + } +} diff --git a/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/java/org/lowcoder/plugin/graphql/GraphQLHttpsTest.java b/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/java/org/lowcoder/plugin/graphql/GraphQLHttpsTest.java new file mode 100644 index 0000000000..1d832ad095 --- /dev/null +++ b/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/java/org/lowcoder/plugin/graphql/GraphQLHttpsTest.java @@ -0,0 +1,121 @@ +package org.lowcoder.plugin.graphql; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.lowcoder.sdk.contract.RecordingHttpServer; +import org.lowcoder.sdk.contract.RecordingHttpServer.Response; +import org.lowcoder.sdk.contract.SelfSignedCertificate; +import org.lowcoder.sdk.exception.PluginException; +import org.lowcoder.sdk.plugin.graphql.GraphQLDatasourceConfig; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The GraphQL executor against an HTTPS server with a self-signed certificate generated in the test + * ({@link SelfSignedCertificate}, {@link RecordingHttpServer#startSecure}). The GraphQL datasource has no SSL setting (unlike + * the REST API datasource: {@code GraphQLDatasourceConfig} has no {@code sslConfig}, and {@code GraphQLExecutor} builds its + * WebClient without one), so the only mode is the JDK's default trust. The tests pin what that means: a self-signed server is + * refused in the handshake and reaches no handler, also when the client sends the REST API datasource's + * {@code sslConfig} with {@code DISABLED} (it is ignored, not applied); and the same server over plain HTTP, the control + * of the same query on a {@link RecordingHttpServer}, is answered, so the refusal is the certificate's and not the query's. + * + *

Limits: no CA-signed certificate (the default trust is shown only by its refusal), no client certificate. + */ +public class GraphQLHttpsTest { + + static final String TAG = "[GraphQLHttpsTest] "; + static final String PATH = "/graphql"; + static final String ANSWER_JSON = "{\"data\":{\"hero\":{\"name\":\"R2-D2\"}}}"; + static final String URL_KEY = "url"; + static final String SSL_KEY = "sslConfig"; + static final String TYPE_KEY = "sslCertVerificationType"; + static final String DISABLED = "DISABLED"; + static final int OK = 200; + + @TempDir + static Path directory; + private static RecordingHttpServer secure; + private static RecordingHttpServer plain; + + private final GraphQLCallSupport calls = new GraphQLCallSupport(); + + @BeforeAll + static void startServers() { + SelfSignedCertificate certificate = SelfSignedCertificate.generate(directory, "graphql"); + Response answer = new Response(OK, Map.of("Content-Type", List.of("application/json")), ANSWER_JSON.getBytes(StandardCharsets.UTF_8)); + secure = RecordingHttpServer.startSecure(certificate.serverContext(), Map.of(PATH, answer)); + plain = RecordingHttpServer.start(Map.of(PATH, answer)); + System.out.println(TAG + "HTTPS server on " + secure.baseUrl() + ", HTTP control on " + plain.baseUrl()); + } + + @AfterAll + static void stopServers() { + secure.close(); + plain.close(); + } + + private static GraphQLDatasourceConfig datasource(RecordingHttpServer server, Map sslConfig) { + Map map = new HashMap<>(); + map.put(URL_KEY, server.baseUrl()); + if (sslConfig != null) { + map.put(SSL_KEY, sslConfig); + } + return GraphQLDatasourceConfig.buildFrom(map); + } + + private Throwable failureOver(Map sslConfig) { + Throwable failure = calls.failureOf(datasource(secure, sslConfig), GraphQLCallSupport.query(Map.of("path", PATH)), + GraphQLCallSupport.visitor(null, null)); + System.out.println(TAG + "sslConfig=" + sslConfig + " -> " + failure); + return failure; + } + + private static boolean causedByHandshake(Throwable failure) { + for (Throwable t = failure; t != null; t = t.getCause()) { + String text = t.getClass().getName() + " " + t.getMessage(); + if (text.contains("SSLHandshakeException") || text.contains("SSLException") || text.contains("PKIX") || text.contains("certificate")) { + return true; + } + } + return false; + } + + @Test + public void aSelfSignedServerIsRefusedByTheDefaultTrust() { + int before = secure.requests().size(); + Throwable failure = failureOver(null); + assertInstanceOf(Throwable.class, failure, "the call must fail"); + assertInstanceOf(PluginException.class, failure, "mapped to a PluginException: " + failure); + assertTrue(causedByHandshake(failure), "the failure names the TLS handshake: " + failure + " / " + failure.getCause()); + assertEquals(before, secure.requests().size(), "a refused handshake reaches no handler"); + } + + @Test + public void anSslConfigThatDisablesVerificationIsIgnoredBecauseTheDatasourceHasNoSslMode() { + int before = secure.requests().size(); + Throwable failure = failureOver(Map.of(TYPE_KEY, DISABLED)); + assertInstanceOf(Throwable.class, failure, "DISABLED must not make the call succeed: the GraphQL datasource has no SSL setting"); + assertTrue(causedByHandshake(failure), "still a handshake failure: " + failure + " / " + failure.getCause()); + assertEquals(before, secure.requests().size(), "no request passed the handshake"); + } + + @Test + public void theSameQueryOverPlainHttpIsAnswered() { + var result = calls.run(datasource(plain, null), GraphQLCallSupport.query(Map.of("path", PATH)), GraphQLCallSupport.visitor(null, null)); + System.out.println(TAG + "plain HTTP control -> " + result.getQueryCode() + " " + result.getData()); + assertTrue(result.isSuccess(), "the control query succeeds: " + result); + assertTrue(String.valueOf(result.getData()).contains("R2-D2"), "the answer body is returned: " + result.getData()); + assertEquals(1, plain.requests().size(), "one request reached the HTTP server"); + assertEquals("POST", plain.requests().get(0).method()); + } +} diff --git a/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/java/org/lowcoder/plugin/graphql/GraphQLRedirectWithoutLocationTest.java b/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/java/org/lowcoder/plugin/graphql/GraphQLRedirectWithoutLocationTest.java index eb13d9f3fd..ee7559fe92 100644 --- a/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/java/org/lowcoder/plugin/graphql/GraphQLRedirectWithoutLocationTest.java +++ b/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/java/org/lowcoder/plugin/graphql/GraphQLRedirectWithoutLocationTest.java @@ -15,7 +15,7 @@ import org.lowcoder.sdk.plugin.graphql.GraphQLDatasourceConfig; import org.springframework.http.HttpStatus; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import com.google.common.collect.Streams; /** @@ -69,7 +69,7 @@ private static Response answer(int status, Map> headers) { /** The values of the result header named {@code name}, compared without case (the test server normalizes names). */ private static JsonNode header(QueryExecutionResult result, String name) { JsonNode headers = result.getHeaders(); - return Streams.stream(headers.fieldNames()).filter(name::equalsIgnoreCase).findFirst().map(headers::get).orElse(null); + return Streams.stream(headers.propertyNames().iterator()).filter(name::equalsIgnoreCase).findFirst().map(headers::get).orElse(null); } private void assertOrdinaryAnswer(int status, Response response) { @@ -84,10 +84,10 @@ private void assertOrdinaryAnswer(int status, Response response) { assertThat(result.getQueryCode()).isEqualTo(HTTP_CODE_PREFIX + HttpStatus.valueOf(status).name()); assertThat(server.requests()).hasSize(1); assertThat(header(result, ANSWER_HEADER)).as("the answer's headers").isNotNull(); - assertThat(header(result, ANSWER_HEADER).get(0).asText()).isEqualTo(ANSWER_HEADER_VALUE); + assertThat(header(result, ANSWER_HEADER).get(0).asString()).isEqualTo(ANSWER_HEADER_VALUE); if (status != NOT_MODIFIED) { assertThat(result.getData()).as("the answer's body").isInstanceOf(JsonNode.class); - assertThat(((JsonNode) result.getData()).get(ANSWER_FIELD).asText()).isEqualTo(ANSWER_HEADER_VALUE); + assertThat(((JsonNode) result.getData()).get(ANSWER_FIELD).asString()).isEqualTo(ANSWER_HEADER_VALUE); } } } diff --git a/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/resources/json-contract/external-json/GraphQLExecutor.responses.json b/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/resources/json-contract/external-json/GraphQLExecutor.responses.json index 4017ff7447..685f27982e 100644 --- a/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/resources/json-contract/external-json/GraphQLExecutor.responses.json +++ b/server/api-service/lowcoder-plugins/graphqlPlugin/src/test/resources/json-contract/external-json/GraphQLExecutor.responses.json @@ -11,51 +11,51 @@ }, "dataShape" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/data" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/data/zeta" : "com.fasterxml.jackson.databind.node.TextNode", - "/data/int" : "com.fasterxml.jackson.databind.node.IntNode", - "/data/negativeInt" : "com.fasterxml.jackson.databind.node.IntNode", - "/data/intMax" : "com.fasterxml.jackson.databind.node.IntNode", - "/data/intMaxPlusOne" : "com.fasterxml.jackson.databind.node.LongNode", - "/data/intMinMinusOne" : "com.fasterxml.jackson.databind.node.LongNode", - "/data/longMax" : "com.fasterxml.jackson.databind.node.LongNode", - "/data/longMaxPlusOne" : "com.fasterxml.jackson.databind.node.BigIntegerNode", - "/data/longMinMinusOne" : "com.fasterxml.jackson.databind.node.BigIntegerNode", - "/data/decimal" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/data/trailingZeroDecimal" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/data/zeroPointZero" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/data/negativeZero" : "com.fasterxml.jackson.databind.node.IntNode", - "/data/exponent" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/data/exponentUpperCase" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/data/negativeExponent" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/data/longDecimal" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/data/true" : "com.fasterxml.jackson.databind.node.BooleanNode", - "/data/false" : "com.fasterxml.jackson.databind.node.BooleanNode", - "/data/null" : "com.fasterxml.jackson.databind.node.NullNode", - "/data/emptyObject" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/data/emptyArray" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/data/nested" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/data/nested/array" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/data/nested/array/0" : "com.fasterxml.jackson.databind.node.IntNode", - "/data/nested/array/1" : "com.fasterxml.jackson.databind.node.TextNode", - "/data/nested/array/2" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/data/nested/array/2/0" : "com.fasterxml.jackson.databind.node.IntNode", - "/data/nested/array/2/1" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/data/nested/array/2/1/four" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/data/nested/array/3" : "com.fasterxml.jackson.databind.node.NullNode", - "/data/nested/array/4" : "com.fasterxml.jackson.databind.node.BooleanNode", - "/data/nested/array/5" : "com.fasterxml.jackson.databind.node.LongNode", - "/data/nested/object" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/data/nested/object/z" : "com.fasterxml.jackson.databind.node.IntNode", - "/data/nested/object/a" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/data/nested/object/a/deeper" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/data/nested/object/a/deeper/0" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/data/nested/object/a/deeper/1" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/data/unicode" : "com.fasterxml.jackson.databind.node.TextNode", - "/data/escapes" : "com.fasterxml.jackson.databind.node.TextNode", - "/data/key with escaped name" : "com.fasterxml.jackson.databind.node.TextNode", - "/data/alpha" : "com.fasterxml.jackson.databind.node.TextNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/data" : "tools.jackson.databind.node.ObjectNode", + "/data/zeta" : "tools.jackson.databind.node.StringNode", + "/data/int" : "tools.jackson.databind.node.IntNode", + "/data/negativeInt" : "tools.jackson.databind.node.IntNode", + "/data/intMax" : "tools.jackson.databind.node.IntNode", + "/data/intMaxPlusOne" : "tools.jackson.databind.node.LongNode", + "/data/intMinMinusOne" : "tools.jackson.databind.node.LongNode", + "/data/longMax" : "tools.jackson.databind.node.LongNode", + "/data/longMaxPlusOne" : "tools.jackson.databind.node.BigIntegerNode", + "/data/longMinMinusOne" : "tools.jackson.databind.node.BigIntegerNode", + "/data/decimal" : "tools.jackson.databind.node.DoubleNode", + "/data/trailingZeroDecimal" : "tools.jackson.databind.node.DoubleNode", + "/data/zeroPointZero" : "tools.jackson.databind.node.DoubleNode", + "/data/negativeZero" : "tools.jackson.databind.node.IntNode", + "/data/exponent" : "tools.jackson.databind.node.DoubleNode", + "/data/exponentUpperCase" : "tools.jackson.databind.node.DoubleNode", + "/data/negativeExponent" : "tools.jackson.databind.node.DoubleNode", + "/data/longDecimal" : "tools.jackson.databind.node.DoubleNode", + "/data/true" : "tools.jackson.databind.node.BooleanNode", + "/data/false" : "tools.jackson.databind.node.BooleanNode", + "/data/null" : "tools.jackson.databind.node.NullNode", + "/data/emptyObject" : "tools.jackson.databind.node.ObjectNode", + "/data/emptyArray" : "tools.jackson.databind.node.ArrayNode", + "/data/nested" : "tools.jackson.databind.node.ObjectNode", + "/data/nested/array" : "tools.jackson.databind.node.ArrayNode", + "/data/nested/array/0" : "tools.jackson.databind.node.IntNode", + "/data/nested/array/1" : "tools.jackson.databind.node.StringNode", + "/data/nested/array/2" : "tools.jackson.databind.node.ArrayNode", + "/data/nested/array/2/0" : "tools.jackson.databind.node.IntNode", + "/data/nested/array/2/1" : "tools.jackson.databind.node.ObjectNode", + "/data/nested/array/2/1/four" : "tools.jackson.databind.node.DoubleNode", + "/data/nested/array/3" : "tools.jackson.databind.node.NullNode", + "/data/nested/array/4" : "tools.jackson.databind.node.BooleanNode", + "/data/nested/array/5" : "tools.jackson.databind.node.LongNode", + "/data/nested/object" : "tools.jackson.databind.node.ObjectNode", + "/data/nested/object/z" : "tools.jackson.databind.node.IntNode", + "/data/nested/object/a" : "tools.jackson.databind.node.ObjectNode", + "/data/nested/object/a/deeper" : "tools.jackson.databind.node.ArrayNode", + "/data/nested/object/a/deeper/0" : "tools.jackson.databind.node.ArrayNode", + "/data/nested/object/a/deeper/1" : "tools.jackson.databind.node.ObjectNode", + "/data/unicode" : "tools.jackson.databind.node.StringNode", + "/data/escapes" : "tools.jackson.databind.node.StringNode", + "/data/key with escaped name" : "tools.jackson.databind.node.StringNode", + "/data/alpha" : "tools.jackson.databind.node.StringNode" }, "keyOrder" : { "/data/emptyObject" : [ ], @@ -79,18 +79,18 @@ }, "dataShape" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/data" : "com.fasterxml.jackson.databind.node.NullNode", - "/errors" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/errors/0" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/errors/0/message" : "com.fasterxml.jackson.databind.node.TextNode", - "/errors/0/locations" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/errors/0/locations/0" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/errors/0/locations/0/line" : "com.fasterxml.jackson.databind.node.IntNode", - "/errors/0/locations/0/column" : "com.fasterxml.jackson.databind.node.IntNode", - "/errors/0/path" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/errors/0/path/0" : "com.fasterxml.jackson.databind.node.TextNode", - "/errors/0/path/1" : "com.fasterxml.jackson.databind.node.IntNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/data" : "tools.jackson.databind.node.NullNode", + "/errors" : "tools.jackson.databind.node.ArrayNode", + "/errors/0" : "tools.jackson.databind.node.ObjectNode", + "/errors/0/message" : "tools.jackson.databind.node.StringNode", + "/errors/0/locations" : "tools.jackson.databind.node.ArrayNode", + "/errors/0/locations/0" : "tools.jackson.databind.node.ObjectNode", + "/errors/0/locations/0/line" : "tools.jackson.databind.node.IntNode", + "/errors/0/locations/0/column" : "tools.jackson.databind.node.IntNode", + "/errors/0/path" : "tools.jackson.databind.node.ArrayNode", + "/errors/0/path/0" : "tools.jackson.databind.node.StringNode", + "/errors/0/path/1" : "tools.jackson.databind.node.IntNode" }, "keyOrder" : { "/errors/0/locations/0" : [ "line", "column" ], diff --git a/server/api-service/lowcoder-plugins/mongoPlugin/pom.xml b/server/api-service/lowcoder-plugins/mongoPlugin/pom.xml index 0d955e8754..5af1ea0996 100644 --- a/server/api-service/lowcoder-plugins/mongoPlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/mongoPlugin/pom.xml @@ -16,9 +16,6 @@ UTF-8 - 17 - ${java.version} - ${java.version} mongo-plugin org.lowcoder.plugin.mongo.MongoPlugin ${revision} @@ -52,7 +49,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/commands/MongoCommand.java b/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/commands/MongoCommand.java index 022cddcb2f..08c7b46892 100644 --- a/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/commands/MongoCommand.java +++ b/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/commands/MongoCommand.java @@ -29,8 +29,8 @@ import org.bson.Document; import org.lowcoder.sdk.exception.PluginException; -import com.fasterxml.jackson.databind.ObjectMapper; - +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -68,7 +68,7 @@ public abstract class MongoCommand { List fieldNamesWithNoConfiguration; - protected static final ObjectMapper objectMapper = new ObjectMapper(); + protected static final ObjectMapper objectMapper = JsonMapper.builderWithJackson2Defaults().build(); public MongoCommand(Map formData) { diff --git a/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/model/MongoConnectionUriParser.java b/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/model/MongoConnectionUriParser.java index 0144e134fe..d7dd53fb30 100644 --- a/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/model/MongoConnectionUriParser.java +++ b/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/model/MongoConnectionUriParser.java @@ -17,19 +17,19 @@ public final class MongoConnectionUriParser { * - mongodb+srv://user:pass@some-url/some-db... * - mongodb://user:pass@some-url:port,some-url:port,.../some-db... * - It has been grouped like this: (mongodb+srv://)(user):(pass)@(some-url)/(some-db...)?(params...) - * - User and password are matched only in the authority, before the first / (CREDENTIAL_PART), as the driver reads - * them (driver 4.11: the authority ends at the first /, so a ? before it belongs to the credentials): a : and a later - * @ in the path or the options are not credentials (BF-060: they were, and the database was lost or another one was - * taken). The URIs this changes are exactly those where the credentials were taken across a /; each is now read with - * the / ending the authority, or is invalid when that leaves no host (mongodb:///:p@h/db). The host list - * (HOST_LIST_PART) ends at the first / or ?, as before. + * - User and password are matched only in the authority, which ends at the first / or ? (CREDENTIAL_PART), as the + * driver reads it (driver 5.5): a : and a later @ in the path or the options are not credentials (BF-060: they were, + * and the database was lost or another one was taken), and neither is a ? with what follows it. So + * mongodb://u?x:p?q@h/db?a=1 is host u, no credentials, no database and the options x:p?q@h/db?a=1, which is how the + * driver reads it. The URIs this changes are exactly those where the credentials were taken across a / or a ?; each + * is now read with that / or ? ending the authority, or is invalid when that leaves no host (mongodb:///:p@h/db). + * The host list (HOST_LIST_PART) ends at the first / or ?, as before. * - Limits: this is a split, not the driver's check. A URI the driver refuses can still match: an unencoded /, : or @ - * in the credentials (mongodb://u:p/ss@h/db is read as host u:p, database ss@h/db), options without a / before the ?, - * or a / in the database name. The driver refuses such a URI when it connects. + * in the credentials (mongodb://u:p/ss@h/db is read as host u:p, database ss@h/db), or a / in the database name. The driver refuses such a URI when it connects. * - * ^(mongodb(?:\+srv)?:\/\/)(?:([^\/]+):([^\/]+)@)?([^\/\?]+)\/?([^\?]+)?\??(.+)?$ + * ^(mongodb(?:\+srv)?:\/\/)(?:([^\/\?]+):([^\/\?]+)@)?([^\/\?]+)\/?([^\?]+)?\??(.+)?$ */ - private static final String CREDENTIAL_PART = "[^/]+"; + private static final String CREDENTIAL_PART = "[^/?]+"; private static final String HOST_LIST_PART = "[^/?]+"; diff --git a/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/utils/MongoQueryUtils.java b/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/utils/MongoQueryUtils.java index 2c7d168f9c..21f191e27e 100644 --- a/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/utils/MongoQueryUtils.java +++ b/server/api-service/lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/utils/MongoQueryUtils.java @@ -53,11 +53,9 @@ import org.lowcoder.plugin.mongo.commands.UpdateMany; import org.lowcoder.sdk.exception.PluginException; import org.lowcoder.sdk.models.DatasourceStructure; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; public class MongoQueryUtils { @@ -148,7 +146,7 @@ public static String urlEncode(String text) { return URLEncoder.encode(text, StandardCharsets.UTF_8); } - public static JsonNode parseResultBody(JSONObject outputJson) throws JsonProcessingException { + public static JsonNode parseResultBody(JSONObject outputJson) { /* For the `findAndModify` command, we don't get the count of modifications made. Instead, we either get the modified new value or the pre-modified old value (depending on the diff --git a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoAuthContainerSupport.java b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoAuthContainerSupport.java new file mode 100644 index 0000000000..ed9f8d5602 --- /dev/null +++ b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoAuthContainerSupport.java @@ -0,0 +1,150 @@ +package org.lowcoder.plugin.mongo; + +import org.lowcoder.plugin.mongo.model.MongoConnection; +import org.lowcoder.plugin.mongo.model.MongoDatasourceConfig; +import org.lowcoder.plugin.mongo.utils.MongoQueryUtils; +import org.lowcoder.sdk.config.dynamic.ConfigCenterForTest; +import org.lowcoder.sdk.contract.ContainerImages; +import org.testcontainers.containers.Container.ExecResult; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.utility.DockerImageName; + +import java.io.IOException; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * The shared MongoDB 7.0 container with authentication of the Mongo authentication tests (default build, not + * heavy-container: one per test JVM, started on first use, removed by Testcontainers' reaper when the JVM exits). The image's + * {@code MONGO_INITDB_ROOT_USERNAME} and {@code MONGO_INITDB_ROOT_PASSWORD} create the root user in the {@code admin} + * database, and the server then runs with authentication on; this class adds the user {@link #APP_USER} in database + * {@link #DATABASE} with {@code mongosh} run in the container (an exec, no file is copied in). A generic container, as in + * {@link MongoContainerSupport}. The image's init phase starts a temporary server, so readiness is the second "Waiting for + * connections" line, then a bounded loop until the root user can ping. No Docker guard on purpose (owner decision D-7). + * Not a test. + */ +final class MongoAuthContainerSupport { + + static final String DATABASE = "app"; + static final String ADMIN_DATABASE = "admin"; + static final String ROOT_USER = "root"; + static final String ROOT_PASSWORD = "root-pw"; + static final String APP_USER = "appuser"; + static final String APP_PASSWORD = "app:p@ss/w#rd%1"; + static final String WRONG_PASSWORD = "not-the-password"; + static final int MONGO_PORT = 27017; + private static final String READY_PATTERN = ".*[Ww]aiting for connections.*"; + private static final int READY_MESSAGES = 2; + private static final Duration START_TIMEOUT = Duration.ofMinutes(2); + private static final Duration PING_TIMEOUT = Duration.ofSeconds(10); + private static final int PING_ATTEMPTS = 30; + private static final long PING_PAUSE_MILLIS = 500; + static final Duration BLOCK_TIMEOUT = Duration.ofSeconds(30); + + private static final GenericContainer MONGO = new GenericContainer<>(DockerImageName.parse(ContainerImages.MONGO_7_0)) + .withEnv("MONGO_INITDB_ROOT_USERNAME", ROOT_USER).withEnv("MONGO_INITDB_ROOT_PASSWORD", ROOT_PASSWORD) + .withExposedPorts(MONGO_PORT) + .waitingFor(Wait.forLogMessage(READY_PATTERN, READY_MESSAGES).withStartupTimeout(START_TIMEOUT)); + + static final MongoPlugin.MongoEngine ENGINE = new MongoPlugin.MongoEngine(new ConfigCenterForTest()); + + static { + long start = System.nanoTime(); + MONGO.start(); + System.out.println("[MongoAuthContainerSupport] " + ContainerImages.MONGO_7_0 + " with authentication started in " + + (System.nanoTime() - start) / 1_000_000 + " ms on " + MONGO.getHost() + ":" + MONGO.getMappedPort(MONGO_PORT)); + awaitRootPing(); + createAppUser(); + } + + private MongoAuthContainerSupport() { + } + + static String host() { + return MONGO.getHost(); + } + + static int port() { + return MONGO.getMappedPort(MONGO_PORT); + } + + /** A host-mode config ({@code usingUri} false); the authentication database is {@code database}, there is no field for another one. */ + static MongoDatasourceConfig hostConfig(String database, String username, String password, String authMechanism) { + Map values = new LinkedHashMap<>(); + values.put("host", host()); + values.put("port", port()); + values.put("database", database); + if (username != null) { + values.put("username", username); + } + if (password != null) { + values.put("password", password); + } + if (authMechanism != null) { + values.put("authMechanism", authMechanism); + } + return MongoDatasourceConfig.buildFrom(values); + } + + static MongoDatasourceConfig uriConfig(String uri) { + return MongoDatasourceConfig.buildFrom(Map.of("usingUri", true, "uri", uri)); + } + + /** {@code mongodb://:@host:port/} plus {@code query} (with its leading {@code ?}, or empty); user and password are percent-encoded. */ + static String uri(String user, String password, String database, String query) { + return "mongodb://" + (user == null ? "" : MongoQueryUtils.urlEncode(user) + ":" + MongoQueryUtils.urlEncode(password) + "@") + host() + ":" + port() + + "/" + database + query; + } + + private static void awaitRootPing() { + RuntimeException last = null; + for (int attempt = 1; attempt <= PING_ATTEMPTS; attempt++) { + MongoConnection connection = null; + try { + connection = ENGINE.createConnection(hostConfig(ADMIN_DATABASE, ROOT_USER, ROOT_PASSWORD, null)).block(BLOCK_TIMEOUT); + System.out.println("[MongoAuthContainerSupport] root ping answered on attempt " + attempt + ": " + + connection.ping().block(PING_TIMEOUT).toJson()); + return; + } catch (RuntimeException e) { + last = e; + pause(); + } finally { + if (connection != null) { + connection.close().block(BLOCK_TIMEOUT); + } + } + } + throw new IllegalStateException("MongoDB with authentication did not answer a root ping after " + PING_ATTEMPTS + " attempts", last); + } + + /** The user of {@link #DATABASE}: read and write there only, so only a login that authenticates against {@code app} reaches it. */ + private static void createAppUser() { + String script = "db.getSiblingDB('" + DATABASE + "').createUser({user: '" + APP_USER + "', pwd: '" + APP_PASSWORD + + "', roles: [{role: 'readWrite', db: '" + DATABASE + "'}]})"; + try { + ExecResult result = MONGO.execInContainer("mongosh", "--quiet", "-u", ROOT_USER, "-p", ROOT_PASSWORD, + "--authenticationDatabase", ADMIN_DATABASE, "--eval", script); + System.out.println("[MongoAuthContainerSupport] createUser exit " + result.getExitCode() + ": " + result.getStdout().trim() + + result.getStderr().trim()); + if (result.getExitCode() != 0) { + throw new IllegalStateException("cannot create " + APP_USER + ": " + result.getStdout() + result.getStderr()); + } + } catch (IOException e) { + throw new IllegalStateException("cannot run mongosh in the container", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while creating " + APP_USER, e); + } + } + + private static void pause() { + try { + Thread.sleep(PING_PAUSE_MILLIS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while waiting for MongoDB", interrupted); + } + } +} diff --git a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoEngineAuthContainerTest.java b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoEngineAuthContainerTest.java new file mode 100644 index 0000000000..75f797f18a --- /dev/null +++ b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoEngineAuthContainerTest.java @@ -0,0 +1,204 @@ +package org.lowcoder.plugin.mongo; + +import tools.jackson.databind.JsonNode; +import org.junit.jupiter.api.Test; +import org.lowcoder.plugin.mongo.model.MongoConnection; +import org.lowcoder.plugin.mongo.model.MongoDatasourceConfig; +import org.lowcoder.plugin.mongo.model.MongoQueryExecutionContext; +import org.lowcoder.sdk.exception.PluginException; +import org.lowcoder.sdk.models.DatasourceTestResult; +import org.lowcoder.sdk.models.QueryExecutionResult; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.ADMIN_DATABASE; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.APP_PASSWORD; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.APP_USER; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.BLOCK_TIMEOUT; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.DATABASE; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.ENGINE; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.ROOT_PASSWORD; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.ROOT_USER; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.WRONG_PASSWORD; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.hostConfig; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.uri; +import static org.lowcoder.plugin.mongo.MongoAuthContainerSupport.uriConfig; + +/** + * Unit MG-7: the Mongo engine against a MongoDB 7.0 that requires authentication ({@link MongoAuthContainerSupport}), with SCRAM + * through a host config and through a URI config: test-connection, a connection that inserts a document and finds it again, a wrong + * password, and the authentication database. A host config has no authentication-database field, so the user is authenticated + * against the config's {@code database} (the driver's default for a connection string without {@code authSource}); a URI + * config names it with {@code ?authSource=}. The tests pin both consequences: the root user (defined in {@code admin}) works in + * a host config whose database is {@code admin} and in a URI with {@code authSource=admin}, and fails in a host config whose + * database is {@code app}. + * + *

Observed behaviour pinned here: {@code ping} needs no authentication on MongoDB 7.0, so a config without credentials + * passes test-connection against this server and is refused only by the first command that needs a role. + * + *

Limits: SCRAM-SHA-1 and SCRAM-SHA-256 only (the {@code MONGODB-X509} value of the enum needs client certificates and TLS, + * which the image does not offer); no TLS; each test uses its own collection. + */ +public class MongoEngineAuthContainerTest { + + static final String TAG = "[MongoEngineAuthContainerTest] "; + static final String QUERY_CODE_OK = "OK"; + static final String SCRAM_SHA_1 = "SCRAM_SHA_1"; + static final String SCRAM_SHA_256 = "SCRAM_SHA_256"; + static final String AUTH_SOURCE_ADMIN = "?authSource=" + ADMIN_DATABASE; + static final String UNAUTHORIZED_KEY = "QUERY_ARGUMENT_ERROR"; + static final String REQUIRES_AUTHENTICATION = "requires authentication"; + static final String AUTHENTICATION_FAILED = "Exception authenticating MongoCredential"; + static final String SOURCE_APP = "source='app'"; + + private static String collection(String prefix) { + return prefix + "_" + UUID.randomUUID().toString().substring(0, 8); + } + + private static Map form(String type, String collection, Object... compKeysAndValues) { + Map comp = new HashMap<>(); + for (int i = 0; i < compKeysAndValues.length; i += 2) { + comp.put((String) compKeysAndValues[i], compKeysAndValues[i + 1]); + } + Map form = new HashMap<>(); + form.put("compType", type); + form.put("collection", collection); + form.put("comp", comp); + return form; + } + + private static QueryExecutionResult run(MongoDatasourceConfig config, MongoConnection connection, Map form) { + MongoQueryExecutionContext context = ENGINE.buildQueryExecutionContext(config, form, Map.of(), null); + QueryExecutionResult result = ENGINE.executeQuery(connection, context).block(BLOCK_TIMEOUT); + System.out.println(TAG + context.getCommand().toJson() + " -> " + result.getQueryCode() + " " + result.getData()); + return result; + } + + private static DatasourceTestResult test(String label, MongoDatasourceConfig config) { + DatasourceTestResult result = ENGINE.testConnection(config).block(BLOCK_TIMEOUT); + assertNotNull(result, "testConnection emits a result: " + label); + System.out.println(TAG + "test connection " + label + ": success=" + result.isSuccess() + + (result.isSuccess() ? "" : " message=" + result.getInvalidMessage(Locale.ENGLISH))); + return result; + } + + /** Connects, inserts one document, finds it, and closes the connection. */ + private static void insertAndFind(String label, MongoDatasourceConfig config) { + MongoConnection connection = ENGINE.createConnection(config).block(BLOCK_TIMEOUT); + try { + String c = collection("auth"); + QueryExecutionResult inserted = run(config, connection, form("INSERT", c, "documents", "{\"n\": 1, \"who\": \"" + label + "\"}")); + assertEquals(QUERY_CODE_OK, inserted.getQueryCode(), label + ": the insert succeeds"); + assertEquals("{\"n\":1}", inserted.getData().toString(), label + ": one document inserted"); + QueryExecutionResult found = run(config, connection, form("FIND", c, "projection", "{\"_id\": 0}")); + assertEquals(QUERY_CODE_OK, found.getQueryCode(), label + ": the find succeeds"); + JsonNode rows = (JsonNode) found.getData(); + assertEquals("[{\"n\":1,\"who\":\"" + label + "\"}]", rows.toString(), label + ": the inserted document is read back"); + } finally { + ENGINE.destroyConnection(connection).block(BLOCK_TIMEOUT); + } + } + + // ---- host config + + @Test + public void hostConfigWithTheAppUserAuthenticatesAgainstItsDatabaseWithEachScramMechanism() { + for (String mechanism : new String[] {null, SCRAM_SHA_1, SCRAM_SHA_256}) { + MongoDatasourceConfig config = hostConfig(DATABASE, APP_USER, APP_PASSWORD, mechanism); + assertTrue(test("host app user, mechanism " + mechanism, config).isSuccess(), "test connection passes with mechanism " + mechanism); + insertAndFind("host-" + mechanism, config); + } + } + + @Test + public void hostConfigWithTheRootUserWorksWhenTheDatabaseIsAdminAndFailsWhenItIsApp() { + MongoDatasourceConfig admin = hostConfig(ADMIN_DATABASE, ROOT_USER, ROOT_PASSWORD, SCRAM_SHA_256); + assertTrue(test("host root user in admin", admin).isSuccess()); + insertAndFind("host-root-admin", admin); + + MongoDatasourceConfig app = hostConfig(DATABASE, ROOT_USER, ROOT_PASSWORD, null); + DatasourceTestResult failed = test("host root user in app", app); + assertFalse(failed.isSuccess(), "the root user is defined in admin; a host config authenticates against its database (app)"); + assertTrue(failed.getInvalidMessage(Locale.ENGLISH).contains(AUTHENTICATION_FAILED), failed.getInvalidMessage(Locale.ENGLISH)); + assertTrue(failed.getInvalidMessage(Locale.ENGLISH).contains(SOURCE_APP), "the credential's source is the config's database: " + failed.getInvalidMessage(Locale.ENGLISH)); + } + + @Test + public void hostConfigWithAWrongPasswordFailsTestConnectionWithAuthenticationFailed() { + for (String mechanism : new String[] {null, SCRAM_SHA_1, SCRAM_SHA_256}) { + DatasourceTestResult failed = test("host wrong password, mechanism " + mechanism, + hostConfig(DATABASE, APP_USER, WRONG_PASSWORD, mechanism)); + assertFalse(failed.isSuccess(), "a wrong password fails the test with mechanism " + mechanism); + assertTrue(failed.getInvalidMessage(Locale.ENGLISH).contains(AUTHENTICATION_FAILED), failed.getInvalidMessage(Locale.ENGLISH)); + } + } + + @Test + public void hostConfigWithAWrongUserFailsTestConnection() { + DatasourceTestResult failed = test("host unknown user", hostConfig(DATABASE, "nobody", APP_PASSWORD, null)); + assertFalse(failed.isSuccess(), "an unknown user fails the test"); + assertTrue(failed.getInvalidMessage(Locale.ENGLISH).contains(AUTHENTICATION_FAILED), failed.getInvalidMessage(Locale.ENGLISH)); + } + + // ---- URI config + + @Test + public void uriConfigWithTheAppUserAuthenticatesAgainstItsDatabase() { + MongoDatasourceConfig config = uriConfig(uri(APP_USER, APP_PASSWORD, DATABASE, "")); + assertTrue(test("uri app user", config).isSuccess()); + insertAndFind("uri-app", config); + + MongoDatasourceConfig sha256 = uriConfig(uri(APP_USER, APP_PASSWORD, DATABASE, "?authMechanism=SCRAM-SHA-256")); + assertTrue(test("uri app user, SCRAM-SHA-256", sha256).isSuccess()); + insertAndFind("uri-app-sha256", sha256); + } + + @Test + public void uriConfigWithTheRootUserNeedsAuthSourceAdmin() { + MongoDatasourceConfig withSource = uriConfig(uri(ROOT_USER, ROOT_PASSWORD, DATABASE, AUTH_SOURCE_ADMIN)); + assertTrue(test("uri root user with authSource=admin", withSource).isSuccess()); + insertAndFind("uri-root-authsource", withSource); + + DatasourceTestResult without = test("uri root user without authSource", uriConfig(uri(ROOT_USER, ROOT_PASSWORD, DATABASE, ""))); + assertFalse(without.isSuccess(), "without authSource the root user is looked up in app, where it does not exist"); + assertTrue(without.getInvalidMessage(Locale.ENGLISH).contains(AUTHENTICATION_FAILED), without.getInvalidMessage(Locale.ENGLISH)); + assertTrue(without.getInvalidMessage(Locale.ENGLISH).contains(SOURCE_APP), "the credential's source defaults to the URI's database: " + without.getInvalidMessage(Locale.ENGLISH)); + } + + @Test + public void uriConfigWithAWrongPasswordFailsTestConnectionWithAuthenticationFailed() { + DatasourceTestResult failed = test("uri wrong password", uriConfig(uri(APP_USER, WRONG_PASSWORD, DATABASE, ""))); + assertFalse(failed.isSuccess(), "a wrong password fails the test"); + assertTrue(failed.getInvalidMessage(Locale.ENGLISH).contains(AUTHENTICATION_FAILED), failed.getInvalidMessage(Locale.ENGLISH)); + DatasourceTestResult wrongSource = test("uri wrong password, authSource=admin", uriConfig(uri(ROOT_USER, WRONG_PASSWORD, DATABASE, AUTH_SOURCE_ADMIN))); + assertFalse(wrongSource.isSuccess()); + } + + // ---- no credentials + + @Test + public void aConfigWithoutCredentialsPassesTestConnectionBecausePingNeedsNoRoleButItsQueriesAreRefused() { + MongoDatasourceConfig anonymous = hostConfig(DATABASE, null, null, null); + assertTrue(test("host without credentials", anonymous).isSuccess(), "ping needs no authentication on this server"); + + MongoConnection connection = ENGINE.createConnection(anonymous).block(BLOCK_TIMEOUT); + try { + PluginException refused = assertThrows(PluginException.class, + () -> run(anonymous, connection, form("FIND", collection("anon")))); + System.out.println(TAG + "find without credentials: " + refused.getError() + " " + refused.getMessageKey() + " " + + java.util.List.of(refused.getArgs())); + assertEquals(UNAUTHORIZED_KEY, refused.getMessageKey()); + assertTrue(String.valueOf(refused.getArgs()[0]).contains(REQUIRES_AUTHENTICATION), String.valueOf(refused.getArgs()[0])); + } finally { + ENGINE.destroyConnection(connection).block(BLOCK_TIMEOUT); + } + } +} diff --git a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoEngineContainerTest.java b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoEngineContainerTest.java index 1571e433b1..18780bf898 100644 --- a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoEngineContainerTest.java +++ b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoEngineContainerTest.java @@ -1,6 +1,7 @@ package org.lowcoder.plugin.mongo; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; import org.bson.Document; import org.bson.types.Decimal128; import org.bson.types.ObjectId; @@ -50,7 +51,7 @@ public class MongoEngineContainerTest { static final long SLOW_FILTER_MILLIS = 1500; static final long QUERY_TIMEOUT_MILLIS = 200; - private static final com.fasterxml.jackson.databind.ObjectMapper JSON = new com.fasterxml.jackson.databind.ObjectMapper(); + private static final tools.jackson.databind.ObjectMapper JSON = JsonMapper.builderWithJackson2Defaults().build(); private static MongoConnection connection; private static final MongoDatasourceConfig CONFIG = MongoContainerSupport.hostConfig(); @@ -144,9 +145,10 @@ public void aClosedConnectionCanNoLongerRunCommands() { MongoConnection closing = ENGINE.createConnection(CONFIG).block(BLOCK_TIMEOUT); assertEquals(1.0, closing.ping().block(BLOCK_TIMEOUT).get("ok")); ENGINE.destroyConnection(closing).block(BLOCK_TIMEOUT); - QueryExecutionResult after = run(closing, form("COUNT", collection("closed")), Map.of()); - assertEquals("MONGO_EXECUTION_ERROR", after.getQueryCode(), "observed: a closed client gives an error result, not an exception"); - assertEquals("MONGODB_EXECUTE_ERROR", after.getMessageKey()); + PluginException thrown = assertThrows(PluginException.class, () -> run(closing, form("COUNT", collection("closed")), Map.of()), + "observed with driver 5.8: a closed client refuses the command when it is issued, as a command error"); + assertEquals("MONGODB_COMMAND_ERROR", thrown.getMessageKey()); + assertTrue(thrown.getMessage().contains("state should be: open"), "the driver's reason is in the message: " + thrown.getMessage()); } // ---- commands diff --git a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoPluginValidateConfigTest.java b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoPluginValidateConfigTest.java index 4d7e3b0585..54baf70a33 100644 --- a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoPluginValidateConfigTest.java +++ b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoPluginValidateConfigTest.java @@ -45,21 +45,21 @@ public class MongoPluginValidateConfigTest { /** * NEW-20: connection strings {@code MONGO_URL_REGEX} matches and the driver refuses, one per reason - an authority * read as host {@code u:p} with a non-numeric port (BF-060's split case), a database holding '/' or ' ', options - * without the leading '/', an option without '=', an SRV host carrying a port, a username without a password, a + * after a '?' in the credentials, an option without '=', an SRV host carrying a port, a username without a password, a * port that is not a number and one out of range, an unknown read preference, an unknown auth mechanism, and an * unenclosed IPv6 literal. Both tests below assert the driver's verdict case by case, so this list pins the * parsing decisions of whichever driver the classpath resolves rather than a stable MongoDB URI specification. */ static final List DRIVER_REFUSED_URIS = List.of( - "mongodb://u:p/ss@h/db", "mongodb://h/db/x", "mongodb://h?x=1", "mongodb://localhost?x=1", + "mongodb://u:p/ss@h/db", "mongodb://h/db/x", "mongodb://u?x:p?q@h/db", "mongodb://localhost/db?x", "mongodb://h/db?x", "mongodb+srv://h:27017/db", "mongodb://u@h/db", "mongodb://h:notaport/db", "mongodb://h:99999/db", "mongodb://h/db?readPreference=bogus", "mongodb://h/a b", "mongodb://u:p@h/db?authMechanism=NOPE", "mongodb://[::1/db"); - /** NEW-20: connection strings that look malformed and the driver accepts; the last two are BF-060's cases. */ + /** NEW-20: connection strings that look malformed and the driver accepts; the last two are BF-060's case and an options part without the leading '/' (the authority ends at the '?'). */ static final List DRIVER_ACCEPTED_URIS = List.of( "mongodb://h/db#frag", "mongodb://h,/db", "mongodb://h/db?ssl=notabool", "mongodb://h/db?w=x=y", - "mongodb://realhost/db?appName=a:b@other", "mongodb://u?x:p?q@h/db"); + "mongodb://realhost/db?appName=a:b@other", "mongodb://h?x=1"); /** NEW-55: host-field values the driver refuses once the connection string is built around them. */ static final List DRIVER_REFUSED_HOSTS = List.of("h:notaport", "[::1", "h:99999"); @@ -110,7 +110,7 @@ public void aUriWithAnEmptyAuthorityIsInvalidBF060() { * NEW-20: a connection string the regex matches but the driver's own parser refuses is now reported, instead of * saving and failing later on connect. Each case asserts three things in order: that the regex accepts it, so the * check that fires is the driver one and not {@code isValid}; that the driver refuses it, so the expectation is the - * driver's own verdict and not a list copied from a probe; and the resulting code. `mongodb://localhost?x=1` also + * driver's own verdict and not a list copied from a probe; and the resulting code. `mongodb://localhost/db?x` also * pins the choice of code: a loopback host inside a refused URI gives the URL code alone, because a refused string * yields no hosts for the loopback check to see. * diff --git a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoTreeTextContractTest.java b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoTreeTextContractTest.java index b78fd2edb4..b90318d5ac 100644 --- a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoTreeTextContractTest.java +++ b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/MongoTreeTextContractTest.java @@ -1,7 +1,6 @@ package org.lowcoder.plugin.mongo; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import org.bson.Document; import org.bson.json.JsonMode; import org.bson.json.JsonWriterSettings; @@ -88,7 +87,7 @@ public void commandsAsParsed() { @BoundarySites("lowcoder-plugins/mongoPlugin/src/main/java/org/lowcoder/plugin/mongo/utils/MongoQueryUtils.java##import#1") @Test - public void distinctResultNode() throws JsonProcessingException { + public void distinctResultNode() { Document reply = new Document("values", List.of(1, 3_000_000_001L, 2.5, "žluť \"quoted\"", new ObjectId("65f0c0ffee0000000000abcd"), new Decimal128(new BigDecimal("10.50")), new Document("nested", List.of(true)))).append("ok", 1.0); JsonNode node = MongoQueryUtils.parseResultBody(new JSONObject(reply.toJson())); diff --git a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/model/MongoConnectionUriParserTest.java b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/model/MongoConnectionUriParserTest.java index a711ad5cff..5d2c370c4a 100644 --- a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/model/MongoConnectionUriParserTest.java +++ b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/java/org/lowcoder/plugin/mongo/model/MongoConnectionUriParserTest.java @@ -24,7 +24,7 @@ * ({@code getParsedDatabase}, used at lines 189, 212, 307 and 365). A misread therefore shows as a wrong or missing database * name, not as a wrong host. * - *

Limits: string handling, no server; the driver (the module's, 4.11) is used only to read the database it would connect + *

Limits: string handling, no server; the driver (the module's, 5.5) is used only to read the database it would connect * with (BF-060 agreement test); the client form carries a copy of the regex as it was before BF-060, which accepts every * URI this one accepts (mongoDatasourceForm.tsx:53-55), not tested here. */ @@ -122,9 +122,9 @@ public void invalidStringsAreRejectedAndGiveNoParts() { /** * BF-060 (formerly pinned as the plan section 9 row "MongoConnectionUriParser reads a `:`...`@` in the query string as - * credentials"): the credentials are matched only before the first {@code /}, so a {@code :} and a later {@code @} - * in the options stay in the options, while a {@code ?} before the first {@code /} stays in the credentials, as the - * driver reads it. {@code mongodb://realhost/db?appName=a:b@other} has host + * credentials"): the credentials are matched only in the authority, which ends at the first {@code /} or {@code ?}, so + * a {@code :} and a later {@code @} in the options stay in the options, and a {@code ?} ends the authority, as the + * driver (5.5) reads it. {@code mongodb://realhost/db?appName=a:b@other} has host * {@code realhost} and database {@code db} (it lost its database before), and {@code mongodb://h/db?appName=a:b@c/other} * has database {@code db} (it gave {@code other}); the driver reads the same database (driver agreement test below). */ @@ -141,26 +141,44 @@ public void aColonAndAnAtSignInTheOptionsStayInTheOptionsBF060() { String withCredentials = "mongodb://u:p@h/db?appName=a:b@c"; assertEquals(expected(PLAIN_HEAD, "u", "p", "h", "db", "appName=a:b@c"), parts(withCredentials), "real credentials are still read"); - assertEquals(expected(PLAIN_HEAD, "u?x", "p?q", "h", "db", "a=1"), parts("mongodb://u?x:p?q@h/db?a=1"), "a ? before the first / is in the credentials"); + assertEquals(expected(PLAIN_HEAD, null, null, "u", null, "x:p?q@h/db?a=1"), parts("mongodb://u?x:p?q@h/db?a=1"), + "the authority ends at the first ?, so u is the host and x:p?q@h/db?a=1 are the options, not credentials"); } /** - * BF-060: for every URI the MongoDB driver accepts, the database the parser gives is the one the driver connects with - * ({@code ConnectionString.getDatabase}): the database that the structure and the queries use is the URI's. The driver - * is the module's own (4.11), so a driver upgrade that reads the authority differently fails here: 5.5 ends the authority - * at a {@code ?}, reads no database from {@code mongodb://u?x:p?q@h/db?a=1} and refuses {@code mongodb://?u:p@h/db}. + * BF-060: for every URI the MongoDB driver accepts and reads a database from, the database the parser gives is the one + * the driver connects with ({@code ConnectionString.getDatabase}): the database that the structure and the queries use + * is the URI's. */ @Test public void theDatabaseIsTheOneTheDriverReadsBF060() { for (String uri : List.of("mongodb://realhost/db?appName=a:b@other", "mongodb://h/db?appName=a:b@c/other", "mongodb://u:p@h:27017/db?x=y", "mongodb+srv://u:p@cluster0.example.net/db?retryWrites=true", "mongodb://us%40er:p%3Aw%40rd@h/db", "mongodb://h1:1,h2:2/db?replicaSet=rs0", - "mongodb://u:p@h/db?authSource=admin&appName=x:y@z", "mongodb://u?x:p?q@h/db?a=1", "mongodb://?u:p@h/db")) { + "mongodb://u:p@h/db?authSource=admin&appName=x:y@z")) { String driverDatabase = new com.mongodb.ConnectionString(uri).getDatabase(); System.out.println("[MongoConnectionUriParserTest] " + uri + " driver database " + driverDatabase); assertEquals(driverDatabase, MongoConnectionUriParser.parseDatabaseFrom(uri), uri); } } + /** + * BF-060, driver 5.5: the authority ends at the first {@code ?}, so {@code mongodb://u?x:p?q@h/db?a=1} is host + * {@code u} with no database for the driver. The parser reads it the same way and refuses it with the empty-database + * error, instead of reading credentials {@code u?x:p?q} and the database {@code db}. + */ + @Test + public void aQuestionMarkInTheCredentialsEndsTheAuthorityAsForTheDriverBF060() { + String uri = "mongodb://u?x:p?q@h/db?a=1"; + com.mongodb.ConnectionString driver = new com.mongodb.ConnectionString(uri); + System.out.println("[MongoConnectionUriParserTest] " + uri + " driver hosts " + driver.getHosts() + " database " + driver.getDatabase()); + assertEquals(List.of("u"), driver.getHosts(), "the driver reads the host up to the first ?"); + assertNull(driver.getDatabase(), "the driver reads no database from " + uri); + + PluginException thrown = assertThrows(PluginException.class, () -> MongoConnectionUriParser.parseDatabaseFrom(uri)); + assertEquals(DATASOURCE_ARGUMENT_ERROR, thrown.getError()); + assertEquals("MONGODB_DATABASE_EMPTY", thrown.getMessageKey(), "the parser reads no database either, as the driver does"); + } + /** * Observation, no section 9 row: a user name without a password has no {@code :} to match the credentials group, so * {@code mongodb://user@h/db} is read as host {@code user@h} with no user. The database is still right and the driver gets diff --git a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/resources/json-contract/external-json/MongoEngine.results.json b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/resources/json-contract/external-json/MongoEngine.results.json index cd09019a5d..b9ca57ec24 100644 --- a/server/api-service/lowcoder-plugins/mongoPlugin/src/test/resources/json-contract/external-json/MongoEngine.results.json +++ b/server/api-service/lowcoder-plugins/mongoPlugin/src/test/resources/json-contract/external-json/MongoEngine.results.json @@ -3,31 +3,31 @@ "queryCode" : "OK", "dataShape" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/value" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/value/zeta" : "com.fasterxml.jackson.databind.node.TextNode", - "/value/date" : "com.fasterxml.jackson.databind.node.TextNode", - "/value/longMax" : "com.fasterxml.jackson.databind.node.LongNode", - "/value/intMax" : "com.fasterxml.jackson.databind.node.IntNode", - "/value/double" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/value/wholeDouble" : "com.fasterxml.jackson.databind.node.IntNode", - "/value/nested" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/value/nested/ids" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/value/nested/ids/0" : "com.fasterxml.jackson.databind.node.TextNode", - "/value/nested/ids/1" : "com.fasterxml.jackson.databind.node.IntNode", - "/value/nested/ids/2" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/value/nested/ids/2/at" : "com.fasterxml.jackson.databind.node.TextNode", - "/value/int" : "com.fasterxml.jackson.databind.node.IntNode", - "/value/long" : "com.fasterxml.jackson.databind.node.LongNode", - "/value/null" : "com.fasterxml.jackson.databind.node.NullNode", - "/value/alpha" : "com.fasterxml.jackson.databind.node.TextNode", - "/value/true" : "com.fasterxml.jackson.databind.node.BooleanNode", - "/value/unicode" : "com.fasterxml.jackson.databind.node.TextNode", - "/value/_id" : "com.fasterxml.jackson.databind.node.TextNode", - "/value/emptyArray" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/value/emptyObject" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/value/decimal128" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/value/bigDouble" : "com.fasterxml.jackson.databind.node.DoubleNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/value" : "tools.jackson.databind.node.ObjectNode", + "/value/zeta" : "tools.jackson.databind.node.StringNode", + "/value/date" : "tools.jackson.databind.node.StringNode", + "/value/longMax" : "tools.jackson.databind.node.LongNode", + "/value/intMax" : "tools.jackson.databind.node.IntNode", + "/value/double" : "tools.jackson.databind.node.DoubleNode", + "/value/wholeDouble" : "tools.jackson.databind.node.IntNode", + "/value/nested" : "tools.jackson.databind.node.ObjectNode", + "/value/nested/ids" : "tools.jackson.databind.node.ArrayNode", + "/value/nested/ids/0" : "tools.jackson.databind.node.StringNode", + "/value/nested/ids/1" : "tools.jackson.databind.node.IntNode", + "/value/nested/ids/2" : "tools.jackson.databind.node.ObjectNode", + "/value/nested/ids/2/at" : "tools.jackson.databind.node.StringNode", + "/value/int" : "tools.jackson.databind.node.IntNode", + "/value/long" : "tools.jackson.databind.node.LongNode", + "/value/null" : "tools.jackson.databind.node.NullNode", + "/value/alpha" : "tools.jackson.databind.node.StringNode", + "/value/true" : "tools.jackson.databind.node.BooleanNode", + "/value/unicode" : "tools.jackson.databind.node.StringNode", + "/value/_id" : "tools.jackson.databind.node.StringNode", + "/value/emptyArray" : "tools.jackson.databind.node.ArrayNode", + "/value/emptyObject" : "tools.jackson.databind.node.ObjectNode", + "/value/decimal128" : "tools.jackson.databind.node.DoubleNode", + "/value/bigDouble" : "tools.jackson.databind.node.DoubleNode" }, "keyOrder" : { "/value/nested/ids/2" : [ "at" ], @@ -43,33 +43,33 @@ "queryCode" : "OK", "dataShape" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/zeta" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/date" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/longMax" : "com.fasterxml.jackson.databind.node.LongNode", - "/0/intMax" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/double" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/wholeDouble" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/nested" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/nested/ids" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0/nested/ids/0" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/nested/ids/1" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/nested/ids/2" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/nested/ids/2/at" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/int" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/long" : "com.fasterxml.jackson.databind.node.LongNode", - "/0/null" : "com.fasterxml.jackson.databind.node.NullNode", - "/0/alpha" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/true" : "com.fasterxml.jackson.databind.node.BooleanNode", - "/0/unicode" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/_id" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/emptyArray" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0/emptyObject" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/decimal128" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/bigDouble" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/1" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/1/_id" : "com.fasterxml.jackson.databind.node.IntNode" + "" : "tools.jackson.databind.node.ArrayNode", + "/0" : "tools.jackson.databind.node.ObjectNode", + "/0/zeta" : "tools.jackson.databind.node.StringNode", + "/0/date" : "tools.jackson.databind.node.StringNode", + "/0/longMax" : "tools.jackson.databind.node.LongNode", + "/0/intMax" : "tools.jackson.databind.node.IntNode", + "/0/double" : "tools.jackson.databind.node.DoubleNode", + "/0/wholeDouble" : "tools.jackson.databind.node.IntNode", + "/0/nested" : "tools.jackson.databind.node.ObjectNode", + "/0/nested/ids" : "tools.jackson.databind.node.ArrayNode", + "/0/nested/ids/0" : "tools.jackson.databind.node.StringNode", + "/0/nested/ids/1" : "tools.jackson.databind.node.IntNode", + "/0/nested/ids/2" : "tools.jackson.databind.node.ObjectNode", + "/0/nested/ids/2/at" : "tools.jackson.databind.node.StringNode", + "/0/int" : "tools.jackson.databind.node.IntNode", + "/0/long" : "tools.jackson.databind.node.LongNode", + "/0/null" : "tools.jackson.databind.node.NullNode", + "/0/alpha" : "tools.jackson.databind.node.StringNode", + "/0/true" : "tools.jackson.databind.node.BooleanNode", + "/0/unicode" : "tools.jackson.databind.node.StringNode", + "/0/_id" : "tools.jackson.databind.node.StringNode", + "/0/emptyArray" : "tools.jackson.databind.node.ArrayNode", + "/0/emptyObject" : "tools.jackson.databind.node.ObjectNode", + "/0/decimal128" : "tools.jackson.databind.node.DoubleNode", + "/0/bigDouble" : "tools.jackson.databind.node.DoubleNode", + "/1" : "tools.jackson.databind.node.ObjectNode", + "/1/_id" : "tools.jackson.databind.node.IntNode" }, "keyOrder" : { "/0/nested/ids/2" : [ "at" ], @@ -88,8 +88,8 @@ "queryCode" : "OK", "dataShape" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/n" : "com.fasterxml.jackson.databind.node.LongNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/n" : "tools.jackson.databind.node.LongNode" }, "keyOrder" : { "" : [ "n" ] @@ -101,8 +101,8 @@ "queryCode" : "OK", "dataShape" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/nModified" : "com.fasterxml.jackson.databind.node.IntNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/nModified" : "tools.jackson.databind.node.IntNode" }, "keyOrder" : { "" : [ "nModified" ] @@ -114,8 +114,8 @@ "queryCode" : "OK", "dataShape" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/n" : "com.fasterxml.jackson.databind.node.IntNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/n" : "tools.jackson.databind.node.IntNode" }, "keyOrder" : { "" : [ "n" ] @@ -127,15 +127,15 @@ "queryCode" : "OK", "dataShape" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/values" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/values/0" : "com.fasterxml.jackson.databind.node.IntNode", - "/values/1" : "com.fasterxml.jackson.databind.node.TextNode", - "/values/2" : "com.fasterxml.jackson.databind.node.TextNode", - "/values/3" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/values/4" : "com.fasterxml.jackson.databind.node.LongNode", - "/values/5" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/values/6" : "com.fasterxml.jackson.databind.node.TextNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/values" : "tools.jackson.databind.node.ArrayNode", + "/values/0" : "tools.jackson.databind.node.IntNode", + "/values/1" : "tools.jackson.databind.node.StringNode", + "/values/2" : "tools.jackson.databind.node.StringNode", + "/values/3" : "tools.jackson.databind.node.DoubleNode", + "/values/4" : "tools.jackson.databind.node.LongNode", + "/values/5" : "tools.jackson.databind.node.DoubleNode", + "/values/6" : "tools.jackson.databind.node.StringNode" }, "keyOrder" : { "" : [ "values" ] diff --git a/server/api-service/lowcoder-plugins/mssqlPlugin/pom.xml b/server/api-service/lowcoder-plugins/mssqlPlugin/pom.xml index ede6988079..5c5ae042e5 100644 --- a/server/api-service/lowcoder-plugins/mssqlPlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/mssqlPlugin/pom.xml @@ -16,9 +16,6 @@ UTF-8 - 17 - ${java.version} - ${java.version} mssql-plugin org.lowcoder.plugin.mssql.MssqlPlugin ${revision} @@ -31,7 +28,7 @@ com.microsoft.sqlserver mssql-jdbc - 10.2.1.jre11 + 13.6.2.jre11 org.lowcoder @@ -63,7 +60,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/mssqlPlugin/src/test/java/org/lowcoder/plugin/mssql/MssqlConnectorUrlTest.java b/server/api-service/lowcoder-plugins/mssqlPlugin/src/test/java/org/lowcoder/plugin/mssql/MssqlConnectorUrlTest.java index 018b8c81ae..80e61a9879 100644 --- a/server/api-service/lowcoder-plugins/mssqlPlugin/src/test/java/org/lowcoder/plugin/mssql/MssqlConnectorUrlTest.java +++ b/server/api-service/lowcoder-plugins/mssqlPlugin/src/test/java/org/lowcoder/plugin/mssql/MssqlConnectorUrlTest.java @@ -9,6 +9,7 @@ import java.sql.DriverPropertyInfo; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Properties; @@ -46,7 +47,9 @@ private static String url(String host, String portAndDatabase) { private static Map parsed(String jdbcUrl) throws Exception { Map properties = new LinkedHashMap<>(); for (DriverPropertyInfo info : new SQLServerDriver().getPropertyInfo(jdbcUrl, new Properties())) { - properties.put(info.name, info.value); + // the driver reports a boolean property as "True"/"False" since 13.x and as "true"/"false" before; the URL says "true" + boolean isBoolean = "true".equalsIgnoreCase(info.value) || "false".equalsIgnoreCase(info.value); + properties.put(info.name, isBoolean ? info.value.toLowerCase(Locale.ROOT) : info.value); } return properties; } diff --git a/server/api-service/lowcoder-plugins/mssqlPlugin/src/test/resources/json-contract/config-binding/MssqlQueryConfig.json b/server/api-service/lowcoder-plugins/mssqlPlugin/src/test/resources/json-contract/config-binding/MssqlQueryConfig.json index 94a3e91e6b..785753d2b9 100644 --- a/server/api-service/lowcoder-plugins/mssqlPlugin/src/test/resources/json-contract/config-binding/MssqlQueryConfig.json +++ b/server/api-service/lowcoder-plugins/mssqlPlugin/src/test/resources/json-contract/config-binding/MssqlQueryConfig.json @@ -70,13 +70,13 @@ "/guiStatementDetail/filterBy/0/value" : "java.lang.String" }, "noView" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" }, "Public" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" }, "Internal" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" } }, "guiJavaNames" : { @@ -98,13 +98,13 @@ "/guiStatementDetail" : "null" }, "noView" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" }, "Public" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" }, "Internal" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" } }, "scalarsAsStrings" : { @@ -148,13 +148,13 @@ "/guiStatementDetail" : "null" }, "noView" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" }, "Public" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" }, "Internal" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mssql.model.MssqlQueryConfig[\"sql\"])" } }, "empty" : { diff --git a/server/api-service/lowcoder-plugins/mysqlPlugin/pom.xml b/server/api-service/lowcoder-plugins/mysqlPlugin/pom.xml index bf1dc3ab58..5cb58d81ff 100644 --- a/server/api-service/lowcoder-plugins/mysqlPlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/mysqlPlugin/pom.xml @@ -16,9 +16,6 @@ UTF-8 - 17 - ${java.version} - ${java.version} mysql-plugin org.lowcoder.plugin.mysql.MysqlPlugin ${revision} @@ -29,9 +26,9 @@ - mysql - mysql-connector-java - 8.0.30 + com.mysql + mysql-connector-j + 9.7.0 org.lowcoder @@ -57,7 +54,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/mysqlPlugin/src/test/java/org/lowcoder/plugin/mysql/MysqlDatabaseTest.java b/server/api-service/lowcoder-plugins/mysqlPlugin/src/test/java/org/lowcoder/plugin/mysql/MysqlDatabaseTest.java index b6a8ca4fef..c370c915ec 100644 --- a/server/api-service/lowcoder-plugins/mysqlPlugin/src/test/java/org/lowcoder/plugin/mysql/MysqlDatabaseTest.java +++ b/server/api-service/lowcoder-plugins/mysqlPlugin/src/test/java/org/lowcoder/plugin/mysql/MysqlDatabaseTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import org.lowcoder.sdk.exception.PluginException; import org.lowcoder.sdk.models.DatasourceStructure; +import org.lowcoder.sdk.models.DatasourceTestResult; import org.lowcoder.sdk.models.DatasourceStructure.Column; import org.lowcoder.sdk.models.DatasourceStructure.ForeignKey; import org.lowcoder.sdk.models.DatasourceStructure.PrimaryKey; @@ -16,16 +17,20 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Random; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.lowcoder.sdk.exception.PluginCommonError.INVALID_GUI_SETTINGS; import static org.lowcoder.sdk.exception.PluginCommonError.QUERY_EXECUTION_ERROR; +import static org.lowcoder.plugin.mysql.MysqlContainerSupport.CONNECTOR; import static org.lowcoder.plugin.mysql.MysqlContainerSupport.app; import static org.lowcoder.plugin.mysql.MysqlContainerSupport.config; import static org.lowcoder.plugin.mysql.MysqlContainerSupport.connect; @@ -105,6 +110,38 @@ public void poolOpensAndReturnsRealColumnTypes() throws Exception { } } + @Test + public void testConnectionSucceedsWithoutAndWithSsl() { + for (boolean ssl : new boolean[] {false, true}) { + MysqlDatasourceConfig config = config(MysqlContainerSupport.DATABASE, MysqlContainerSupport.PASSWORD, ssl, false, false); + long start = System.nanoTime(); + DatasourceTestResult test = CONNECTOR.testConnection(config).block(); + System.out.println("[MysqlDatabaseTest] test connection, ssl=" + ssl + ": success=" + (test != null && test.isSuccess()) + + " after " + (System.nanoTime() - start) / 1_000_000 + " ms"); + assertNotNull(test, "testConnection emits a result (ssl=" + ssl + ")"); + assertTrue(test.isSuccess(), "the right credentials pass the test (ssl=" + ssl + ")"); + } + } + + @Test + public void testConnectionWithAWrongPasswordErrorsWithAccessDeniedAndTheServerMapsItToAFailedResult() { + for (boolean ssl : new boolean[] {false, true}) { + MysqlDatasourceConfig config = config(MysqlContainerSupport.DATABASE, WRONG_PASSWORD, ssl, false, false); + RuntimeException thrown = assertThrows(RuntimeException.class, () -> CONNECTOR.testConnection(config).block(), + "a wrong password must not give a successful result (ssl=" + ssl + ")"); + System.out.println("[MysqlDatabaseTest] test connection with a wrong password, ssl=" + ssl + ": " + thrown.getClass().getSimpleName() + + ": " + thrown.getMessage()); + assertTrue(String.valueOf(thrown.getMessage()).contains(ACCESS_DENIED), "the error names the refusal (ssl=" + ssl + "): " + thrown.getMessage()); + // what DatasourceServiceImpl.testDatasourceLocally does with the error + DatasourceTestResult mapped = CONNECTOR.testConnection(config).onErrorResume(error -> reactor.core.publisher.Mono.just(DatasourceTestResult.testFail(error))).block(); + assertNotNull(mapped); + assertFalse(mapped.isSuccess(), "the mapped result is a failure (ssl=" + ssl + ")"); + String message = mapped.getInvalidMessage(Locale.ENGLISH); + System.out.println("[MysqlDatabaseTest] mapped failed result, ssl=" + ssl + ": " + message); + assertTrue(String.valueOf(message).contains(ACCESS_DENIED), "the failed result carries the refusal (ssl=" + ssl + "): " + message); + } + } + @Test public void wrongPasswordFailsTheConnectionCreationWithAccessDeniedBF054() { long start = System.nanoTime(); diff --git a/server/api-service/lowcoder-plugins/mysqlPlugin/src/test/resources/json-contract/config-binding/MysqlQueryConfig.json b/server/api-service/lowcoder-plugins/mysqlPlugin/src/test/resources/json-contract/config-binding/MysqlQueryConfig.json index 39bdabcae2..5a07f9a417 100644 --- a/server/api-service/lowcoder-plugins/mysqlPlugin/src/test/resources/json-contract/config-binding/MysqlQueryConfig.json +++ b/server/api-service/lowcoder-plugins/mysqlPlugin/src/test/resources/json-contract/config-binding/MysqlQueryConfig.json @@ -70,13 +70,13 @@ "/guiStatementDetail/filterBy/0/value" : "java.lang.String" }, "noView" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" }, "Public" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" }, "Internal" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" } }, "guiJavaNames" : { @@ -98,13 +98,13 @@ "/guiStatementDetail" : "null" }, "noView" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" }, "Public" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" }, "Internal" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" } }, "scalarsAsStrings" : { @@ -148,13 +148,13 @@ "/guiStatementDetail" : "null" }, "noView" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" }, "Public" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" }, "Internal" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"String.trim()\" because \"this.sql\" is null (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"String.trim()\" because \"this.sql\" is null\n at [No location information] (through reference chain: org.lowcoder.plugin.mysql.model.MysqlQueryConfig[\"sql\"])" } }, "empty" : { diff --git a/server/api-service/lowcoder-plugins/oraclePlugin/pom.xml b/server/api-service/lowcoder-plugins/oraclePlugin/pom.xml index 8df1e0466a..04fd3845b6 100644 --- a/server/api-service/lowcoder-plugins/oraclePlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/oraclePlugin/pom.xml @@ -17,9 +17,6 @@ UTF-8 UTF-8 - 17 - 17 - oracle-plugin org.lowcoder.plugin.oracle.OraclePlugin ${revision} @@ -32,7 +29,7 @@ com.oracle.database.jdbc ojdbc11 - 23.7.0.25.01 + 23.26.4.0.0 org.testcontainers @@ -56,7 +53,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/pom.xml b/server/api-service/lowcoder-plugins/pom.xml index 9c6abe2655..3615ad9680 100644 --- a/server/api-service/lowcoder-plugins/pom.xml +++ b/server/api-service/lowcoder-plugins/pom.xml @@ -13,13 +13,6 @@ lowcoder-plugins pom - - - local_libs - Temporary local libraries - file://${maven.multiModuleProjectDirectory}/local-repo - - tv.twelvetone.rjson rjson - 1.3.1-SNAPSHOT + 1.3.1 test @@ -190,10 +184,9 @@ org.apache.maven.plugins maven-compiler-plugin - 3.13.0 + 3.16.0 - ${java.version} - ${java.version} + ${java.version} -parameters @@ -202,12 +195,12 @@ org.apache.maven.plugins maven-dependency-plugin - 3.6.1 + 3.11.0 org.apache.maven.plugins maven-antrun-plugin - 3.1.0 + 3.2.0 create-plugin-properties diff --git a/server/api-service/lowcoder-plugins/postgresPlugin/pom.xml b/server/api-service/lowcoder-plugins/postgresPlugin/pom.xml index 8019b5cb58..df6bb0f148 100644 --- a/server/api-service/lowcoder-plugins/postgresPlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/postgresPlugin/pom.xml @@ -17,9 +17,6 @@ UTF-8 - 17 - ${java.version} - ${java.version} postgres-plugin org.lowcoder.plugin.postgres.PostgresPlugin ${revision} @@ -32,7 +29,7 @@ org.postgresql postgresql - 42.3.8 + 42.7.15 @@ -59,7 +56,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/postgresPlugin/src/main/java/org/lowcoder/plugin/postgres/PostgresExecutor.java b/server/api-service/lowcoder-plugins/postgresPlugin/src/main/java/org/lowcoder/plugin/postgres/PostgresExecutor.java index 4e8ce48cf8..16e198c296 100644 --- a/server/api-service/lowcoder-plugins/postgresPlugin/src/main/java/org/lowcoder/plugin/postgres/PostgresExecutor.java +++ b/server/api-service/lowcoder-plugins/postgresPlugin/src/main/java/org/lowcoder/plugin/postgres/PostgresExecutor.java @@ -34,9 +34,7 @@ import org.lowcoder.sdk.plugin.sqlcommand.command.postgres.PostgresInsertCommand; import org.lowcoder.sdk.plugin.sqlcommand.command.postgres.PostgresUpdateCommand; import org.pf4j.Extension; - -import com.fasterxml.jackson.core.JsonProcessingException; - +import tools.jackson.core.JacksonException; import lombok.extern.slf4j.Slf4j; @Slf4j @@ -50,7 +48,7 @@ public PostgresExecutor() { protected List> parseDataRows(ResultSet resultSet) throws SQLException { try { return PostgresResultParser.parseRows(resultSet); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { throw new PluginException(QUERY_EXECUTION_ERROR, "QUERY_EXECUTION_ERROR", e.getMessage()); } } diff --git a/server/api-service/lowcoder-plugins/postgresPlugin/src/main/java/org/lowcoder/plugin/postgres/utils/PostgresResultParser.java b/server/api-service/lowcoder-plugins/postgresPlugin/src/main/java/org/lowcoder/plugin/postgres/utils/PostgresResultParser.java index 2d72f26c22..775fb57395 100644 --- a/server/api-service/lowcoder-plugins/postgresPlugin/src/main/java/org/lowcoder/plugin/postgres/utils/PostgresResultParser.java +++ b/server/api-service/lowcoder-plugins/postgresPlugin/src/main/java/org/lowcoder/plugin/postgres/utils/PostgresResultParser.java @@ -38,8 +38,6 @@ import org.lowcoder.sdk.models.DatasourceStructure.Table; import org.postgresql.util.PGobject; -import com.fasterxml.jackson.core.JsonProcessingException; - @SuppressWarnings({"SqlNoDataSourceInspection", "SqlDialectInspection"}) public class PostgresResultParser { @@ -173,7 +171,7 @@ private static void parseTableAndColumns(Map tablesByName, Statem } } - public static List> parseRows(ResultSet resultSet) throws SQLException, JsonProcessingException { + public static List> parseRows(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); List> result = new ArrayList<>(); @@ -186,7 +184,7 @@ public static List> parseRows(ResultSet resultSet) throws SQ private static Map parseRowValue(ResultSet resultSet, ResultSetMetaData metaData, int colCount) - throws SQLException, JsonProcessingException { + throws SQLException { Map row = new LinkedHashMap<>(colCount); for (int i = 1; i <= colCount; i++) { final String typeName = metaData.getColumnTypeName(i); @@ -197,7 +195,7 @@ private static Map parseRowValue(ResultSet resultSet, ResultSetM return row; } - private static Object parseValue(ResultSet resultSet, int i, String typeName) throws SQLException, JsonProcessingException { + private static Object parseValue(ResultSet resultSet, int i, String typeName) throws SQLException { if (resultSet.getObject(i) == null) { return null; } diff --git a/server/api-service/lowcoder-plugins/postgresPlugin/src/test/resources/json-contract/external-json/PostgresResultParser.rows.json b/server/api-service/lowcoder-plugins/postgresPlugin/src/test/resources/json-contract/external-json/PostgresResultParser.rows.json index ecf8ce3b30..5886637e54 100644 --- a/server/api-service/lowcoder-plugins/postgresPlugin/src/test/resources/json-contract/external-json/PostgresResultParser.rows.json +++ b/server/api-service/lowcoder-plugins/postgresPlugin/src/test/resources/json-contract/external-json/PostgresResultParser.rows.json @@ -4,62 +4,62 @@ "classes" : { "" : "java.util.ArrayList", "/0" : "java.util.LinkedHashMap", - "/0/json" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/json/zeta" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/json/int" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/json/negativeInt" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/json/intMax" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/json/intMaxPlusOne" : "com.fasterxml.jackson.databind.node.LongNode", - "/0/json/intMinMinusOne" : "com.fasterxml.jackson.databind.node.LongNode", - "/0/json/longMax" : "com.fasterxml.jackson.databind.node.LongNode", - "/0/json/longMaxPlusOne" : "com.fasterxml.jackson.databind.node.BigIntegerNode", - "/0/json/longMinMinusOne" : "com.fasterxml.jackson.databind.node.BigIntegerNode", - "/0/json/decimal" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/json/trailingZeroDecimal" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/json/zeroPointZero" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/json/negativeZero" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/json/exponent" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/json/exponentUpperCase" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/json/negativeExponent" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/json/longDecimal" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/json/true" : "com.fasterxml.jackson.databind.node.BooleanNode", - "/0/json/false" : "com.fasterxml.jackson.databind.node.BooleanNode", - "/0/json/null" : "com.fasterxml.jackson.databind.node.NullNode", - "/0/json/emptyObject" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/json/emptyArray" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0/json/nested" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/json/nested/array" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0/json/nested/array/0" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/json/nested/array/1" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/json/nested/array/2" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0/json/nested/array/2/0" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/json/nested/array/2/1" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/json/nested/array/2/1/four" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/json/nested/array/3" : "com.fasterxml.jackson.databind.node.NullNode", - "/0/json/nested/array/4" : "com.fasterxml.jackson.databind.node.BooleanNode", - "/0/json/nested/array/5" : "com.fasterxml.jackson.databind.node.LongNode", - "/0/json/nested/object" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/json/nested/object/z" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/json/nested/object/a" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/json/nested/object/a/deeper" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0/json/nested/object/a/deeper/0" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0/json/nested/object/a/deeper/1" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/json/unicode" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/json/escapes" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/json/key with escaped name" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/json/alpha" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/jsonb" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/jsonb/zeta" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/jsonb/alpha" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0/jsonb/alpha/0" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/jsonb/alpha/1" : "com.fasterxml.jackson.databind.node.LongNode", - "/0/jsonb/alpha/2" : "com.fasterxml.jackson.databind.node.NullNode", - "/0/json$array" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0/json$array/0" : "com.fasterxml.jackson.databind.node.IntNode", - "/0/json$array/1" : "com.fasterxml.jackson.databind.node.TextNode", - "/0/json$array/2" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/0/json$array/2/three" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/0/json$scalar" : "com.fasterxml.jackson.databind.node.TextNode", + "/0/json" : "tools.jackson.databind.node.ObjectNode", + "/0/json/zeta" : "tools.jackson.databind.node.StringNode", + "/0/json/int" : "tools.jackson.databind.node.IntNode", + "/0/json/negativeInt" : "tools.jackson.databind.node.IntNode", + "/0/json/intMax" : "tools.jackson.databind.node.IntNode", + "/0/json/intMaxPlusOne" : "tools.jackson.databind.node.LongNode", + "/0/json/intMinMinusOne" : "tools.jackson.databind.node.LongNode", + "/0/json/longMax" : "tools.jackson.databind.node.LongNode", + "/0/json/longMaxPlusOne" : "tools.jackson.databind.node.BigIntegerNode", + "/0/json/longMinMinusOne" : "tools.jackson.databind.node.BigIntegerNode", + "/0/json/decimal" : "tools.jackson.databind.node.DoubleNode", + "/0/json/trailingZeroDecimal" : "tools.jackson.databind.node.DoubleNode", + "/0/json/zeroPointZero" : "tools.jackson.databind.node.DoubleNode", + "/0/json/negativeZero" : "tools.jackson.databind.node.IntNode", + "/0/json/exponent" : "tools.jackson.databind.node.DoubleNode", + "/0/json/exponentUpperCase" : "tools.jackson.databind.node.DoubleNode", + "/0/json/negativeExponent" : "tools.jackson.databind.node.DoubleNode", + "/0/json/longDecimal" : "tools.jackson.databind.node.DoubleNode", + "/0/json/true" : "tools.jackson.databind.node.BooleanNode", + "/0/json/false" : "tools.jackson.databind.node.BooleanNode", + "/0/json/null" : "tools.jackson.databind.node.NullNode", + "/0/json/emptyObject" : "tools.jackson.databind.node.ObjectNode", + "/0/json/emptyArray" : "tools.jackson.databind.node.ArrayNode", + "/0/json/nested" : "tools.jackson.databind.node.ObjectNode", + "/0/json/nested/array" : "tools.jackson.databind.node.ArrayNode", + "/0/json/nested/array/0" : "tools.jackson.databind.node.IntNode", + "/0/json/nested/array/1" : "tools.jackson.databind.node.StringNode", + "/0/json/nested/array/2" : "tools.jackson.databind.node.ArrayNode", + "/0/json/nested/array/2/0" : "tools.jackson.databind.node.IntNode", + "/0/json/nested/array/2/1" : "tools.jackson.databind.node.ObjectNode", + "/0/json/nested/array/2/1/four" : "tools.jackson.databind.node.DoubleNode", + "/0/json/nested/array/3" : "tools.jackson.databind.node.NullNode", + "/0/json/nested/array/4" : "tools.jackson.databind.node.BooleanNode", + "/0/json/nested/array/5" : "tools.jackson.databind.node.LongNode", + "/0/json/nested/object" : "tools.jackson.databind.node.ObjectNode", + "/0/json/nested/object/z" : "tools.jackson.databind.node.IntNode", + "/0/json/nested/object/a" : "tools.jackson.databind.node.ObjectNode", + "/0/json/nested/object/a/deeper" : "tools.jackson.databind.node.ArrayNode", + "/0/json/nested/object/a/deeper/0" : "tools.jackson.databind.node.ArrayNode", + "/0/json/nested/object/a/deeper/1" : "tools.jackson.databind.node.ObjectNode", + "/0/json/unicode" : "tools.jackson.databind.node.StringNode", + "/0/json/escapes" : "tools.jackson.databind.node.StringNode", + "/0/json/key with escaped name" : "tools.jackson.databind.node.StringNode", + "/0/json/alpha" : "tools.jackson.databind.node.StringNode", + "/0/jsonb" : "tools.jackson.databind.node.ObjectNode", + "/0/jsonb/zeta" : "tools.jackson.databind.node.IntNode", + "/0/jsonb/alpha" : "tools.jackson.databind.node.ArrayNode", + "/0/jsonb/alpha/0" : "tools.jackson.databind.node.DoubleNode", + "/0/jsonb/alpha/1" : "tools.jackson.databind.node.LongNode", + "/0/jsonb/alpha/2" : "tools.jackson.databind.node.NullNode", + "/0/json$array" : "tools.jackson.databind.node.ArrayNode", + "/0/json$array/0" : "tools.jackson.databind.node.IntNode", + "/0/json$array/1" : "tools.jackson.databind.node.StringNode", + "/0/json$array/2" : "tools.jackson.databind.node.ObjectNode", + "/0/json$array/2/three" : "tools.jackson.databind.node.DoubleNode", + "/0/json$scalar" : "tools.jackson.databind.node.StringNode", "/0/json$null" : "null", "/0/_int4" : "[Ljava.lang.Integer;", "/0/_text" : "[Ljava.lang.String;", diff --git a/server/api-service/lowcoder-plugins/redisPlugin/pom.xml b/server/api-service/lowcoder-plugins/redisPlugin/pom.xml index f9271f90c5..4e4e52c688 100644 --- a/server/api-service/lowcoder-plugins/redisPlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/redisPlugin/pom.xml @@ -16,9 +16,6 @@ UTF-8 - 17 - ${java.version} - ${java.version} redis-plugin org.lowcoder.plugin.redis.RedisPlugin ${revision} @@ -31,7 +28,7 @@ redis.clients jedis - 3.3.0 + 8.1.0 org.slf4j @@ -55,7 +52,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/redisPlugin/src/main/java/org/lowcoder/plugin/redis/RedisPlugin.java b/server/api-service/lowcoder-plugins/redisPlugin/src/main/java/org/lowcoder/plugin/redis/RedisPlugin.java index cbf8d6b269..ba5504455e 100644 --- a/server/api-service/lowcoder-plugins/redisPlugin/src/main/java/org/lowcoder/plugin/redis/RedisPlugin.java +++ b/server/api-service/lowcoder-plugins/redisPlugin/src/main/java/org/lowcoder/plugin/redis/RedisPlugin.java @@ -90,7 +90,10 @@ public Mono createConnection(RedisDatasourceConfig connectionConfig) }) .subscribeOn(scheduler) .onErrorMap(t -> { - if (t instanceof ArrayIndexOutOfBoundsException && connectionConfig.isUsingUri()) { + // Jedis refuses a user name without a password with an IllegalArgumentException (before Jedis 8, with an + // ArrayIndexOutOfBoundsException); the exact class excludes its subclass NumberFormatException (a bad port). + if (connectionConfig.isUsingUri() + && (t instanceof ArrayIndexOutOfBoundsException || t.getClass() == IllegalArgumentException.class)) { return new PluginException(REDIS_URL_ERROR, "REDIS_URL_ERROR", t.getMessage()); } return t; diff --git a/server/api-service/lowcoder-plugins/redisPlugin/src/main/java/org/lowcoder/plugin/redis/utils/RedisUriUtils.java b/server/api-service/lowcoder-plugins/redisPlugin/src/main/java/org/lowcoder/plugin/redis/utils/RedisUriUtils.java index f622bbd26f..04c9d8ecef 100644 --- a/server/api-service/lowcoder-plugins/redisPlugin/src/main/java/org/lowcoder/plugin/redis/utils/RedisUriUtils.java +++ b/server/api-service/lowcoder-plugins/redisPlugin/src/main/java/org/lowcoder/plugin/redis/utils/RedisUriUtils.java @@ -61,13 +61,10 @@ private static String getUriHostAndPort(RedisDatasourceConfig datasourceConfigur /** * The user info of the URI, {@code user:password@}, each part percent-encoded (BF-055): Jedis reads them with - * {@link URI#getUserInfo()}, which decodes, and splits at the first colon, so a password with {@code @ : / # %} or a space + * the raw user info at its first colon and decodes each part, so a user name or a password with {@code @ : / # %} or a space * comes back unchanged. A user name without a password is kept as {@code user:@}, which Jedis sends as {@code AUTH user ""} * (a user with {@code nopass} is let in); without the colon Jedis would fail to read the password. A blank user name or * password counts as absent. - *

- * Limits: a user name containing a colon cannot be given: Jedis splits the decoded user info at its first colon, so the - * rest of the name becomes part of the password. */ private static String getUriAuth(RedisDatasourceConfig datasourceConfiguration) { String username = datasourceConfiguration.getUsername(); diff --git a/server/api-service/lowcoder-plugins/redisPlugin/src/test/java/org/lowcoder/plugin/redis/RedisEngineConnectionTest.java b/server/api-service/lowcoder-plugins/redisPlugin/src/test/java/org/lowcoder/plugin/redis/RedisEngineConnectionTest.java index d516b425e3..59d4786710 100644 --- a/server/api-service/lowcoder-plugins/redisPlugin/src/test/java/org/lowcoder/plugin/redis/RedisEngineConnectionTest.java +++ b/server/api-service/lowcoder-plugins/redisPlugin/src/test/java/org/lowcoder/plugin/redis/RedisEngineConnectionTest.java @@ -28,8 +28,8 @@ * is contacted: the host is a reserved test address that nothing answers), with the pool settings of {@code buildPoolConfig}; * an unparsable URI is reported; destroying null or twice does not throw. * - *

Limits: the pool settings are read from the Jedis pool's protected {@code internalPool} field by reflection (Jedis 3.3.0 has - * no public getter for them); borrowing behaviour against a server is RD-6. + *

Limits: the pool settings are read by reflection from the Jedis pool, which is a commons-pool2 {@code GenericObjectPool} since + * Jedis 4; borrowing behaviour against a server is RD-6. */ public class RedisEngineConnectionTest { @@ -40,10 +40,7 @@ public class RedisEngineConnectionTest { private final RedisPlugin.RedisEngine engine = new RedisPlugin.RedisEngine(); private static Object poolSetting(JedisPool pool, String getter) throws Exception { - Field internal = redis.clients.jedis.util.Pool.class.getDeclaredField("internalPool"); - internal.setAccessible(true); - Object generic = internal.get(pool); - return generic.getClass().getMethod(getter).invoke(generic); + return pool.getClass().getMethod(getter).invoke(pool); } @Test @@ -70,7 +67,7 @@ public void createConnectionBuildsALazyPoolWithTheConfiguredSettings() throws Ex } } - /** Observation: only an ArrayIndexOutOfBoundsException is mapped to REDIS_URL_ERROR; an unparsable URI reaches the caller as the raw URISyntaxException. */ + /** Observation: only an ArrayIndexOutOfBoundsException or a plain IllegalArgumentException is mapped to REDIS_URL_ERROR; an unparsable URI reaches the caller as the raw URISyntaxException. */ @Test public void unparsableUriInUriModeReachesTheCallerAsAUriSyntaxException() { RedisDatasourceConfig bad = RedisDatasourceConfig.buildFrom(Map.of("usingUri", true, "uri", "redis://bad host:1")); diff --git a/server/api-service/lowcoder-plugins/redisPlugin/src/test/java/org/lowcoder/plugin/redis/utils/RedisUriUtilsTest.java b/server/api-service/lowcoder-plugins/redisPlugin/src/test/java/org/lowcoder/plugin/redis/utils/RedisUriUtilsTest.java index 5ba8d44843..58b8f03f34 100644 --- a/server/api-service/lowcoder-plugins/redisPlugin/src/test/java/org/lowcoder/plugin/redis/utils/RedisUriUtilsTest.java +++ b/server/api-service/lowcoder-plugins/redisPlugin/src/test/java/org/lowcoder/plugin/redis/utils/RedisUriUtilsTest.java @@ -112,19 +112,16 @@ public void passwordsWithReservedCharactersRoundTripBF055() throws Exception { } /** - * BF-055, the user-name half: a user name with characters a URI gives a meaning to comes back unchanged, except a colon: - * Jedis splits the decoded user info at its first colon, so a user name with one cannot be given (the limit documented on - * {@code RedisUriUtils.getUriAuth}). + * BF-055, the user-name half: a user name with characters a URI gives a meaning to comes back unchanged, a colon included: + * Jedis 8 splits the raw user info at its first colon before it decodes, so the encoded colon stays in the user name + * (Jedis 3 split the decoded text, so the rest of the name became part of the password). */ @Test - public void userNamesWithReservedCharactersRoundTripExceptAColonBF055() throws Exception { + public void userNamesWithReservedCharactersRoundTripBF055() throws Exception { for (String username : RESERVED) { - if (username.contains(":")) { - continue; - } assertEquals(List.of(username, PASSWORD, HOST), readBack(username, PASSWORD), username); } - assertEquals(List.of("a", "b:" + PASSWORD, HOST), readBack("a:b", PASSWORD), "the colon limit"); + assertEquals(List.of("a:b", PASSWORD, HOST), readBack("a:b", PASSWORD), "a colon in the user name"); } /** diff --git a/server/api-service/lowcoder-plugins/restApiPlugin/pom.xml b/server/api-service/lowcoder-plugins/restApiPlugin/pom.xml index 912902ad37..c126ec425c 100644 --- a/server/api-service/lowcoder-plugins/restApiPlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/restApiPlugin/pom.xml @@ -16,9 +16,6 @@ UTF-8 - 17 - ${java.version} - ${java.version} restapi-plugin org.lowcoder.plugin.restapi.RestApiPlugin ${revision} @@ -47,23 +44,11 @@ - com.fasterxml.jackson.core + tools.jackson.core jackson-databind provided - - com.fasterxml.jackson.datatype - jackson-datatype-jdk8 - provided - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - provided - - io.github.vzhn netty-http-authenticator @@ -103,7 +88,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/restApiPlugin/src/main/java/org/lowcoder/plugin/restapi/RestApiExecutor.java b/server/api-service/lowcoder-plugins/restApiPlugin/src/main/java/org/lowcoder/plugin/restapi/RestApiExecutor.java index 3289ce10f7..9aa2c8b498 100644 --- a/server/api-service/lowcoder-plugins/restApiPlugin/src/main/java/org/lowcoder/plugin/restapi/RestApiExecutor.java +++ b/server/api-service/lowcoder-plugins/restApiPlugin/src/main/java/org/lowcoder/plugin/restapi/RestApiExecutor.java @@ -19,9 +19,8 @@ package org.lowcoder.plugin.restapi; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableMap; import jakarta.annotation.Nullable; import lombok.Builder; @@ -50,8 +49,10 @@ import org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType; import org.lowcoder.sdk.query.QueryVisitorContext; import org.lowcoder.sdk.util.CookieForwarding; +import org.lowcoder.sdk.util.HttpHeaderMaps; import org.lowcoder.sdk.webclient.WebClientBuildHelper; import org.lowcoder.sdk.webclient.WebClientRedirects; +import org.lowcoder.sdk.webclient.JacksonClientCodecs; import org.pf4j.Extension; import org.springframework.http.*; import org.springframework.http.client.reactive.ClientHttpRequest; @@ -61,8 +62,8 @@ import org.springframework.web.reactive.function.client.ExchangeStrategies; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; +import tools.jackson.core.JacksonException; -import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; @@ -101,7 +102,10 @@ public class RestApiExecutor implements QueryExecutor configurer.defaultCodecs().maxInMemorySize(-1)) + .codecs(configurer -> { + JacksonClientCodecs.apply(configurer); + configurer.defaultCodecs().maxInMemorySize(-1); + }) .build(); public RestApiExecutor(CommonConfig commonConfig) { @@ -405,7 +409,7 @@ private ResponseBodyData parseResponseDataInfo(byte[] body, MediaType contentTyp .dataType(ResponseDataType.JSON) .build(); - } catch (IOException e) { + } catch (JacksonException e) { throw new PluginException(REST_API_EXECUTION_ERROR, "INVALID_JSON_FROM_RESPONSE"); } } @@ -433,15 +437,15 @@ private JsonNode parseExecuteResultHeaders(HttpHeaders headers) { // Convert the headers into json tree to store in the results String headerInJsonString; try { - headerInJsonString = toJsonThrows(headers); - } catch (JsonProcessingException e) { + headerInJsonString = toJsonThrows(HttpHeaderMaps.copyOf(headers)); + } catch (JacksonException e) { throw new PluginException(QUERY_EXECUTION_ERROR, DEFAULT_REST_ERROR_CODE, e.getMessage()); } // Set headers in the result now try { return (readTree(headerInJsonString)); - } catch (IOException e) { + } catch (JacksonException e) { throw new PluginException(JSON_PARSE_ERROR, "JSON_PARSE_ERROR", headerInJsonString, e.getMessage()); } } diff --git a/server/api-service/lowcoder-plugins/restApiPlugin/src/main/java/org/lowcoder/plugin/restapi/model/QueryBody.java b/server/api-service/lowcoder-plugins/restApiPlugin/src/main/java/org/lowcoder/plugin/restapi/model/QueryBody.java index 5417c4ed9f..e4eec485c1 100644 --- a/server/api-service/lowcoder-plugins/restApiPlugin/src/main/java/org/lowcoder/plugin/restapi/model/QueryBody.java +++ b/server/api-service/lowcoder-plugins/restApiPlugin/src/main/java/org/lowcoder/plugin/restapi/model/QueryBody.java @@ -1,6 +1,6 @@ package org.lowcoder.plugin.restapi.model; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; /** * value is either JsonNode or String diff --git a/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/EchoServerStub.java b/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/EchoServerStub.java index 88e431c680..5dcf32a32a 100644 --- a/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/EchoServerStub.java +++ b/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/EchoServerStub.java @@ -16,11 +16,11 @@ import org.lowcoder.sdk.contract.RecordingHttpServer; import org.lowcoder.sdk.contract.RecordingHttpServer.Request; import org.lowcoder.sdk.contract.RecordingHttpServer.Response; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; /** * A local stand-in for the parts of postman-echo.com that {@link RestApiEngineTest} uses, served by @@ -69,7 +69,7 @@ final class EchoServerStub { private static final String CRLF = "\r\n"; private static final Pattern DIGEST_PARAM = Pattern.compile("(\\w+)=(?:\"([^\"]*)\"|([^,\\s]+))"); private static final Pattern DISPOSITION_PARAM = Pattern.compile("(name|filename)=\"([^\"]*)\""); - private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final ObjectMapper MAPPER = JsonMapper.builderWithJackson2Defaults().build(); private EchoServerStub() { } @@ -134,7 +134,7 @@ private static Response responseHeaders(Request request) { parameters.forEach((name, value) -> headers.put(name, List.of(value))); try { return new Response(OK, headers, MAPPER.writeValueAsBytes(parameters)); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { throw new IllegalStateException(e); } } @@ -234,7 +234,7 @@ private static void readMultipart(byte[] body, String boundary, ObjectNode form, private static JsonNode parseOrNull(String text) { try { return MAPPER.readTree(text); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { return null; } } diff --git a/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/RestApiEngineTest.java b/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/RestApiEngineTest.java index fcc69f756f..ba7b8eb65b 100644 --- a/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/RestApiEngineTest.java +++ b/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/RestApiEngineTest.java @@ -1,8 +1,7 @@ package org.lowcoder.plugin.restapi; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.fasterxml.jackson.databind.node.TextNode; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -26,6 +25,7 @@ import org.springframework.web.reactive.function.client.ClientResponse; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import tools.jackson.databind.node.StringNode; import java.net.URI; import java.util.List; @@ -141,8 +141,8 @@ public void testPostWithTextPlain() { .assertNext(result -> { assertTrue(result.isSuccess()); JsonNode data = ((ObjectNode) result.getData()).get("data"); - assertTrue(data instanceof TextNode); - assertEquals("{\"key\":\"value\"}", data.asText()); + assertTrue(data instanceof StringNode); + assertEquals("{\"key\":\"value\"}", data.asString()); }) .verifyComplete(); } @@ -196,7 +196,7 @@ public void testMultipartFormDataWithFileType() { assertEquals("data:application/octet-stream;base64," + "iVBORw0KGgoAAAANSUhEUgAAA5wAAAEcCAYAAACrnbsgAAAACXBIWXMAAAsSAAALEgHS3X78AAAfxElEQVR4nO3d3XHcxrouYPiU76l7XIhO4IiOQHQE4opAdACnTEcgKgLLtQMwFcGiIjAZgcmdwCIvcC9GwFMtf7M3zOHP/HQDDczzVLGW1wxFDjFAT7/9Nbq/u7+/bwAAACC3/+OIAgAAUILACQAAQBECJwAAAEUInAAAABQhcAIAAFCEwAkAAEARAicAAABFCJwAAAAUIXACAABQhMAJAABAEQInAAAARQicAAAAFCFwAgAAUITACQAAQBECJwAAAEUInAAAABQhcAIAAFCEwAkAAEARAicAAABFCJwAAAAUIXACAABQhMAJAABAEQInAAAARQicAAAAFCFwAgAAUITACQAAQBECJwAAAEUInAAAABQhcAIAAFCEwAkAAEARAicAAABFCJwAAAAUIXACAABQhMAJAABAEQInAAAARQicAAAAFCFwAgAAUITACQAAQBECJwAAAEUInAAAABQhcAIAAFCEwAkAAEARAicAAABFCJwAAAAUIXACAABQhMAJAABAEQInAAAARQicAAAAFCFwAgAAUITACQAAQBECJwAAAEUInAAAABQhcAIAAFCEwAkAAEARAicAAABFCJwAAAAUIXACAABQhMAJAABAEQInAAAARQicAAAAFCFwAgAAUITACQAAQBECJwAAAEUInAAAABQhcAIAAFCEwAkAAEARAicAAABFCJwAAAAUIXACAABQhMAJAABAEQInAAAARQicAAAAFCFwAgAAUITACQAAQBECJwAAAEV877ACADyubdvDB09cdV339dFvBmDJd/f390sPAgDsqgiZJ03TvHviEFw3TfOp67qzpWcA+AeBEwDg76D5qmmas2eC5kMpeB51XXez9AwA3wicAMDOi7B50TTNmzWPxV3TNIdd110tPQOAwAkA7LYtwuZCCp37U7m3s23b/fR6l55Y382UqrsZ/+6vBhhgdRYNAgB23ekWYTPZi6m4R0vP1Om4aZoPGV7Zxzh2U5Hr775MVe2lR4FH2RYFANhZUfX6JcPf/+6RFW0Bdp7ACQDsspOMf/vx0iMAO07gBAB2Wc6qpAonwAMCJwCwy7a5d/Oh10uPAOw4gRMAAIAiBE4AAACKEDgBAAAoQuAEAHbZZca//XrpEYAdJ3ACALvsPOPffrb0CMCOEzgBgF2WQuJdhr//TuAEWCZwAgA7q+u6r03THGf4+0/jZwHQI3ACADut67o0rfbzFsfgc9d1n5YeBUDgBADoui5VOX/f4ED8Hv8WgEcInAAAf4fOk6Zpfmqa5naF45G+51/xbwB4wvePPwwAsHu6rrtomma/bdvDpmmOmqY5eHAQrpqmuYhpuAC8QOAEAHgggufF0hMArMWUWgAAAIoQOAEAAChC4AQAAKAIgRMAAIAiBE4AAACKsEptxWJJ9pdcdV339YXvYUNt26bl8F899q9jBUMye+a8/9p13dXSo/xD27b7aUuHF47KTdd1N0uPspVnzt1q2+m2bV89su3HN9o4GMYzbYe2mlkQOEcUYWY/PuwXwebtuq+obdvFf16nTnnsEXYTnRwdhhVEp+swvhbvx95z//LBcb/p7c3mmK8gzv/+8X7z0r/qHfPLB8d8p4JoHLuDB23Hi8fvwc9Y/Kd2YwPRQey3Gau0F4u24mKM8zbauaPea372nHniejvXAYbNbNHXuIvr76rXfig2MBnf3d/fe7cGEpWHw94H/rONTEbX0UCd1dox73XettJ13ekav3PR+TpZt7O+gi+pYxads1orG8crVMJekkZfz174nv7v3I/jnY7766Vv2NxdHO+zOYalOG5HvY7KEG3Hde8crrXdyHEOr9xu9M7f40zvwW0c408lQ1wcp+NNBjSfkF73WVxvo4TPXO99AcUHHeM8PF56Yj2Hmc6Hy4J7la71+bKKtm3Ttf4hw4+67Lpu5T5L27ZH8Z69W3pyc1+ifc56jKAEgbOwwqFmE4N0cNaV60Og67rvlh58IN6Tk/gq3XFfBKHT2qoCbdteZOhwrPShGwMKJ5k/bJ+SzvFP0Rme9AhwgaCwqVrbjRzn8IvtRrQZ6Zx6v/RkPqnjfpIz3Mf5c5p5cOehz2O0b7ne+wI+rjPwuYloT/+s8G/Pba1Qt4qhA+dA1+BdtE+fVD2plUWDCkkdlGjY0ofwH5WEzSYavV+apvlP27ZnMVK6M3rvyYeBqkR70UldHO9H7wedq3R+tW17Hp2jIcJmE+f4b+l9btv2ZOnZCUidlLZtF21HDZ3qnW034hy6KRw2m3if/2rb9tO27USact227VWcPyU7uk2vfTvdtfYNnpIGBXpteOlrcC/6NDdRSYXqCJwF9DooQ4WaTS06Clt3cGrX64CN+Z68n3IIWleM7F4NGDQfSu/zb+l9f2ZBhqoM3EnZ1E4MoMSg4XkMXgzZZqRgfxX36a4tBtX+GmGQM7WtF5u+bpiL1KeKQdah2/DUTv07tVsGf6iNwJlRVHOuRuigbGurDk7tIvhcVFJlXoSgi5l31s8iNNVwHaT3/c/oiFcpws3ZSJ2UTb2f64h6XJsXIw6WvI7wtvJ9er2AnGO64KbexOtWZWHnxDV4FX2qMb0z+ENtBM5M4gP2qqKps+tau4MzBREyagk+fW+jsz6rD4TeB27p6Yeb+FBj0I/pqReVHrOXLEbUP73wfZMR50cNbXk6tn+s0iZXEJD7FufErD5L4DnxWX5TUR/wjdBJTQTODOKD9d8Tq2o+ZuUOzhRExWjM0f6X7M0p5Pc6vTUPuryNY15F6IzOwJQHqhZ+iett0nrncE1V5j+e6zRWfN39odLJLojr86LCPuCe0EktBM4tRVj4Y9J/xLJnOzhTEPdJTqFiNKeQX3vYXHhTQ3W5V9mc+kDVwvsZhM5az+HnBklqvu7OdHaZs4rD5sJeXIdPtR8wCIFzCzF6O7ewufBcB6dq8b78NrGXPelqQASNKVXpRv0Qjt97PqOwufC+5ntlnxPTgms9h/di38t/mMB19+jrhjmYUDv+xnXI2ATODUV1Ys4X8F7s6zQpE39fJlkNiOrsFO8/fDPiwMrpDKbRPuXDVFYFXojBnrEX+njJu/6g1ISuuzdTHYSAF5xPaJG3d6a4MyaBc3NnM6xOPPR+gvvtTblqlF731JYz35/iwETPm6Fff4Sx2sPNtqY2hWsqg1TfztVol6d03X3YtT2fmb23leyRvI7ZLO7G9AicG4iR5ak1NJua2sj01KtGrydWoX09g4GX9wOP/A59TV03TXO79GhZ6byY0n6zUzmHX8fnzxQHPFU5YVyvrR7NWL535DcyxAfnZdM0X2MFy6ek6ZevCoff1Bk/6bru69IzlPJt6kvXdeeO8GBSRW6/9Hke1c0S1+tdVPfT4hU3XdddLH3H8utIFafD+CoxLewk3Rep7chuqusGfLu/t+u6m6VngKGcup+TMQica4rRoRKds+toBC66rnsuZD4qOpCpSnNcYOT7aEcbqOsRK6aDBKDK3MYAyhiVm8U9y6VHf3P//HTMUid+reuzF0i//btoP3LfE7gXP9M0LhaOVTphVK8NaDMGgXN9uaeJpQ7j8UsViZfEv7+IxRlOMu8/OefAuVJlKO5HO4ivwwE2WN+L93GOnbPb3jG/eqriEfd8HfSqcKXD/7dtPZ46B3L9jqVHNvc5nSM5BiV67cdZXOu5BtVOZho4b2OT98XXq96Mk5qn9T/1upuBbhPJGTjPog3JpeY9mx9K793HpUfXk2u2xWXm96Hv0c+GibuMl784ZvvxNWTbcRSfwTCY7+7v7x3tFUUH+D8Zf+SXCJvZq1iZ9we967qu6AIgEZSH/MDfqDK0EAH0JDpQJVep++GpQLattm0vBr4XOQWkjQNdXH+nhVfmvOy6rsgKq1FF/HPpic187rquSDU2zu2cezv+uMmsjVUMfA7fRng+f+majHuCjypZRba2113sfNhG27a5OkMfu66rfqAw42fuJP7ehRH6GotB7fNVqoq9a/Co4Gyf4n06eMiiQevJubDIdamw2fxdsUhB6velJzazN6MVBlPj/2vXdfubhs3m7+P7NT5kDzKMND9nDhXOdK7/lALSNtXD1FmOkPVDb5Q4t7cFt/TI9XPvSi7IE23SYfyeHKa+FH86Dj9Hm/FplQGg1LEc4Fx9yW2lr3tSW+bAFlLfYD8++1aqKPauwf2CfYu9qW1dxfQJnOvJ2XE6GuD+vNOMncY5BM4UfA5S52vpmQ31guePGY9139HEtpd4KFXiDnJOU43gmT4sf116Mo9SIT/XHqtnpduO+Pm5Qu2UOzaX0WHcaHCqd65+XnqyrC/R1tX4unV0mbvrqOSfbtpW9/oWPxXqW0xuz2+mTeBcT66pW5+HWKkvGrpc8/SnPv0ifQAcljruMUVsP35PTnsDLGRTyq+lpn02fx/zNHDw89IT23tbqKKf6xoa5N6bCCs5tlOZ6hZSqZ0+zHSP7PGAoTO97iwDmoVet8DJnH2OvkaWaeMxWJtzxsmC65BBCZwryjz9YMhFNHLdKzPl0bBF2ByiKlTig2FK+xku/J6zkvyUCEUlQmeJY54rxA65kEaW97Bt26m1H5e5B0vi5+UekHqoxL29J5n3cd2b+KwNeMrnmD6bta8R4TX3Z5JrkEEJnKvL1Vm8HXjBhOoWZxjY3RBhc6EXOnN6PbEO+5eu6wYLyRE6c9/rUuK+wyyLSw28j2GuqdBT6tzcFrzvtOR1cVvi50eblnuauel8zM114Rk9Z5nvq57qzBMmSuBcXa7AWXLLBZYVW5jpKTGgkDsATWVa7d0YrzXudclZPao25A/5ujIOjk1p+laWrWYeE9PjclYL+0ovQlfqdcPU3Q3UxtnTmMkSOFeXq5M3x32lavVlrM2NIwDl7KBNpcNerLO+yu9eemQ7uYNzrqnWQwfhsVZZHcPlAG1GiT2NLwvvH9tkvnfY/WPMySCfe9E2ZetXTPBWByZM4FxdrilhQ1c4d/mDfex7H3NOQ3szga1pbrfZamZb0eHOGY5yXzu5qoVTXURqCoaoIJT4DBhi+ySzc2DZ0J97Oa9D93EymO8d6pWdZLo4h76ncup74G3qy8D3ui1JH0Jt237KuHnzYaHqSC417BmaXsOfS49uJoX8VyNWbJ+SVtE9GWJRpubv83hXBq1uh5gRkQZG2rZdenwLtwNUNxuBEx419Ode6kO+X3oUKidwrmjghX6yiJV130ztdWdSSzBLr+OXpUc3U/P0l7uhtut4TnTmb3Mt0BPHPFdH+yrjQg2/tW37dcyK8gwNef7mPEeH2ibna+agDHMw9Oferi8EyUSZUjtTsez86AFgJHdj3bv5iJyBoObAeV5RJbDWe81ydxT+aNv2bAJTradiyApeztkXQ7Z1pbd1gSn5MsLnXm0zbmAlAucMRWXzJuNUzqmpJmhHZTzXYjE1L2Ne0+BGzteSM+SXCDRpatV/InhaiGU7k5wyOtB02gWdXfhfg1cbpzjbDhqBcz5SRbNt2+O2bS/iHrZdDZtNhR3HbK+n4mpWNcc8cwc826IKcU9xqQpRCp5/tm17E+HzWOVzLXcV3qu7ChVHGI/7mmFF7uGcoFjK+lXsDXoQXzbx/V+1fQikEcl3S49uZr/CrXWuK+ysX2a6JnJfV2mK9W9Lj+bzOsLnt0Ul2ra9i/PvJr7StfHVKPmSqR4PFUcYj3YUViRwVqIXIpvefWOvelP69jMuMjFrY69O+4jUyf+w/PBGci5ik0uNH7o5F+jJ6SxWNRxqBsJeHIfFsfh2HsbiL9cRWC4WgXTg6Zk1mWpwU2GBkUx0VgSMQuAcWNxndfCgOrnL019zq3GT+pwfSjXum1VbwG9yHvN0zeYKYrHS56eMAxDbWKxg/T/BPILoZQT29Ddf7EinSqUCAAoROAuLgLn4Mu21vOo6x2n64sy3E6i1wlmlrutO0z2WFc9YWFREv23n07btdSzEdG4qLsA37p+GNQicBUTITB3KI9XLwc29Q1zj1ig1VsBqr8qltuGvpUfr9Ca+PsQep2la8FmFU9cBhmI6LazBKrWZ9FaJvYlVYt8Lm/TcZjoYNU6pnbvsIT8qhT8vPVG/1zEdOG3Fcm4rFgDgJQJnBm3bnsR9bH9Y2IcnzLkaNPeqcpGQ33Xd2URD58K72IrlQvAEAJ4icG4hrSzbtu1VbHOgmslOqnRRmUmE4BmEzibu9/wz9v9UgQcA/kHg3FDbtqdxD9abIr8A2AkROn/MOO16LOk2gqvY4gkA4BuBc01xr+ZZJdsaAI+bVOiJezrTa/596clpSbcU/BWr8AIACJzriOliFzGSPwWfm6b510Re69ztz/XvM40yjzQ1ueu6k6h21rif7Dr+EDoBgEbgXNunCUyhvY0qyQ9d1x1bursac15Mau5TKAe9hlK1s+u6tAjPTzFoNFUpdB5N+PUDABnYh3NFcc9mTZXN21j5dPGVpuRd2Rtv9gwgrCZn1XWUBYi6rkuzKS5iFezj+JraPeNpIaH9SheWAgAGIHCuIBbBGPqezcWUuov436sIG1c6b8+qrtqWeRGVGldfrXFK7WyqrnG9p9kVn1J4a5rmsPdVe+U8rd6d7nlX6QSAHSVwruZT4Z9/HcHyQpVyazWGn7nf45jC3fnSo+Oa5TGPtuEsvpoIoAe9r/0Kq6Dv0j6dUbEFAHaMwPmC2ND87fPftZHbRcdRwMyqxHu1rZyb4td4rtS4IFK2CmfNQSnajpuHgT+q6oswehj/PWY19KQ3WwMA2CEC58tOCvzMj6lqampsGXHPWE3BLOf0zhoDZ43TV2sceBhMbLNy9UgQXYTPw3jfhqqGvqvwugQABiBwPiO2e3j39Hes7S519KIzSDmHiymHlZh74HyTrpVaBlAy3zM79e1J/qFXrV1MyX0V91cexv/uLf2jfGq7LgGAAdgW5Xm5F7o4GiFs7uIeiTmnsG4lwk+2qYwVV4iqOeaZr9tZV+Ri7880rf+467rUVvxcMGRbOAgAdpDA+bycnejPI90LNvc9Eh9TU8c25+b3NVfbajrmAueGInymdu9fMSMjp11siwBg5wmcz8vZQTpdemQYNS7oUtpeRRvO53wdNU/FPorpmaOKinLO+xJ3cqGbruvOo+24Xnpyc7Vv4QIAFOAezufl6rjejjgVsqapjkM6GXurjgi9OTvZNYefvQjXY9+jl3WRrxyzEmLrkhwDP4PuwZt+V5zDV7nu7bQ9CgDsHoFzGKNUpqKju6tVhbcVdG5zr3Bce0f9dMzAGef7+6UnNpdrCnOaVv1h6dH1fRx6pkQaKGvb9lOm1w8A7CBTap8Q2wfkMtZUyF1fpGOsacyL6mbOrTmuJ7CNzuu2bUc75gXe71wBP9fshrGmLFtZFgDYmMA5byX2EJ2SVOUc/BjEvYyflp7YzqjTg9dwEpXGQcUAUc7qZpPxmOcKnKNMj7d3JgCwDYFzGINXJtq2PbZIxzenmfdlXMVZgWM/lSpTutfvfMgFhOJ35Q7ktxm3MMoV2N6MuDDTrPYjBQCGI3AOY9DAU6jCNlWDBqCYUvpu6YntXE+syvRmqPMv3teLXIva9GQL+Jnfu7Gmye/iatfAy3Z1YUJgDQLnEzIvNvN24MrEWYEO+JSlauNF6fcgpu+WWFxlioMH79u2LVqV7YXNnNugLOR+7TkXIBpUHOdcFXvTc2FeDEYBLxI4hzNIZSI6+bkrbHPwJkJnkWpzHPfflp7Y3t2E7t986FvoLBH04z7RUmHzc4GKcq7puW8zL2i2imxtl/tBYXZej9AmARMjcD4v56bnnwaosJ0VWDhlThahM9tCQumDtm3bq4LH/dMEVqd9TjouVzk7JPH+XRUKm02h+2VzDhoUCfHPyFVVdR8ozFPx/g0wbQLn83JuZ7JXauGX1NC3bXshbK4kvQ+/tW17EwsrbSSCZno//ywYfO5mci9umo75ZzpHtwme6f1K71tUkktNGb8ssXdr/My7pSc283rAe2RPM27vM9b2UMCynLMN3sTA4q5vxQY84fvHHybkDnHv2rZNlY7jXFWrqPacumdzbanT/kdsan8e7/XNU2EjpnAexAIJRwOtADz16uZDbyN43vaO+dVT0yxj+nP/mA9xjpe8R/I8Y3vyPs7Jo1LnSITNnPckT3VqOBWKAcMa7x88zLwf8dlTbeSWcv/M9Jn477Zt72Jw6dHP0jWU+ruBEQicz8te6Yj7K9NI4GnXdRtVPGPqynHss2nrk+3sRQj4FgTatu3/sNsRj2/aliNnp6Um6Zj+El/9Y76oAI41ePJ74Q7OaeYBrBTgb2LQJNvgRFShc1Y2mzifS7Sn7K7jzOdoLm8zv66LQottlZpxsJfpGJT6u4ERCJzPSJ3Ptm0vC3yoLaprpytWevZjJPcwvmr8kJ2jMcP84KuRVmDMKv1thKxiCrUne1GFPInZE6ktuXiqLXlKhMyjgtX7qewjCzshDVDFbBOD1kBxAufLzgoGvKcqPelD4JVpsjvrd9WgwWWb5v6CNCvhr+e/ZSOPVer7i/T0z6f93lTEgwHambnciwxzY+0HYBAC5wvStNeoRA45CljjiKO9toZx3XVdtlV0WcnHoQJ+13VpOv3vi0GmwvoDZWPOipjbvcgwFznvKwd4klVqV7OL0xsfmkrgvM24GujQ7obarzWznNsHDe3LCPfKnsZ5uguuZ3wvMkxa13XnO9QWASMSOFcQ1Y/P1b/Qx33JtP/dVPbYupnoAEEKm4cTXZXvfKLXx/UY50pU+44mPDCyqqkOoMAuMSAEFCdwru5kgpWcRYc6x2p0pfaazC5GbX+eyuvthc3J7lPYdd3xxDb2v45jPspUz3iv5zxzYsoDKLAzYrX8Kc9SASZA4FxRdEwPJ1SVuOt1qHNtl3Cw9GCl4kN0ClW3yYfNnqOJdFxGDZsLExwYWdWczmnYBbsw4wIYkcC5huigHkygU51e30GvQ51rQZTDpUcqFlW3jxW/xOs5dcx7gzI1Xx+fawibCzEw8uOMOnu3wiZMS8xEmNKAOjAxAueaeg1zrdMHLx+Zypar8zepwNn8/X6dVlpF+jLHjnkKcl3XHVRaXf41DULUtmJqnAMHE5uS/JgvMdAlbMLExHUrdAJFCJwbiE71YYXVs7S9w1L1Jv5/jpXo3rVtO5XFg/5Hr4pUQ+UtfZj/q+u6ozlvFRHV5Z8r6bykIPdj13XV7gWZBoiiTfl1gh2+2104p2HuInTux+ARQDYC5xaievZDBZWJ9Pt/eGH7gVzTaie50En6II3K28cRO/Tpd+/HvXuzF0H/YMTOSwpCP8cgzCSqbhGK90c+T1d1G4NcO3NOw9zFgHq6p/OnGcy6ACohcG6pV5n4aYSOdfp9P0WH+qXVIHN1CE+nWOVciFC+mPI5RIf+LsLDtwGBXasAxfUxdOdlETT3I/ROSnT4TiN4/lrhPnmXveP73CAXMFFpO7jo26RB9d+tZAts43tHL4/Yq/Oibdv9WPHtuNBWIqnRT53o83W2HEgViLZtc00B3s94X+jg4rgdR3A+ii1vcr5Xd1FRPp9i4Ckhro/DuD5O4ri/zvirbmNQ5WxmizCliuenWCH6OO6xGmOLoss4vmu1OwM4yzR7I9cMkFV53fW8ltqNer3F9Z7a7CY+Mw9j0PYg9udO/7u39A9Xd/3ISvpXBf/uXOfMmO9Lrr6cbasYzHf39/eOdiEPGufDCGrrdLJvo0G4iAb4Yq4VsrZtU6Xkw9IT67uMUdl1f/8ifB70vlb9EL2O92nxHk2iE9S2bXqdb5eeWN/HTSpdEaL6nZd1gtTlg2O+MwvVZGhXXjLJ8xkAqJMKZ0ERDs8fTmeNDuNze1peWXxjWHG8l6qREYoenUKsI76dCIlLQbFt26cGDL5aAfXZdmU/wmfTqz685KY3yq3dAQCyEzhHEJ06YWUCBJzhCfKbialvi/DoGAIAVbBoEAAAAEUInAAAABQhcAIAAFCEwAkAAEARAicAAABFCJwAAAAUIXACAABQhH04AQCAF93/v/972jTNB0fqUT9991//bR/sR6hwAgAAUITACQAAQBECJwAAAEUInAAAABQhcAIAAFCEwAkAAEARAicAAABFCJwAAAAUIXACAABQhMAJAABAEQInAAAARQicAAAAFPG9wwoAAKzgpmmaSwfqUV8fexCBEwAAWMF3//XfZ03TnDlWrMOUWgAAAIoQOAEAACjClFpqcZHpddwsPcJTzjId91zvHQAAM/Pd/f299xQAAIDsTKkFAACgCIETAACAIgROAAAAihA4AQAAKELgBAAAoAiBEwAAgCIETgAAAIoQOAEAAChC4AQAAKAIgRMAAIAiBE4AAACKEDgBAAAoQuAEAACgCIETAACAIgROAAAAihA4AQAAKELgBAAAoAiBEwAAgCIETgAAAIoQOAEAAChC4AQAAKAIgRMAAIAiBE4AAACKEDgBAAAoQuAEAACgCIETAACAIgROAAAAihA4AQAAKELgBAAAoAiBEwAAgCIETgAAAIoQOAEAAChC4AQAAKAIgRMAAIAiBE4AAACKEDgBAAAoQuAEAACgCIETAACAIgROAAAAihA4AQAAKELgBAAAoAiBEwAAgCIETgAAAIoQOAEAAChC4AQAAKAIgRMAAIAiBE4AAACKEDgBAAAoQuAEAACgCIETAACAIgROAAAAihA4AQAAKELgBAAAoAiBEwAAgCIETgAAAIoQOAEAAChC4AQAAKAIgRMAAIAiBE4AAACKEDgBAAAoQuAEAACgCIETAACAIgROAAAAihA4AQAAKELgBAAAoAiBEwAAgCIETgAAAIoQOAEAAChC4AQAAKAIgRMAAIAiBE4AAACKEDgBAAAoQuAEAACgCIETAACAIgROAAAA8mua5v8DhCQidUReNJIAAAAASUVORK5CYII=", - fileValue.asText()); + fileValue.asString()); }) .verifyComplete(); } @@ -255,8 +255,8 @@ public void testParamBinding() { ObjectNode data = (ObjectNode) result.getData(); ObjectNode postBody = (ObjectNode) data.get("data"); assertEquals(3, postBody.size()); - assertEquals("jack", postBody.get("name").textValue()); - assertEquals("jack@jack.com", postBody.get("email").textValue()); + assertEquals("jack", postBody.get("name").stringValue()); + assertEquals("jack@jack.com", postBody.get("email").stringValue()); assertEquals(30, postBody.get("age").asInt()); }) @@ -404,7 +404,7 @@ public void responseJsonTypeTest() { assertTrue(result.isSuccess()); assertNotNull(result.getData()); JsonNode value = ((ObjectNode) result.getData()).get("key"); - assertEquals("value", value.asText()); + assertEquals("value", value.asString()); }) .verifyComplete(); } diff --git a/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/RestApiHttpsTest.java b/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/RestApiHttpsTest.java new file mode 100644 index 0000000000..f60019101a --- /dev/null +++ b/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/RestApiHttpsTest.java @@ -0,0 +1,163 @@ +package org.lowcoder.plugin.restapi; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.lowcoder.sdk.contract.RecordingHttpServer; +import org.lowcoder.sdk.contract.RecordingHttpServer.Response; +import org.lowcoder.sdk.contract.SelfSignedCertificate; +import org.lowcoder.sdk.exception.PluginException; +import org.lowcoder.sdk.models.QueryExecutionResult; +import org.lowcoder.sdk.plugin.common.ssl.DisableVerifySslConfig; +import org.lowcoder.sdk.plugin.common.ssl.SslCertVerificationType; +import org.lowcoder.sdk.plugin.common.ssl.VerifyCACertSslConfig; +import org.lowcoder.sdk.plugin.common.ssl.VerifySelfSignedCertSslConfig; +import org.lowcoder.sdk.plugin.restapi.RestApiDatasourceConfig; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The REST API executor against an HTTPS server with a self-signed certificate generated in the test + * ({@link SelfSignedCertificate}, {@link RecordingHttpServer#startSecure}), once for each SSL mode the datasource offers + * ({@code sslConfig.sslCertVerificationType}): the default (no {@code sslConfig}), {@code VERIFY_CA_CERT}, {@code DISABLED}, + * {@code VERIFY_SELF_SIGNED_CERT} with the server's certificate and with another certificate. The datasource is bound from + * the JSON map the client sends ({@code RestApiDatasourceConfig.buildFrom}), so the polymorphic {@code sslConfig} binding is + * part of the path. A request that passes the handshake is recorded by the server; one that is refused by it is not. + * + *

Limits: one self-signed certificate (CN=localhost, SAN 127.0.0.1); no CA-signed certificate, so "verify the CA" is + * shown only by its refusal of the self-signed one; no client certificate. + */ +public class RestApiHttpsTest { + + static final String TAG = "[RestApiHttpsTest] "; + static final String PATH = "/secure"; + static final String ANSWER_JSON = "{\"secure\":true}"; + static final String TYPE_KEY = "sslCertVerificationType"; + static final String CERT_KEY = "selfSignedCert"; + static final String SSL_KEY = "sslConfig"; + static final String URL_KEY = "url"; + static final int OK = 200; + + @TempDir + static Path directory; + private static SelfSignedCertificate serverCertificate; + private static SelfSignedCertificate otherCertificate; + private static RecordingHttpServer server; + + private final RestApiCallSupport calls = new RestApiCallSupport(); + + @BeforeAll + static void startServer() { + serverCertificate = SelfSignedCertificate.generate(directory, "server"); + otherCertificate = SelfSignedCertificate.generate(directory, "other"); + server = RecordingHttpServer.startSecure(serverCertificate.serverContext(), Map.of(PATH, + new Response(OK, Map.of("Content-Type", List.of("application/json")), ANSWER_JSON.getBytes(StandardCharsets.UTF_8)))); + System.out.println(TAG + "HTTPS server on " + server.baseUrl()); + } + + @AfterAll + static void stopServer() { + server.close(); + } + + private static RestApiDatasourceConfig datasource(Map sslConfig) { + Map map = new java.util.HashMap<>(); + map.put(URL_KEY, server.baseUrl()); + if (sslConfig != null) { + map.put(SSL_KEY, sslConfig); + } + return RestApiDatasourceConfig.buildFrom(map); + } + + private Object call(Map sslConfig) { + int before = server.requests().size(); + Object outcome; + try { + outcome = calls.run(datasource(sslConfig), Map.of("httpMethod", "GET", "path", PATH), RestApiCallSupport.visitor(null, null)); + } catch (RuntimeException e) { + outcome = e; + } + System.out.println(TAG + "sslConfig=" + sslConfig + " -> " + outcome + " (requests recorded: " + (server.requests().size() - before) + ")"); + return outcome; + } + + private static boolean causedBy(Throwable failure, String className) { + for (Throwable t = failure; t != null; t = t.getCause()) { + if (t.getClass().getName().contains(className) || String.valueOf(t.getMessage()).contains(className)) { + return true; + } + } + return false; + } + + private void assertAnswered(Object outcome, int recordedBefore) { + QueryExecutionResult result = assertInstanceOf(QueryExecutionResult.class, outcome, String.valueOf(outcome)); + assertTrue(result.isSuccess(), "the call over TLS succeeded: " + result); + assertTrue(String.valueOf(result.getData()).contains("secure"), "the answer body is returned: " + result.getData()); + assertEquals(recordedBefore + 1, server.requests().size(), "the server recorded the request that passed the handshake"); + } + + private void assertRefused(Object outcome, int recordedBefore) { + Throwable failure = assertInstanceOf(Throwable.class, outcome, "the call must fail, it returned " + outcome); + assertInstanceOf(PluginException.class, failure, "the executor maps the failure to a PluginException: " + failure); + assertTrue(causedBy(failure, "SSLHandshakeException") || causedBy(failure, "SSLException") || causedBy(failure, "PKIX") + || causedBy(failure, "CertificateException") || causedBy(failure, "certificate"), + "the failure names the TLS handshake: " + failure + " / " + failure.getCause()); + assertEquals(recordedBefore, server.requests().size(), "a refused handshake reaches no handler"); + } + + @Test + public void withoutAnSslConfigTheDefaultTrustRefusesTheSelfSignedServer() { + int before = server.requests().size(); + assertRefused(call(null), before); + } + + @Test + public void verifyCaCertRefusesTheSelfSignedServerLikeTheDefault() { + int before = server.requests().size(); + assertRefused(call(Map.of(TYPE_KEY, SslCertVerificationType.VERIFY_CA_CERT.name())), before); + } + + @Test + public void disabledVerificationAcceptsTheSelfSignedServer() { + RestApiDatasourceConfig bound = datasource(Map.of(TYPE_KEY, SslCertVerificationType.DISABLED.name())); + assertInstanceOf(DisableVerifySslConfig.class, bound.getSslConfig(), "DISABLED binds to the disable-verification config"); + int before = server.requests().size(); + assertAnswered(call(Map.of(TYPE_KEY, SslCertVerificationType.DISABLED.name())), before); + } + + @Test + public void verifySelfSignedCertAcceptsTheServerWhoseCertificateIsGiven() { + Map ssl = Map.of(TYPE_KEY, SslCertVerificationType.VERIFY_SELF_SIGNED_CERT.name(), CERT_KEY, serverCertificate.pem()); + RestApiDatasourceConfig bound = datasource(ssl); + assertInstanceOf(VerifySelfSignedCertSslConfig.class, bound.getSslConfig(), "VERIFY_SELF_SIGNED_CERT binds to the pinned-certificate config"); + assertEquals(serverCertificate.pem(), ((VerifySelfSignedCertSslConfig) bound.getSslConfig()).getSelfSignedCert()); + int before = server.requests().size(); + assertAnswered(call(ssl), before); + } + + @Test + public void verifySelfSignedCertRefusesAServerWhoseCertificateIsNotTheGivenOne() { + Map ssl = Map.of(TYPE_KEY, SslCertVerificationType.VERIFY_SELF_SIGNED_CERT.name(), CERT_KEY, otherCertificate.pem()); + int before = server.requests().size(); + assertRefused(call(ssl), before); + } + + @Test + public void anSslConfigWithoutATypeBindsToTheCaVerifyingDefault() { + RestApiDatasourceConfig bound = datasource(Map.of()); + assertNotNull(bound.getSslConfig(), "an empty sslConfig object still binds"); + assertInstanceOf(VerifyCACertSslConfig.class, bound.getSslConfig(), "the default type is VERIFY_CA_CERT"); + int before = server.requests().size(); + assertRefused(call(Map.of()), before); + } +} diff --git a/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/RestApiRedirectWithoutLocationTest.java b/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/RestApiRedirectWithoutLocationTest.java index c4a0f29b17..eacea971c4 100644 --- a/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/RestApiRedirectWithoutLocationTest.java +++ b/server/api-service/lowcoder-plugins/restApiPlugin/src/test/java/org/lowcoder/plugin/restapi/RestApiRedirectWithoutLocationTest.java @@ -15,7 +15,7 @@ import org.lowcoder.sdk.plugin.restapi.RestApiDatasourceConfig; import org.springframework.http.HttpStatus; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import com.google.common.collect.Streams; /** @@ -68,7 +68,7 @@ private static Response answer(int status, Map> headers) { /** The values of the result header named {@code name}, compared without case (the test server normalizes names). */ private static JsonNode header(QueryExecutionResult result, String name) { JsonNode headers = result.getHeaders(); - return Streams.stream(headers.fieldNames()).filter(name::equalsIgnoreCase).findFirst().map(headers::get).orElse(null); + return Streams.stream(headers.propertyNames().iterator()).filter(name::equalsIgnoreCase).findFirst().map(headers::get).orElse(null); } private void assertOrdinaryAnswer(int status, Response response) { @@ -83,10 +83,10 @@ private void assertOrdinaryAnswer(int status, Response response) { assertThat(result.getQueryCode()).isEqualTo(HTTP_CODE_PREFIX + HttpStatus.valueOf(status).name()); assertThat(server.requests()).hasSize(1); assertThat(header(result, ANSWER_HEADER)).as("the answer's headers").isNotNull(); - assertThat(header(result, ANSWER_HEADER).get(0).asText()).isEqualTo(ANSWER_HEADER_VALUE); + assertThat(header(result, ANSWER_HEADER).get(0).asString()).isEqualTo(ANSWER_HEADER_VALUE); if (status != NOT_MODIFIED) { assertThat(result.getData()).as("the answer's body").isInstanceOf(JsonNode.class); - assertThat(((JsonNode) result.getData()).get(ANSWER_FIELD).asText()).isEqualTo(ANSWER_HEADER_VALUE); + assertThat(((JsonNode) result.getData()).get(ANSWER_FIELD).asString()).isEqualTo(ANSWER_HEADER_VALUE); } } } diff --git a/server/api-service/lowcoder-plugins/restApiPlugin/src/test/resources/json-contract/external-json/RestApiExecutor.responses.json b/server/api-service/lowcoder-plugins/restApiPlugin/src/test/resources/json-contract/external-json/RestApiExecutor.responses.json index 3d0331c891..99a21cf5c2 100644 --- a/server/api-service/lowcoder-plugins/restApiPlugin/src/test/resources/json-contract/external-json/RestApiExecutor.responses.json +++ b/server/api-service/lowcoder-plugins/restApiPlugin/src/test/resources/json-contract/external-json/RestApiExecutor.responses.json @@ -10,50 +10,50 @@ }, "dataShape" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/zeta" : "com.fasterxml.jackson.databind.node.TextNode", - "/int" : "com.fasterxml.jackson.databind.node.IntNode", - "/negativeInt" : "com.fasterxml.jackson.databind.node.IntNode", - "/intMax" : "com.fasterxml.jackson.databind.node.IntNode", - "/intMaxPlusOne" : "com.fasterxml.jackson.databind.node.LongNode", - "/intMinMinusOne" : "com.fasterxml.jackson.databind.node.LongNode", - "/longMax" : "com.fasterxml.jackson.databind.node.LongNode", - "/longMaxPlusOne" : "com.fasterxml.jackson.databind.node.BigIntegerNode", - "/longMinMinusOne" : "com.fasterxml.jackson.databind.node.BigIntegerNode", - "/decimal" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/trailingZeroDecimal" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/zeroPointZero" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/negativeZero" : "com.fasterxml.jackson.databind.node.IntNode", - "/exponent" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/exponentUpperCase" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/negativeExponent" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/longDecimal" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/true" : "com.fasterxml.jackson.databind.node.BooleanNode", - "/false" : "com.fasterxml.jackson.databind.node.BooleanNode", - "/null" : "com.fasterxml.jackson.databind.node.NullNode", - "/emptyObject" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/emptyArray" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/nested" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/nested/array" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/nested/array/0" : "com.fasterxml.jackson.databind.node.IntNode", - "/nested/array/1" : "com.fasterxml.jackson.databind.node.TextNode", - "/nested/array/2" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/nested/array/2/0" : "com.fasterxml.jackson.databind.node.IntNode", - "/nested/array/2/1" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/nested/array/2/1/four" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/nested/array/3" : "com.fasterxml.jackson.databind.node.NullNode", - "/nested/array/4" : "com.fasterxml.jackson.databind.node.BooleanNode", - "/nested/array/5" : "com.fasterxml.jackson.databind.node.LongNode", - "/nested/object" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/nested/object/z" : "com.fasterxml.jackson.databind.node.IntNode", - "/nested/object/a" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/nested/object/a/deeper" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/nested/object/a/deeper/0" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/nested/object/a/deeper/1" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/unicode" : "com.fasterxml.jackson.databind.node.TextNode", - "/escapes" : "com.fasterxml.jackson.databind.node.TextNode", - "/key with escaped name" : "com.fasterxml.jackson.databind.node.TextNode", - "/alpha" : "com.fasterxml.jackson.databind.node.TextNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/zeta" : "tools.jackson.databind.node.StringNode", + "/int" : "tools.jackson.databind.node.IntNode", + "/negativeInt" : "tools.jackson.databind.node.IntNode", + "/intMax" : "tools.jackson.databind.node.IntNode", + "/intMaxPlusOne" : "tools.jackson.databind.node.LongNode", + "/intMinMinusOne" : "tools.jackson.databind.node.LongNode", + "/longMax" : "tools.jackson.databind.node.LongNode", + "/longMaxPlusOne" : "tools.jackson.databind.node.BigIntegerNode", + "/longMinMinusOne" : "tools.jackson.databind.node.BigIntegerNode", + "/decimal" : "tools.jackson.databind.node.DoubleNode", + "/trailingZeroDecimal" : "tools.jackson.databind.node.DoubleNode", + "/zeroPointZero" : "tools.jackson.databind.node.DoubleNode", + "/negativeZero" : "tools.jackson.databind.node.IntNode", + "/exponent" : "tools.jackson.databind.node.DoubleNode", + "/exponentUpperCase" : "tools.jackson.databind.node.DoubleNode", + "/negativeExponent" : "tools.jackson.databind.node.DoubleNode", + "/longDecimal" : "tools.jackson.databind.node.DoubleNode", + "/true" : "tools.jackson.databind.node.BooleanNode", + "/false" : "tools.jackson.databind.node.BooleanNode", + "/null" : "tools.jackson.databind.node.NullNode", + "/emptyObject" : "tools.jackson.databind.node.ObjectNode", + "/emptyArray" : "tools.jackson.databind.node.ArrayNode", + "/nested" : "tools.jackson.databind.node.ObjectNode", + "/nested/array" : "tools.jackson.databind.node.ArrayNode", + "/nested/array/0" : "tools.jackson.databind.node.IntNode", + "/nested/array/1" : "tools.jackson.databind.node.StringNode", + "/nested/array/2" : "tools.jackson.databind.node.ArrayNode", + "/nested/array/2/0" : "tools.jackson.databind.node.IntNode", + "/nested/array/2/1" : "tools.jackson.databind.node.ObjectNode", + "/nested/array/2/1/four" : "tools.jackson.databind.node.DoubleNode", + "/nested/array/3" : "tools.jackson.databind.node.NullNode", + "/nested/array/4" : "tools.jackson.databind.node.BooleanNode", + "/nested/array/5" : "tools.jackson.databind.node.LongNode", + "/nested/object" : "tools.jackson.databind.node.ObjectNode", + "/nested/object/z" : "tools.jackson.databind.node.IntNode", + "/nested/object/a" : "tools.jackson.databind.node.ObjectNode", + "/nested/object/a/deeper" : "tools.jackson.databind.node.ArrayNode", + "/nested/object/a/deeper/0" : "tools.jackson.databind.node.ArrayNode", + "/nested/object/a/deeper/1" : "tools.jackson.databind.node.ObjectNode", + "/unicode" : "tools.jackson.databind.node.StringNode", + "/escapes" : "tools.jackson.databind.node.StringNode", + "/key with escaped name" : "tools.jackson.databind.node.StringNode", + "/alpha" : "tools.jackson.databind.node.StringNode" }, "keyOrder" : { "/emptyObject" : [ ], @@ -75,13 +75,13 @@ }, "dataShape" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/title" : "com.fasterxml.jackson.databind.node.TextNode", - "/status" : "com.fasterxml.jackson.databind.node.IntNode", - "/errors" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/errors/0" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/errors/0/field" : "com.fasterxml.jackson.databind.node.TextNode", - "/errors/0/limit" : "com.fasterxml.jackson.databind.node.DoubleNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/title" : "tools.jackson.databind.node.StringNode", + "/status" : "tools.jackson.databind.node.IntNode", + "/errors" : "tools.jackson.databind.node.ArrayNode", + "/errors/0" : "tools.jackson.databind.node.ObjectNode", + "/errors/0/field" : "tools.jackson.databind.node.StringNode", + "/errors/0/limit" : "tools.jackson.databind.node.DoubleNode" }, "keyOrder" : { "/errors/0" : [ "field", "limit" ], @@ -98,8 +98,8 @@ }, "dataShape" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/line" : "com.fasterxml.jackson.databind.node.IntNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/line" : "tools.jackson.databind.node.IntNode" }, "keyOrder" : { "" : [ "line" ] diff --git a/server/api-service/lowcoder-plugins/smtpPlugin/pom.xml b/server/api-service/lowcoder-plugins/smtpPlugin/pom.xml index e2ec9c50a9..0a59c1a81a 100644 --- a/server/api-service/lowcoder-plugins/smtpPlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/smtpPlugin/pom.xml @@ -16,9 +16,6 @@ UTF-8 - 17 - ${java.version} - ${java.version} smtp-plugin org.lowcoder.plugins.SmtpPlugin ${revision} @@ -31,16 +28,23 @@ com.sun.mail jakarta.mail - 2.0.1 + 2.0.2 provided + + + org.testcontainers + testcontainers + test + + com.icegreen greenmail - 2.0.1 + 2.1.15 test @@ -56,7 +60,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar @@ -101,13 +105,14 @@ maven-antrun-plugin org.apache.maven.plugins maven-surefire-plugin - 3.2.5 + 3.6.1 us-ascii-default-charset diff --git a/server/api-service/lowcoder-plugins/smtpPlugin/src/test/java/org/lowcoder/plugins/Smtp4DevContainerSupport.java b/server/api-service/lowcoder-plugins/smtpPlugin/src/test/java/org/lowcoder/plugins/Smtp4DevContainerSupport.java new file mode 100644 index 0000000000..03231798c9 --- /dev/null +++ b/server/api-service/lowcoder-plugins/smtpPlugin/src/test/java/org/lowcoder/plugins/Smtp4DevContainerSupport.java @@ -0,0 +1,144 @@ +package org.lowcoder.plugins; + +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; +import org.lowcoder.sdk.contract.ContainerImages; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.lifecycle.Startables; +import org.testcontainers.utility.DockerImageName; +import tools.jackson.core.JacksonException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UncheckedIOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * The two smtp4dev containers of the SMTP STARTTLS tests (default build, not heavy-container: started once per test JVM on + * first use, in parallel, removed by Testcontainers' reaper when the JVM exits): {@link #STARTTLS}, whose server offers + * STARTTLS with the self-signed certificate smtp4dev generates at start ({@code ServerOptions__TlsMode=StartTls}), and + * {@link #PLAIN}, the control that offers no TLS ({@code None}). No file is copied into either. Messages the servers received are + * read from smtp4dev's HTTP API ({@code /api/messages}); {@link #capabilities} asks a server what its EHLO answer advertises. + * A generic container, as elsewhere in this module's siblings. No Docker guard on purpose (owner decision D-7). Not a test. + */ +final class Smtp4DevContainerSupport { + + static final int SMTP_PORT = 25; + static final int HTTP_PORT = 80; + static final String TLS_MODE_ENV = "ServerOptions__TlsMode"; + static final String TLS_MODE_STARTTLS = "StartTls"; + static final String TLS_MODE_NONE = "None"; + static final String MESSAGES_PATH = "/api/messages"; + static final String STARTTLS_CAPABILITY = "STARTTLS"; + private static final String EHLO_NAME = "test.local"; + private static final int CONNECT_TIMEOUT_MILLIS = 5000; + private static final int READ_TIMEOUT_MILLIS = 10_000; + private static final Duration START_TIMEOUT = Duration.ofMinutes(2); + private static final Duration HTTP_TIMEOUT = Duration.ofSeconds(10); + private static final ObjectMapper JSON = JsonMapper.builderWithJackson2Defaults().build(); + private static final HttpClient HTTP = HttpClient.newHttpClient(); + + private Smtp4DevContainerSupport() { + } + + /** A started smtp4dev and the ways to reach it. */ + static final class Server { + private final GenericContainer container; + private final String name; + + private Server(String name, String tlsMode) { + this.name = name; + this.container = new GenericContainer<>(DockerImageName.parse(ContainerImages.SMTP4DEV_3_6)) + .withEnv(TLS_MODE_ENV, tlsMode).withExposedPorts(SMTP_PORT, HTTP_PORT) + .waitingFor(Wait.forHttp(MESSAGES_PATH).forPort(HTTP_PORT).forStatusCode(200).withStartupTimeout(START_TIMEOUT)); + } + + String host() { + return container.getHost(); + } + + int smtpPort() { + return container.getMappedPort(SMTP_PORT); + } + + /** The datasource config map of this server, without credentials (smtp4dev accepts any sender and needs no login). */ + Map configMap() { + return Map.of("host", host(), "port", smtpPort()); + } + + /** The subjects of the messages the server has stored, in the order its API lists them. */ + List subjects() { + try { + HttpResponse response = HTTP.send(HttpRequest.newBuilder(URI.create("http://" + host() + ":" + + container.getMappedPort(HTTP_PORT) + MESSAGES_PATH)).timeout(HTTP_TIMEOUT).GET().build(), + HttpResponse.BodyHandlers.ofString()); + JsonNode results = JSON.readTree(response.body()).path("results"); + List subjects = new ArrayList<>(); + results.forEach(message -> subjects.add(message.path("subject").asString())); + return subjects; + } catch (IOException e) { + throw new UncheckedIOException("cannot read the messages of " + name, e); + } catch (JacksonException e) { + throw new IllegalStateException("cannot read the messages of " + name, e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while reading the messages of " + name, e); + } + } + + /** The capability lines of the server's answer to EHLO, read over a plain socket (the part of the answer after "250-" or "250 "). */ + List capabilities() { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(host(), smtpPort()), CONNECT_TIMEOUT_MILLIS); + socket.setSoTimeout(READ_TIMEOUT_MILLIS); + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII)); + in.readLine(); + socket.getOutputStream().write(("EHLO " + EHLO_NAME + "\r\n").getBytes(StandardCharsets.US_ASCII)); + socket.getOutputStream().flush(); + List capabilities = new ArrayList<>(); + String line; + while ((line = in.readLine()) != null) { + capabilities.add(line.substring(4)); + if (line.charAt(3) == ' ') { + break; + } + } + return capabilities; + } catch (IOException e) { + throw new UncheckedIOException("cannot read the EHLO answer of " + name, e); + } + } + + @Override + public String toString() { + return name + " " + host() + ":" + smtpPort(); + } + } + + static final Server STARTTLS; + static final Server PLAIN; + + static { + long start = System.nanoTime(); + Server starttls = new Server("smtp4dev-starttls", TLS_MODE_STARTTLS); + Server plain = new Server("smtp4dev-plain", TLS_MODE_NONE); + Startables.deepStart(starttls.container, plain.container).join(); + STARTTLS = starttls; + PLAIN = plain; + System.out.println("[Smtp4DevContainerSupport] " + ContainerImages.SMTP4DEV_3_6 + " started twice in " + + (System.nanoTime() - start) / 1_000_000 + " ms: " + STARTTLS + ", " + PLAIN); + } +} diff --git a/server/api-service/lowcoder-plugins/smtpPlugin/src/test/java/org/lowcoder/plugins/SmtpStartTlsContainerTest.java b/server/api-service/lowcoder-plugins/smtpPlugin/src/test/java/org/lowcoder/plugins/SmtpStartTlsContainerTest.java new file mode 100644 index 0000000000..c6ebbb3029 --- /dev/null +++ b/server/api-service/lowcoder-plugins/smtpPlugin/src/test/java/org/lowcoder/plugins/SmtpStartTlsContainerTest.java @@ -0,0 +1,116 @@ +package org.lowcoder.plugins; + +import jakarta.mail.Session; +import org.junit.jupiter.api.Test; +import org.lowcoder.plugins.SmtpPlugin.SmtpEngine; +import org.lowcoder.sdk.exception.PluginCommonError; +import org.lowcoder.sdk.models.DatasourceTestResult; +import org.lowcoder.sdk.models.QueryExecutionResult; + +import java.time.Duration; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lowcoder.plugins.Smtp4DevContainerSupport.PLAIN; +import static org.lowcoder.plugins.Smtp4DevContainerSupport.STARTTLS; +import static org.lowcoder.plugins.Smtp4DevContainerSupport.STARTTLS_CAPABILITY; + +/** + * Unit SM-3: the SMTP engine against a server that offers STARTTLS with a self-signed certificate it generated itself + * ({@link Smtp4DevContainerSupport#STARTTLS}, the pinned smtp4dev image; no certificate is made or copied by the test). The + * engine enables STARTTLS ({@code mail.smtp.starttls.enable}) without a trust setting, so JavaMail upgrades the connection + * and verifies the server's certificate against the JDK's default trust (the host name is not checked, + * {@code mail.smtp.ssl.checkserveridentity=false}). The tests pin what that gives for an untrusted certificate: the TLS + * handshake fails, test-connection reports a failed result naming it, a send is an error result and the server stores no + * message. The control is the same engine against a server that offers no STARTTLS ({@link Smtp4DevContainerSupport#PLAIN}): + * test-connection succeeds and the mail is stored, so the failure is the certificate's, not the engine's or the image's. + * + *

Limits: only the refusal of an untrusted certificate is shown; there is no setting for trusting one, so a successful + * STARTTLS session with a trusted certificate is not tested; the TLS version is the engine's TLSv1.2. + */ +public class SmtpStartTlsContainerTest { + + static final String TAG = "[SmtpStartTlsContainerTest] "; + static final Duration BLOCK_TIMEOUT = Duration.ofSeconds(30); + static final String QUERY_CODE_OK = "OK"; + static final String FROM = "sender@example.com"; + static final String TO = "to@example.com"; + static final String CONNECT_FAILURE_TEXT = "Could not convert socket to TLS"; + static final String HANDSHAKE_TEXT = "SSLHandshakeException"; + static final String PKIX_TEXT = "PKIX path building failed"; + static final String QUERY_EXECUTION_ERROR_KEY = "QUERY_EXECUTION_ERROR"; + + private final SmtpEngine engine = new SmtpEngine(); + + private static Map query(String subject) { + Map query = new HashMap<>(); + query.put("from", FROM); + query.put("to", "[\"" + TO + "\"]"); + query.put("subject", subject); + query.put("content", "

over STARTTLS?

"); + return query; + } + + @Test + public void theStarttlsServerAdvertisesStarttlsAndThePlainControlDoesNot() { + List starttls = STARTTLS.capabilities(); + List plain = PLAIN.capabilities(); + System.out.println(TAG + "EHLO of " + STARTTLS + ": " + starttls); + System.out.println(TAG + "EHLO of " + PLAIN + ": " + plain); + assertTrue(starttls.contains(STARTTLS_CAPABILITY), "the STARTTLS server advertises STARTTLS: " + starttls); + assertFalse(plain.contains(STARTTLS_CAPABILITY), "the control server does not: " + plain); + } + + @Test + public void testConnectionAgainstAnUntrustedStarttlsCertificateIsAFailedResultNamingTheHandshake() { + DatasourceTestResult result = engine.testConnection(engine.resolveConfig(STARTTLS.configMap())).block(BLOCK_TIMEOUT); + assertNotNull(result); + String message = result.isSuccess() ? "" : result.getInvalidMessage(Locale.ENGLISH); + System.out.println(TAG + "test connection against " + STARTTLS + ": success=" + result.isSuccess() + " message=" + message); + assertFalse(result.isSuccess(), "an untrusted certificate must fail the test"); + assertTrue(message.contains(CONNECT_FAILURE_TEXT) || message.contains(HANDSHAKE_TEXT) || message.contains(PKIX_TEXT), + "the message names the TLS failure: " + message); + } + + @Test + public void aSendThroughAnUntrustedStarttlsCertificateIsAnErrorResultNamingTheHandshakeAndTheServerStoresNothing() { + var datasource = engine.resolveConfig(STARTTLS.configMap()); + Session session = engine.createConnection(datasource).block(BLOCK_TIMEOUT); + String subject = "starttls-refused"; + var context = engine.buildQueryExecutionContext(datasource, query(subject), Map.of(), null); + QueryExecutionResult result = engine.executeQuery(session, context).block(BLOCK_TIMEOUT); + assertNotNull(result); + System.out.println(TAG + "send against " + STARTTLS + ": code=" + result.getQueryCode() + " key=" + result.getMessageKey() + + " args=" + Arrays.toString(result.getMessageArgs())); + assertEquals(PluginCommonError.QUERY_EXECUTION_ERROR.name(), result.getQueryCode(), "the engine reports the refused TLS upgrade as an error result"); + assertEquals(QUERY_EXECUTION_ERROR_KEY, result.getMessageKey()); + String detail = Arrays.toString(result.getMessageArgs()); + assertTrue(detail.contains(CONNECT_FAILURE_TEXT) || detail.contains(HANDSHAKE_TEXT) || detail.contains(PKIX_TEXT), + "the error names the TLS failure: " + detail); + assertFalse(STARTTLS.subjects().contains(subject), "the refused send stored no message: " + STARTTLS.subjects()); + } + + @Test + public void theSameEngineTestsAndSendsAgainstTheServerWithoutStarttls() { + var datasource = engine.resolveConfig(PLAIN.configMap()); + DatasourceTestResult result = engine.testConnection(datasource).block(BLOCK_TIMEOUT); + assertNotNull(result); + System.out.println(TAG + "control test connection against " + PLAIN + ": success=" + result.isSuccess()); + assertTrue(result.isSuccess(), "the control server passes the test"); + + Session session = engine.createConnection(datasource).block(BLOCK_TIMEOUT); + String subject = "plain-control"; + var context = engine.buildQueryExecutionContext(datasource, query(subject), Map.of(), null); + QueryExecutionResult sent = engine.executeQuery(session, context).block(BLOCK_TIMEOUT); + System.out.println(TAG + "control send -> " + sent.getQueryCode() + "; stored subjects " + PLAIN.subjects()); + assertEquals(QUERY_CODE_OK, sent.getQueryCode()); + assertTrue(PLAIN.subjects().contains(subject), "the control server stored the message: " + PLAIN.subjects()); + } +} diff --git a/server/api-service/lowcoder-plugins/snowflakePlugin/pom.xml b/server/api-service/lowcoder-plugins/snowflakePlugin/pom.xml index 767cecdc9c..16c40dc1fe 100644 --- a/server/api-service/lowcoder-plugins/snowflakePlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/snowflakePlugin/pom.xml @@ -13,9 +13,6 @@ snowflakePlugin - 17 - 17 - 17 UTF-8 snowflake-plugin @@ -30,7 +27,7 @@ net.snowflake snowflake-jdbc - 3.22.0 + 4.4.1 org.lowcoder @@ -51,7 +48,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.2 shade-plugin-jar diff --git a/server/api-service/lowcoder-plugins/snowflakePlugin/src/test/java/org/lowcoder/plugin/snowflake/SnowflakeDriverStubTest.java b/server/api-service/lowcoder-plugins/snowflakePlugin/src/test/java/org/lowcoder/plugin/snowflake/SnowflakeDriverStubTest.java new file mode 100644 index 0000000000..00a36bb4ca --- /dev/null +++ b/server/api-service/lowcoder-plugins/snowflakePlugin/src/test/java/org/lowcoder/plugin/snowflake/SnowflakeDriverStubTest.java @@ -0,0 +1,312 @@ +package org.lowcoder.plugin.snowflake; + +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; +import com.zaxxer.hikari.HikariDataSource; +import org.junit.jupiter.api.Test; +import org.lowcoder.sdk.contract.RecordingHttpServer; +import org.lowcoder.sdk.contract.RecordingHttpServer.Handler; +import org.lowcoder.sdk.contract.RecordingHttpServer.Request; +import org.lowcoder.sdk.contract.RecordingHttpServer.Response; +import org.lowcoder.sdk.exception.PluginException; +import org.lowcoder.sdk.models.DatasourceTestResult; +import org.lowcoder.sdk.models.QueryExecutionResult; +import org.lowcoder.sdk.plugin.common.sql.HikariPerfWrapper; +import org.lowcoder.sdk.plugin.common.sql.SqlBasedQueryExecutionContext; +import tools.jackson.core.JacksonException; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit SN-3: the real Snowflake JDBC driver (snowflake-jdbc 3.22.0), loaded by {@link SnowflakeConnector} and talking to a local + * stand-in of the Snowflake REST API ({@link RecordingHttpServer} answering the login, query, heartbeat and logout requests in + * the shape of the service's JSON answers), so the driver loads, the Hikari pool initialises, a test connection succeeds and a + * SELECT returns rows through {@link SnowflakeQueryExecutor}. Nothing of the driver is mocked, and nothing is set JVM-wide. + * + *

How the driver is pointed at the stand-in: {@code SnowflakeConnector} fixes the host ({@code .snowflakecomputing.com}) + * and passes the datasource's {@code extParams} to the driver as connection properties ({@code SqlBasedConnector}). Those + * properties are the driver's own ({@code SFSessionProperty}, read from the 3.22.0 jar): {@code useProxy}, {@code proxyHost}, + * {@code proxyPort} and {@code proxyProtocol=http} send every request, as a plain HTTP request with the full URL, to the stand-in + * as if it were a proxy, and {@code ssl=off} makes the driver use {@code http} for the account host (no TLS, no OCSP). + * {@code gzipDisabled=true} sends the query body as plain JSON, which the test reads. {@code JDBC_QUERY_RESULT_FORMAT=JSON} asks for the JSON result format, which the stand-in answers ({@code rowset}); Arrow, the + * service's default, is not served. + * + *

Limits: the answers are made to resemble the service's, not recorded from an account (there is none in the tests), so they + * show that the driver and the plugin work against that protocol shape, not that Snowflake answers so; only the JSON result + * format, one chunk, no bind parameters, no MFA, key-pair or OAuth login; the structure query is not served. + */ +public class SnowflakeDriverStubTest { + + static final String TAG = "[SnowflakeDriverStubTest] "; + static final Duration TIMEOUT = Duration.ofSeconds(60); + static final ObjectMapper JSON = JsonMapper.builderWithJackson2Defaults().build(); + static final String LOGIN_PATH = "/session/v1/login-request"; + static final String QUERY_PATH = "/queries/v1/query-request"; + static final String HEARTBEAT_PATH = "/session/heartbeat"; + static final String SESSION_PATH = "/session"; + static final String HOST = "stub"; + static final String ACCOUNT_SUFFIX = ".snowflakecomputing.com"; + static final String DATABASE = "ANALYTICS"; + static final String USER = "LOADER"; + static final String PASSWORD = "stub-secret-pw"; + static final String SELECT_SQL = "SELECT 1 AS ID, 'x' AS NAME"; + static final String BAD_SQL = "SELECT * FROM MISSING_TABLE"; + static final String WRONG_LOGIN_CODE = "390100"; + static final String WRONG_LOGIN_MESSAGE = "Incorrect username or password was specified."; + static final String COMPILATION_ERROR_CODE = "002003"; + static final String COMPILATION_ERROR_MESSAGE = "SQL compilation error:\nObject 'MISSING_TABLE' does not exist or not authorized."; + static final String LOGOUT_QUERY = "delete=true"; + static final int OK = 200; + + /** The session parameters of a login answer, as the service sends them (a subset); the driver reads AUTOCOMMIT from them. */ + static final String LOGIN_PARAMETERS = "[" + + "{\"name\":\"AUTOCOMMIT\",\"value\":true}," + + "{\"name\":\"CLIENT_SESSION_KEEP_ALIVE\",\"value\":false}," + + "{\"name\":\"CLIENT_PREFETCH_THREADS\",\"value\":4}," + + "{\"name\":\"CLIENT_RESULT_CHUNK_SIZE\",\"value\":160}," + + "{\"name\":\"CLIENT_MEMORY_LIMIT\",\"value\":1536}," + + "{\"name\":\"CLIENT_STAGE_ARRAY_BINDING_THRESHOLD\",\"value\":65280}," + + "{\"name\":\"JDBC_QUERY_RESULT_FORMAT\",\"value\":\"JSON\"}," + + "{\"name\":\"TIMEZONE\",\"value\":\"America/Los_Angeles\"}," + + "{\"name\":\"DATE_OUTPUT_FORMAT\",\"value\":\"YYYY-MM-DD\"}," + + "{\"name\":\"TIME_OUTPUT_FORMAT\",\"value\":\"HH24:MI:SS\"}," + + "{\"name\":\"TIMESTAMP_OUTPUT_FORMAT\",\"value\":\"YYYY-MM-DD HH24:MI:SS.FF3 TZHTZM\"}," + + "{\"name\":\"BINARY_OUTPUT_FORMAT\",\"value\":\"HEX\"}]"; + + private static Response json(String body) { + return new Response(OK, Map.of("Content-Type", List.of("application/json")), body.getBytes(StandardCharsets.UTF_8)); + } + + private static Response loginAccepted() { + return json("{\"data\":{\"masterToken\":\"master-token\",\"token\":\"session-token\",\"validityInSeconds\":3600," + + "\"masterValidityInSeconds\":14400,\"displayUserName\":\"" + USER + "\",\"serverVersion\":\"8.40.0\",\"firstLogin\":false," + + "\"remMeToken\":null,\"remMeValidityInSeconds\":0,\"healthCheckInterval\":45,\"newClientForUpgrade\":null," + + "\"sessionId\":1001,\"parameters\":" + LOGIN_PARAMETERS + ",\"sessionInfo\":{\"databaseName\":\"" + DATABASE + + "\",\"schemaName\":\"PUBLIC\",\"warehouseName\":\"WH\",\"roleName\":\"ANALYST\"},\"idToken\":null," + + "\"idTokenValidityInSeconds\":0,\"responseData\":null,\"mfaToken\":null,\"mfaTokenValidityInSeconds\":0}," + + "\"code\":null,\"message\":null,\"success\":true}"); + } + + private static Response loginRefused() { + return json("{\"data\":{\"nextAction\":\"RETRY_LOGIN\",\"authnMethod\":\"USERNAME_PASSWORD\",\"signInOptions\":{}}," + + "\"code\":\"" + WRONG_LOGIN_CODE + "\",\"message\":\"" + WRONG_LOGIN_MESSAGE + "\",\"success\":false,\"headers\":null}"); + } + + private static Response selectAnswered() { + return json("{\"data\":{\"parameters\":" + LOGIN_PARAMETERS + ",\"rowtype\":[" + + "{\"name\":\"ID\",\"database\":\"\",\"schema\":\"\",\"table\":\"\",\"nullable\":false,\"length\":null,\"type\":\"fixed\"," + + "\"scale\":0,\"precision\":1,\"byteLength\":null,\"collation\":null}," + + "{\"name\":\"NAME\",\"database\":\"\",\"schema\":\"\",\"table\":\"\",\"nullable\":false,\"length\":1,\"type\":\"text\"," + + "\"scale\":null,\"precision\":null,\"byteLength\":4,\"collation\":null}]," + + "\"rowset\":[[\"1\",\"x\"]],\"total\":1,\"returned\":1,\"queryId\":\"01b0a8c1-0000-0000-0000-000000000001\"," + + "\"databaseProvider\":null,\"finalDatabaseName\":\"" + DATABASE + "\",\"finalSchemaName\":\"PUBLIC\"," + + "\"finalWarehouseName\":\"WH\",\"finalRoleName\":\"ANALYST\",\"numberOfBinds\":0,\"arrayBindSupported\":false," + + "\"statementTypeId\":4096,\"version\":1,\"sendResultTime\":1700000000000,\"queryResultFormat\":\"json\"}," + + "\"code\":null,\"message\":null,\"success\":true}"); + } + + private static Response compilationError() { + return json("{\"data\":{\"internalError\":false,\"errorCode\":\"" + COMPILATION_ERROR_CODE + "\",\"age\":0,\"sqlState\":\"42S02\"," + + "\"queryId\":\"01b0a8c1-0000-0000-0000-000000000002\",\"line\":1,\"pos\":14,\"type\":\"COMPILATION\"}," + + "\"code\":\"" + COMPILATION_ERROR_CODE + "\",\"message\":\"SQL compilation error:\\nObject 'MISSING_TABLE' does not exist or not authorized.\"," + + "\"success\":false,\"headers\":null}"); + } + + private static Response acknowledged() { + return json("{\"data\":null,\"code\":null,\"message\":null,\"success\":true}"); + } + + /** The stand-in: login, query, heartbeat and logout, each answered by the given response of its path. */ + private static RecordingHttpServer standIn(Response login, Response query) { + Map handlers = new LinkedHashMap<>(); + handlers.put(LOGIN_PATH, request -> login); + handlers.put(QUERY_PATH, request -> query); + handlers.put(HEARTBEAT_PATH, request -> acknowledged()); + handlers.put(SESSION_PATH, request -> acknowledged()); + return RecordingHttpServer.serve(handlers); + } + + /** The datasource of the stand-in: the driver's proxy properties name the stand-in's port. */ + private static SnowflakeDatasourceConfig datasource(RecordingHttpServer server, String password) { + Map extParams = new LinkedHashMap<>(); + extParams.put("useProxy", "true"); + extParams.put("proxyHost", RecordingHttpServer.LOOPBACK); + extParams.put("proxyPort", String.valueOf(server.port())); + extParams.put("proxyProtocol", "http"); + extParams.put("ssl", "off"); + extParams.put("JDBC_QUERY_RESULT_FORMAT", "JSON"); + extParams.put("gzipDisabled", "true"); + extParams.put("loginTimeout", "20"); + return SnowflakeDatasourceConfig.builder().host(HOST).database(DATABASE).username(USER).password(password).extParams(extParams).build(); + } + + private static String pathOf(Request request) { + return request.pathAndQuery().split("\\?")[0]; + } + + private static List requestsTo(RecordingHttpServer server, String path) { + return server.requests().stream().filter(request -> pathOf(request).equals(path)).toList(); + } + + private static JsonNode bodyOf(Request request) { + try { + return JSON.readTree(request.bodyText()); + } catch (JacksonException e) { + throw new IllegalStateException("not JSON: " + request.pathAndQuery(), e); + } + } + + private static void printRequests(RecordingHttpServer server) { + server.requests().forEach(request -> System.out.println(TAG + "recorded " + request.method() + " " + request.pathAndQuery() + + " (" + request.body().length + " bytes)")); + } + + /** Waits for a logout the driver sends when its pool closes; it is sent from the closing thread, so it is there on return, with a short grace for the stand-in's own bookkeeping. */ + private static List logoutsOf(RecordingHttpServer server) { + long deadline = System.nanoTime() + Duration.ofSeconds(10).toNanos(); + List logouts = requestsTo(server, SESSION_PATH).stream().filter(request -> request.pathAndQuery().contains(LOGOUT_QUERY)).toList(); + while (logouts.isEmpty() && System.nanoTime() < deadline) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + logouts = requestsTo(server, SESSION_PATH).stream().filter(request -> request.pathAndQuery().contains(LOGOUT_QUERY)).toList(); + } + return logouts; + } + + @Test + public void testConnectionLoadsTheDriverLogsInThroughTheProxyPropertiesAndLogsOut() { + try (RecordingHttpServer server = standIn(loginAccepted(), selectAnswered())) { + DatasourceTestResult result = new SnowflakeConnector().testConnection(datasource(server, PASSWORD)).block(TIMEOUT); + printRequests(server); + assertNotNull(result, "testConnection emits a result"); + assertTrue(result.isSuccess(), "the stand-in accepted the login, so the test passes"); + + List logins = requestsTo(server, LOGIN_PATH); + assertFalse(logins.isEmpty(), "the driver sent a login request to the stand-in: " + server.requests().stream().map(Request::pathAndQuery).toList()); + Request login = logins.get(0); + assertEquals("POST", login.method()); + assertTrue(login.pathAndQuery().contains("databaseName=" + DATABASE), "the db property is the login's database: " + login.pathAndQuery()); + JsonNode data = bodyOf(login).path("data"); + assertEquals(HOST, data.path("ACCOUNT_NAME").asString(), "the account is the datasource's host"); + assertEquals(USER, data.path("LOGIN_NAME").asString(), "the user property is the login name"); + assertEquals(PASSWORD, data.path("PASSWORD").asString(), "the password property is the login password"); + assertEquals("JSON", data.path("SESSION_PARAMETERS").path("JDBC_QUERY_RESULT_FORMAT").asString(), "the extParams reach the driver as session parameters"); + assertEquals("JDBC", data.path("CLIENT_APP_ID").asString(), "the request is the JDBC driver's"); + + List logouts = logoutsOf(server); + assertFalse(logouts.isEmpty(), "closing the tested pool logged the session out: " + server.requests().stream().map(Request::pathAndQuery).toList()); + assertEquals("POST", logouts.get(0).method()); + } + } + + @Test + public void aSelectRunsThroughTheExecutorAndItsRowsComeFromTheJsonRowset() throws SQLException { + try (RecordingHttpServer server = standIn(loginAccepted(), selectAnswered())) { + SnowflakeConnector connector = new SnowflakeConnector(); + SnowflakeDatasourceConfig config = datasource(server, PASSWORD); + HikariPerfWrapper pool = connector.createConnection(config).block(TIMEOUT); + try { + assertNotNull(pool, "createConnection emits the pool"); + HikariDataSource dataSource = (HikariDataSource) pool.getHikariDataSource(); + assertTrue(dataSource.isRunning(), "the pool is running"); + assertEquals("net.snowflake.client.jdbc.SnowflakeDriver", dataSource.getDriverClassName()); + assertEquals("jdbc:snowflake://" + HOST + ACCOUNT_SUFFIX + "/", dataSource.getJdbcUrl()); + try (Connection connection = dataSource.getConnection()) { + DatabaseMetaData metaData = connection.getMetaData(); + System.out.println(TAG + "driver " + metaData.getDriverName() + " " + metaData.getDriverVersion()); + assertTrue(metaData.getDriverVersion().startsWith("4.4"), "the driver is snowflake-jdbc 4.4.x: " + metaData.getDriverVersion()); + } + + SnowflakeQueryExecutor executor = new SnowflakeQueryExecutor(); + Map queryConfig = new LinkedHashMap<>(); + queryConfig.put("mode", "SQL"); + queryConfig.put("sql", SELECT_SQL); + SqlBasedQueryExecutionContext context = executor.buildQueryExecutionContext(config, queryConfig, Map.of(), null); + QueryExecutionResult result = executor.executeQuery(pool, context).block(TIMEOUT); + printRequests(server); + assertNotNull(result); + System.out.println(TAG + "select -> " + result.getQueryCode() + " " + result.getData()); + assertEquals("OK", result.getQueryCode()); + @SuppressWarnings("unchecked") + List> rows = (List>) result.getData(); + assertEquals(1, rows.size(), "one row from the rowset"); + assertEquals(1L, ((Number) rows.get(0).get("ID")).longValue(), "the fixed(1,0) column is read as a number: " + rows.get(0)); + assertEquals("x", rows.get(0).get("NAME"), "the text column is read as text: " + rows.get(0)); + + List queries = requestsTo(server, QUERY_PATH); + assertEquals(1, queries.size(), "one query request reached the stand-in"); + JsonNode sent = bodyOf(queries.get(0)); + assertEquals(SELECT_SQL, sent.path("sqlText").asString(), "the statement is sent as written (no bind parameters: the executor forces a plain statement)"); + assertTrue(queries.get(0).header("Authorization").stream().anyMatch(value -> value.contains("session-token")), + "the query carries the session token of the login answer: " + queries.get(0).header("Authorization")); + } finally { + connector.destroyConnection(pool).block(TIMEOUT); + } + assertFalse(logoutsOf(server).isEmpty(), "destroying the pool logged the session out"); + } + } + + @Test + public void aRefusedLoginIsAFailedTestConnectionWithTheServicesMessage() { + try (RecordingHttpServer server = standIn(loginRefused(), selectAnswered())) { + SnowflakeConnector connector = new SnowflakeConnector(); + RuntimeException thrown = assertThrows(RuntimeException.class, + () -> connector.testConnection(datasource(server, "wrong-password")).block(TIMEOUT), "a refused login must not give a result"); + System.out.println(TAG + "refused login: " + thrown.getClass().getSimpleName() + ": " + thrown.getMessage()); + assertTrue(String.valueOf(thrown.getMessage()).contains(WRONG_LOGIN_MESSAGE), "the error carries the service's text: " + thrown.getMessage()); + assertFalse(requestsTo(server, LOGIN_PATH).isEmpty(), "the login request reached the stand-in"); + // what DatasourceServiceImpl.testDatasourceLocally does with the error + DatasourceTestResult mapped = connector.testConnection(datasource(server, "wrong-password")) + .onErrorResume(error -> reactor.core.publisher.Mono.just(DatasourceTestResult.testFail(error))).block(TIMEOUT); + assertNotNull(mapped); + assertFalse(mapped.isSuccess(), "the mapped result is a failure"); + String message = mapped.getInvalidMessage(Locale.ENGLISH); + System.out.println(TAG + "mapped failed result: " + message); + assertTrue(message.contains(WRONG_LOGIN_MESSAGE), message); + assertTrue(requestsTo(server, QUERY_PATH).isEmpty(), "no query was sent after a refused login"); + } + } + + @Test + public void aStatementTheServiceRefusesIsAPluginExceptionWithItsMessage() { + try (RecordingHttpServer server = standIn(loginAccepted(), compilationError())) { + SnowflakeConnector connector = new SnowflakeConnector(); + SnowflakeDatasourceConfig config = datasource(server, PASSWORD); + HikariPerfWrapper pool = connector.createConnection(config).block(TIMEOUT); + try { + SnowflakeQueryExecutor executor = new SnowflakeQueryExecutor(); + Map queryConfig = new LinkedHashMap<>(); + queryConfig.put("mode", "SQL"); + queryConfig.put("sql", BAD_SQL); + SqlBasedQueryExecutionContext context = executor.buildQueryExecutionContext(config, queryConfig, Map.of(), null); + Throwable failure = assertThrows(Throwable.class, () -> executor.executeQuery(pool, context).block(TIMEOUT)); + System.out.println(TAG + "refused statement: " + failure.getClass().getSimpleName() + ": " + failure.getMessage()); + assertInstanceOf(PluginException.class, failure, "the executor maps the driver's SQLException: " + failure); + assertTrue(String.valueOf(failure.getMessage()).contains("MISSING_TABLE"), "the service's message is kept: " + failure.getMessage()); + assertEquals(1, requestsTo(server, QUERY_PATH).size(), "the statement reached the stand-in"); + } finally { + connector.destroyConnection(pool).block(TIMEOUT); + } + } + } +} diff --git a/server/api-service/lowcoder-plugins/sqlBasedPlugin/pom.xml b/server/api-service/lowcoder-plugins/sqlBasedPlugin/pom.xml index 2ede0d9516..b58c3c4351 100644 --- a/server/api-service/lowcoder-plugins/sqlBasedPlugin/pom.xml +++ b/server/api-service/lowcoder-plugins/sqlBasedPlugin/pom.xml @@ -13,16 +13,13 @@ UTF-8 - 17 - ${java.version} - ${java.version} com.zaxxer HikariCP - 5.0.1 + 7.1.0 org.slf4j diff --git a/server/api-service/lowcoder-sdk/pom.xml b/server/api-service/lowcoder-sdk/pom.xml index 8d41876d69..4b09a964f8 100644 --- a/server/api-service/lowcoder-sdk/pom.xml +++ b/server/api-service/lowcoder-sdk/pom.xml @@ -14,13 +14,6 @@ lowcoder-sdk - - - local_libs - Temporary local libraries - file://${maven.multiModuleProjectDirectory}/local-repo - - @@ -81,7 +74,7 @@ provided - com.fasterxml.jackson.core + tools.jackson.core jackson-databind @@ -128,28 +121,21 @@ org.apache.commons commons-collections4 - - com.fasterxml.jackson.module - jackson-module-parameter-names - com.google.guava guava + tv.twelvetone.rjson rjson - 1.3.1-SNAPSHOT + 1.3.1 org.jetbrains.kotlin kotlin-stdlib-jdk7 - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - com.jayway.jsonpath json-path @@ -161,7 +147,6 @@ io.netty netty-resolver - 4.1.109.Final io.projectreactor.netty @@ -194,7 +179,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.3.0 + 3.5.1 diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/auth/AbstractAuthConfig.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/auth/AbstractAuthConfig.java index ff44a9b885..2928ee5ec4 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/auth/AbstractAuthConfig.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/auth/AbstractAuthConfig.java @@ -1,5 +1,6 @@ package org.lowcoder.sdk.auth; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import jakarta.annotation.Nullable; @@ -29,6 +30,7 @@ public abstract class AbstractAuthConfig { protected String authType; + @JsonCreator protected AbstractAuthConfig(@Nullable String id, String source, String sourceName, Boolean enable, Boolean enableRegister, String authType) { this.id = id; this.source = source; diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/models/QueryExecutionResult.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/models/QueryExecutionResult.java index c532222e38..f12ad281c6 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/models/QueryExecutionResult.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/models/QueryExecutionResult.java @@ -2,7 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import lombok.Getter; import org.apache.commons.lang3.StringUtils; import org.lowcoder.sdk.exception.PluginError; @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @Getter @@ -18,6 +19,16 @@ public class QueryExecutionResult { private static final String CODE_FAILED = "FAILED"; private static final String CODE_OK = "OK"; + private static final String HTTP_CODE_PREFIX = "HTTP"; + + /** + * The names under which the status codes whose {@link HttpStatus} constant Spring 7 renamed (RFC 9110) were reported in + * a query's {@code queryCode}, which stays what it was for the apps that compare it. + */ + private static final Map LEGACY_HTTP_STATUS_NAMES = Map.of( + HttpStatus.CONTENT_TOO_LARGE, "PAYLOAD_TOO_LARGE", + HttpStatus.MISDIRECTED_REQUEST, "DESTINATION_LOCKED", + HttpStatus.UNPROCESSABLE_CONTENT, "UNPROCESSABLE_ENTITY"); private String queryCode = CODE_OK; private JsonNode headers; @@ -75,7 +86,7 @@ public static QueryExecutionResult errorWithMessage(String message) { public static QueryExecutionResult ofRestApiResult(HttpStatus httpStatus, JsonNode resultHeaders, Object body) { QueryExecutionResult result = new QueryExecutionResult(); if (!httpStatus.is2xxSuccessful()) { - result.queryCode = "HTTP" + httpStatus.name(); + result.queryCode = HTTP_CODE_PREFIX + LEGACY_HTTP_STATUS_NAMES.getOrDefault(httpStatus, httpStatus.name()); } result.headers = resultHeaders; result.data = body; diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/common/sql/SqlBasedDatasourceConnectionConfig.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/common/sql/SqlBasedDatasourceConnectionConfig.java index 2fdcaff71f..de30b08763 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/common/sql/SqlBasedDatasourceConnectionConfig.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/common/sql/SqlBasedDatasourceConnectionConfig.java @@ -1,5 +1,6 @@ package org.lowcoder.sdk.plugin.common.sql; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonView; import lombok.Getter; import lombok.experimental.SuperBuilder; @@ -41,6 +42,7 @@ public abstract class SqlBasedDatasourceConnectionConfig implements DatasourceCo private final Map extParams; + @JsonCreator protected SqlBasedDatasourceConnectionConfig(String database, String username, String password, String host, Long port, boolean usingSsl, String serverTimezone, boolean isReadonly, boolean enableTurnOffPreparedStatement, diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/common/ssl/SslConfig.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/common/ssl/SslConfig.java index 17d551ead2..3fb2b751c3 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/common/ssl/SslConfig.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/common/ssl/SslConfig.java @@ -1,5 +1,6 @@ package org.lowcoder.sdk.plugin.common.ssl; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; @@ -20,6 +21,7 @@ public abstract class SslConfig implements Encrypt { protected final SslCertVerificationType sslCertVerificationType; + @JsonCreator protected SslConfig(SslCertVerificationType sslCertVerificationType) { this.sslCertVerificationType = sslCertVerificationType; } diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/http/RawHttpHandlerHelper.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/http/RawHttpHandlerHelper.java index fc9bde7a23..02f5dfa528 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/http/RawHttpHandlerHelper.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/http/RawHttpHandlerHelper.java @@ -23,6 +23,10 @@ public class RawHttpHandlerHelper { private static final DataUtils DATA_UTILS = DataUtils.getInstance(); + /** The charset-suffixed forms of the JSON media types, which Spring 7 no longer declares as constants. */ + private static final String JSON_UTF8_CONTENT_TYPE = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"; + private static final String PROBLEM_JSON_UTF8_CONTENT_TYPE = MediaType.APPLICATION_PROBLEM_JSON_VALUE + ";charset=UTF-8"; + public static BodyInserter buildBodyInserter(HttpMethod httpMethod, boolean isEncodeParams, @@ -49,12 +53,11 @@ public class RawHttpHandlerHelper { return BodyInserters.fromValue(queryBody); } - @SuppressWarnings("deprecation") private static boolean isJsonContentType(String requestContentType) { return MediaType.APPLICATION_JSON_VALUE.equals(requestContentType) - || MediaType.APPLICATION_JSON_UTF8_VALUE.equals(requestContentType) + || JSON_UTF8_CONTENT_TYPE.equals(requestContentType) || MediaType.APPLICATION_PROBLEM_JSON_VALUE.equals(requestContentType) - || MediaType.APPLICATION_PROBLEM_JSON_UTF8_VALUE.equals(requestContentType); + || PROBLEM_JSON_UTF8_CONTENT_TYPE.equals(requestContentType); } private static boolean isNoneContentType(String requestContentType) { diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/restapi/DataUtils.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/restapi/DataUtils.java index 4f7e93e769..fc6ec9c143 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/restapi/DataUtils.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/restapi/DataUtils.java @@ -18,9 +18,9 @@ // copied and adapted for rest api request package org.lowcoder.sdk.plugin.restapi; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; import com.google.common.collect.Streams; import jakarta.annotation.Nonnull; import org.apache.commons.collections4.CollectionUtils; @@ -60,8 +60,7 @@ public enum MultipartFormDataType { } private DataUtils() { - this.objectMapper = new ObjectMapper(); - this.objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + this.objectMapper = JsonMapper.builderWithJackson2Defaults().build(); } public static DataUtils getInstance() { @@ -200,16 +199,16 @@ public static List convertToMultiformFileValue(String fileVal private static MultipartFormData parseMultipartFormData(JsonNode jsonObject) { MultipartFormData result = new MultipartFormData(); JsonNode data = jsonObject.get("data"); - if (!data.isTextual()) { + if (!data.isString()) { throw new PluginException(DATASOURCE_ARGUMENT_ERROR, "MULTIFORM_DATA_IS_NOT_STRING"); } - result.setData(data.asText()); + result.setData(data.asString()); JsonNode name = jsonObject.get("name"); - if (!name.isTextual()) { + if (!name.isString()) { throw new PluginException(DATASOURCE_ARGUMENT_ERROR, "MULTIFORM_NAME_IS_NOT_STRING"); } - result.setName(name.asText()); + result.setName(name.asString()); return result; } } diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/restapi/auth/AuthConfig.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/restapi/auth/AuthConfig.java index bbc6225921..37d32187bb 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/restapi/auth/AuthConfig.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/restapi/auth/AuthConfig.java @@ -1,5 +1,6 @@ package org.lowcoder.sdk.plugin.restapi.auth; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; @@ -22,6 +23,7 @@ public abstract class AuthConfig implements Encrypt { protected final RestApiAuthType type; + @JsonCreator protected AuthConfig(RestApiAuthType type) { this.type = type; } diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetBulkObjectChangeSet.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetBulkObjectChangeSet.java index 249f09d7cc..ad76e33c76 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetBulkObjectChangeSet.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetBulkObjectChangeSet.java @@ -1,6 +1,6 @@ package org.lowcoder.sdk.plugin.sheet.changeset; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import org.lowcoder.sdk.exception.PluginException; import org.lowcoder.sdk.util.MustacheHelper; diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetChangeSetRow.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetChangeSetRow.java index 491c1843f8..797d8d4453 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetChangeSetRow.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetChangeSetRow.java @@ -1,7 +1,7 @@ package org.lowcoder.sdk.plugin.sheet.changeset; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.node.ObjectNode; import jakarta.annotation.Nonnull; import org.lowcoder.sdk.exception.PluginException; import org.lowcoder.sdk.util.JsonUtils; @@ -33,7 +33,7 @@ public static SheetChangeSetRow fromJsonNode(JsonNode node) { throw new PluginException(INVALID_GUI_SETTINGS, "GUI_INVALID_JSON_MAP_TYPE"); } List result = new ArrayList<>(); - Iterator> iterator = objectNode.fields(); + Iterator> iterator = objectNode.properties().iterator(); while (iterator.hasNext()) { Entry next = iterator.next(); String column = next.getKey(); diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetChangeSetRows.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetChangeSetRows.java index 0ab9144d05..0201bf088b 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetChangeSetRows.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetChangeSetRows.java @@ -1,8 +1,8 @@ package org.lowcoder.sdk.plugin.sheet.changeset; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.node.ArrayNode; import com.google.common.collect.Streams; import jakarta.annotation.Nonnull; import org.lowcoder.sdk.exception.PluginException; diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetObjectChangeSet.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetObjectChangeSet.java index a51defdc78..55bf1fcc97 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetObjectChangeSet.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sheet/changeset/SheetObjectChangeSet.java @@ -1,7 +1,7 @@ package org.lowcoder.sdk.plugin.sheet.changeset; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import org.lowcoder.sdk.exception.PluginException; import org.lowcoder.sdk.util.MustacheHelper; diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/GuiSqlCommand.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/GuiSqlCommand.java index fc620040e2..b9cd112a27 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/GuiSqlCommand.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/GuiSqlCommand.java @@ -51,7 +51,7 @@ public boolean returnsGeneratedKeys() { } static String parseTable(Map commandDetail) { - String table = MapUtils.getString(commandDetail, TABLE_KEY, null); + String table = MapUtils.getString(commandDetail, TABLE_KEY); if (StringUtils.isBlank(table)) { throw new PluginException(INVALID_GUI_SETTINGS, "GUI_FIELD_EMPTY"); } diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/BulkObjectChangeSet.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/BulkObjectChangeSet.java index 00508a6911..a56a6d9500 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/BulkObjectChangeSet.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/BulkObjectChangeSet.java @@ -1,6 +1,6 @@ package org.lowcoder.sdk.plugin.sqlcommand.changeset; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import org.lowcoder.sdk.exception.PluginException; import org.lowcoder.sdk.util.MustacheHelper; diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetRow.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetRow.java index bfeee100ff..db2c8bec51 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetRow.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetRow.java @@ -1,7 +1,7 @@ package org.lowcoder.sdk.plugin.sqlcommand.changeset; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.node.ObjectNode; import com.google.common.collect.Streams; import jakarta.annotation.Nonnull; import org.lowcoder.sdk.exception.PluginException; @@ -33,7 +33,7 @@ private static List parseChangeSetItems(JsonNode node) { throw new PluginException(INVALID_GUI_SETTINGS, "GUI_INVALID_JSON_MAP_TYPE"); } - return Streams.stream(objectNode.fields()) + return Streams.stream(objectNode.properties().iterator()) .map(next -> { String column = next.getKey(); JsonNode value = next.getValue(); diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetRows.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetRows.java index 01759c042d..2e1badbba6 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetRows.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetRows.java @@ -1,7 +1,7 @@ package org.lowcoder.sdk.plugin.sqlcommand.changeset; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.node.ArrayNode; import com.google.common.collect.Streams; import jakarta.annotation.Nonnull; import org.lowcoder.sdk.exception.PluginException; diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ObjectChangeSet.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ObjectChangeSet.java index f79a102e51..2f07e764ec 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ObjectChangeSet.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ObjectChangeSet.java @@ -1,6 +1,6 @@ package org.lowcoder.sdk.plugin.sqlcommand.changeset; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import org.lowcoder.sdk.exception.PluginException; import org.lowcoder.sdk.util.MustacheHelper; diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/HttpHeaderMaps.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/HttpHeaderMaps.java new file mode 100644 index 0000000000..7f5c35804c --- /dev/null +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/HttpHeaderMaps.java @@ -0,0 +1,32 @@ +package org.lowcoder.sdk.util; + +import java.util.List; +import java.util.Locale; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.CollectionUtils; +import org.springframework.util.LinkedCaseInsensitiveMap; +import org.springframework.util.MultiValueMap; + +/** + * {@link HttpHeaders} as a map. Since Spring 7 it is no longer a {@code MultiValueMap}, and its {@code asMultiValueMap()} + * bridge is deprecated for removal, so the code that needs the headers as a {@code Map} (to remove a header, to hand them + * over as a plain map, to write them as JSON) takes this copy. + * + *

Limits: it is a snapshot; changes to the copy do not reach the headers it was made from, and the reverse. + */ +public final class HttpHeaderMaps { + + private HttpHeaderMaps() { + } + + /** + * A writable copy of {@code headers} that compares header names without regard to case, as {@link HttpHeaders} does, + * keeps their order and the case of the first spelling, and is a {@code Map>}. + */ + public static MultiValueMap copyOf(HttpHeaders headers) { + MultiValueMap copy = CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap>(Locale.ENGLISH)); + headers.forEach(copy::addAll); + return copy; + } +} diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/JsonUtils.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/JsonUtils.java index 6c50845564..6ffb14d708 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/JsonUtils.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/JsonUtils.java @@ -1,19 +1,25 @@ package org.lowcoder.sdk.util; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.databind.jsontype.NamedType; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.fasterxml.jackson.databind.type.CollectionType; -import com.fasterxml.jackson.databind.type.MapType; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; +import tools.jackson.core.StreamReadConstraints; +import tools.jackson.core.json.JsonFactory; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.MapperFeature; +import tools.jackson.databind.ObjectWriter; +import tools.jackson.databind.SerializationFeature; +import tools.jackson.databind.cfg.ConstructorDetector; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.jsontype.NamedType; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; +import tools.jackson.databind.type.CollectionType; +import tools.jackson.databind.type.MapType; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import jakarta.annotation.Nullable; import lombok.extern.slf4j.Slf4j; import org.lowcoder.sdk.auth.*; +import tools.jackson.core.JacksonException; import java.nio.charset.StandardCharsets; import java.util.List; @@ -25,34 +31,54 @@ @Slf4j public final class JsonUtils { - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - static { - OBJECT_MAPPER.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES)); - OBJECT_MAPPER.registerModule(new JavaTimeModule()); - OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); - // register sub types - OBJECT_MAPPER.registerSubtypes(new NamedType(EmailAuthConfig.class, FORM)); - OBJECT_MAPPER.registerSubtypes(new NamedType(Oauth2SimpleAuthConfig.class, GITHUB)); - OBJECT_MAPPER.registerSubtypes(new NamedType(Oauth2SimpleAuthConfig.class, GOOGLE)); - OBJECT_MAPPER.registerSubtypes(new NamedType(Oauth2OryAuthConfig.class, ORY)); - OBJECT_MAPPER.registerSubtypes(new NamedType(Oauth2KeycloakAuthConfig.class, KEYCLOAK)); - OBJECT_MAPPER.registerSubtypes(new NamedType(Oauth2GenericAuthConfig.class, GENERIC)); - } + /** Jackson 2's read limits: Jackson 3 lowers the nesting depth to 500 and raises the string length. */ + private static final int MAX_NESTING_DEPTH = 1000; + private static final int MAX_STRING_LENGTH = 20_000_000; + + private static final JsonFactory JSON_FACTORY = JsonFactory.builderWithJackson2Defaults() + .streamReadConstraints(StreamReadConstraints.builder() + .maxNestingDepth(MAX_NESTING_DEPTH) + .maxStringLength(MAX_STRING_LENGTH) + .build()) + .build(); + + /** + * Jackson 3 changed several defaults. The mapper keeps the Jackson 2 ones through {@link JsonMapper.Builder#configureForJackson2()} + * (dates as timestamps, for one), and states the settings the application has always relied on that it does not + * restore: constructor parameters are named by the compiler's {@code -parameters} (the Jackson 2 parameter names + * module was registered), a constructor of any visibility can be the creator (Lombok's all-args constructor is + * package-private) but only when the class has no default constructor, accessor names are lower-cased as in Jackson 2 ({@link LegacyBeanNaming}), properties + * without a {@code @JsonView} stay in every view, and unknown properties and empty beans are tolerated. + */ + private static final JsonMapper OBJECT_MAPPER = JsonMapper.builder(JSON_FACTORY).configureForJackson2() + .propertyNamingStrategy(new LegacyBeanNaming()) + .changeDefaultVisibility(visibility -> visibility.withCreatorVisibility(Visibility.ANY)) + .constructorDetector(ConstructorDetector.DEFAULT.withAllowImplicitWithDefaultConstructor(false)) + .enable(MapperFeature.DETECT_PARAMETER_NAMES) + .enable(MapperFeature.DEFAULT_VIEW_INCLUSION) + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) + // register sub types + .registerSubtypes(new NamedType(EmailAuthConfig.class, FORM)) + .registerSubtypes(new NamedType(Oauth2SimpleAuthConfig.class, GITHUB)) + .registerSubtypes(new NamedType(Oauth2SimpleAuthConfig.class, GOOGLE)) + .registerSubtypes(new NamedType(Oauth2OryAuthConfig.class, ORY)) + .registerSubtypes(new NamedType(Oauth2KeycloakAuthConfig.class, KEYCLOAK)) + .registerSubtypes(new NamedType(Oauth2GenericAuthConfig.class, GENERIC)) + .build(); public static final JsonNode EMPTY_JSON_NODE = createObjectNode(); private static final ObjectWriter WRITER = OBJECT_MAPPER.writer(); - public static ObjectMapper getObjectMapper() { + public static JsonMapper getObjectMapper() { return OBJECT_MAPPER; } public static String toJson(Object obj) { try { return WRITER.writeValueAsString(obj); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { log.error("fail to print json of class type: {}", obj.getClass().getSimpleName(), e); return ""; } @@ -61,20 +87,20 @@ public static String toJson(Object obj) { public static String toJsonSafely(Object obj, Class viewClass) { try { return OBJECT_MAPPER.writerWithView(viewClass).writeValueAsString(obj); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { log.error("fail to print json of class type: {}", obj.getClass().getSimpleName(), e); return ""; } } - public static String toJsonThrows(Object obj) throws JsonProcessingException { + public static String toJsonThrows(Object obj) { return WRITER.writeValueAsString(obj); } public static T fromJson(String obj, Class tClass) { try { return OBJECT_MAPPER.readValue(obj, tClass); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { log.error("fail to print json of class type: {}", obj.getClass().getSimpleName(), e); return null; } @@ -83,7 +109,7 @@ public static T fromJson(String obj, Class tClass) { public static T fromJsonSafely(String obj, TypeReference valueTypeRef, @Nullable T defaultValue) { try { return OBJECT_MAPPER.readValue(obj, valueTypeRef); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { log.error("fail to print json of class type: {}", valueTypeRef.getType().getTypeName(), e); return defaultValue; } @@ -92,7 +118,7 @@ public static T fromJsonSafely(String obj, TypeReference valueTypeRef, @N public static T fromJsonQuietly(String obj, Class tClass) { try { return OBJECT_MAPPER.readValue(obj, tClass); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { return null; } } @@ -105,7 +131,7 @@ public static List fromJsonList(String obj, Class tClass) { try { CollectionType javaType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, tClass); return OBJECT_MAPPER.readValue(obj, javaType); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { log.error("fail to print json of class type: {}", obj.getClass().getSimpleName(), e); return null; } @@ -115,7 +141,7 @@ public static Set fromJsonSet(String obj, Class tClass) { try { CollectionType javaType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(Set.class, tClass); return OBJECT_MAPPER.readValue(obj, javaType); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { log.error("fail to print json of class type: {}", obj.getClass().getSimpleName(), e); return null; } @@ -129,17 +155,17 @@ public static Map fromJsonMap(String obj, Class kClass, Class try { MapType mapType = OBJECT_MAPPER.getTypeFactory().constructMapType(Map.class, kClass, vClass); return OBJECT_MAPPER.readValue(obj, mapType); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { log.error("fail to print json of class type: {}", obj.getClass().getSimpleName(), e); return null; } } - public static JsonNode readTree(byte[] body) throws JsonProcessingException { + public static JsonNode readTree(byte[] body) { return OBJECT_MAPPER.readTree(new String(body, StandardCharsets.UTF_8)); } - public static JsonNode readTree(String value) throws JsonProcessingException { + public static JsonNode readTree(String value) { return OBJECT_MAPPER.readTree(value); } @@ -158,7 +184,7 @@ public static ArrayNode createArrayNode() { public static Object jsonNodeToObject(JsonNode jsonNode) { try { return OBJECT_MAPPER.treeToValue(jsonNode, Object.class); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { log.error("jsonNode to object error ", e); return null; } diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/LegacyBeanNaming.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/LegacyBeanNaming.java new file mode 100644 index 0000000000..77d50911e6 --- /dev/null +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/LegacyBeanNaming.java @@ -0,0 +1,42 @@ +package org.lowcoder.sdk.util; + +import tools.jackson.databind.PropertyNamingStrategy; +import tools.jackson.databind.cfg.MapperConfig; +import tools.jackson.databind.introspect.AnnotatedMethod; + +/** + * Names the properties of getters and setters as Jackson 2 did. + * + *

Jackson 2 lower-cased the whole leading run of upper-case letters of an accessor name ({@code getSQLTypeName} became + * {@code sqltypeName}, {@code getURL} became {@code url}); Jackson 3 follows the JavaBeans rule and keeps a name that + * starts with two upper-case letters ({@code SQLTypeName}, {@code URL}). The strategy receives the Jackson 3 name and + * lower-cases that leading run, which gives the Jackson 2 name in every case. Field names and constructor parameter + * names are left as they are, as they were in Jackson 2. + * + *

Limit: it renames only properties that Jackson names implicitly. A name given with {@code @JsonProperty} is never + * passed through it. + */ +public final class LegacyBeanNaming extends PropertyNamingStrategy { + + @Override + public String nameForGetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName) { + return lowerCaseLeadingRun(defaultName); + } + + @Override + public String nameForSetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName) { + return lowerCaseLeadingRun(defaultName); + } + + /** {@code SQLTypeName} to {@code sqltypeName}; a name that does not start with an upper-case letter is returned as it is. */ + static String lowerCaseLeadingRun(String name) { + int end = 0; + while (end < name.length() && Character.isUpperCase(name.charAt(end))) { + end++; + } + if (end == 0) { + return name; + } + return name.substring(0, end).toLowerCase() + name.substring(end); + } +} diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/MustacheHelper.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/MustacheHelper.java index 5969841528..46d9ee3613 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/MustacheHelper.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/MustacheHelper.java @@ -19,7 +19,7 @@ package org.lowcoder.sdk.util; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.google.common.annotations.VisibleForTesting; diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/RjsonMustacheParser.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/RjsonMustacheParser.java index e83f410b07..8c63e4d080 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/RjsonMustacheParser.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/RjsonMustacheParser.java @@ -1,12 +1,13 @@ package org.lowcoder.sdk.util; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.*; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.node.*; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.lowcoder.sdk.exception.PluginException; +import tools.jackson.databind.node.StringNode; import tv.twelvetone.json.Json; import tv.twelvetone.json.JsonObject.Member; import tv.twelvetone.json.JsonValue; @@ -51,7 +52,7 @@ public static JsonNode renderMustacheJson(String jsonStr, Map paramMa return traverse(RjsonParser.parse(oneTokenStr), Map.of()); } catch (Throwable e) { // return as a textNode if fails to parse - return TextNode.valueOf(oneTokenStr); + return StringNode.valueOf(oneTokenStr); } } @@ -124,28 +125,28 @@ private static JsonNode traverse(JsonValue jsonValue, Map paramM private static String tryResolveAsString(String input, Map paramMap) { JsonNode jsonNode = tryResolve(Json.INSTANCE.value(input), paramMap, true); - return jsonNode.textValue(); + return jsonNode.stringValue(); } private static JsonNode tryResolve(JsonValue jsonValue, Map paramMap, boolean toStringType) { String input = jsonValue.asString().trim(); if (isBlank(input)) { - return TextNode.valueOf(input); + return StringNode.valueOf(input); } var checkStringResult = checkString(input); if (checkStringResult.isRawStr()) { - return TextNode.valueOf(input); + return StringNode.valueOf(input); } if (toStringType || checkStringResult.isQuotedStr()) { - return TextNode.valueOf(MustacheHelper.renderMustacheTokens(tokenize(checkStringResult.result()), paramMap, true, token -> isGeneratedMustache(token, paramMap))); + return StringNode.valueOf(MustacheHelper.renderMustacheTokens(tokenize(checkStringResult.result()), paramMap, true, token -> isGeneratedMustache(token, paramMap))); } List tokenize = tokenize(input); if (tokenize.isEmpty()) { - return TextNode.valueOf(input); + return StringNode.valueOf(input); } if (tokenize.size() == 1) { @@ -156,7 +157,7 @@ private static JsonNode tryResolve(JsonValue jsonValue, Map para } } - return TextNode.valueOf(MustacheHelper.renderMustacheTokens(tokenize, paramMap, true, token -> isGeneratedMustache(token, paramMap))); + return StringNode.valueOf(MustacheHelper.renderMustacheTokens(tokenize, paramMap, true, token -> isGeneratedMustache(token, paramMap))); } private static JsonNode convertToJsonNode(Object mustacheValue) { @@ -176,7 +177,7 @@ private static JsonNode convertToJsonNode(Object mustacheValue) { return BooleanNode.valueOf((boolean) mustacheValue); } - return TextNode.valueOf(mustacheValue.toString()); + return StringNode.valueOf(mustacheValue.toString()); } @Nullable diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/SqlGuiUtils.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/SqlGuiUtils.java index 3f6ef1ef6a..5bbe42e217 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/SqlGuiUtils.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/util/SqlGuiUtils.java @@ -1,6 +1,6 @@ package org.lowcoder.sdk.util; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import jakarta.annotation.Nonnull; import org.apache.commons.lang3.RandomStringUtils; import org.lowcoder.sdk.exception.PluginException; diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/JacksonClientCodecs.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/JacksonClientCodecs.java new file mode 100644 index 0000000000..c45de2c74f --- /dev/null +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/JacksonClientCodecs.java @@ -0,0 +1,38 @@ +package org.lowcoder.sdk.webclient; + +import org.springframework.http.codec.ClientCodecConfigurer; +import org.springframework.http.codec.json.JacksonJsonDecoder; +import org.springframework.http.codec.json.JacksonJsonEncoder; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Gives the JSON codecs of the application's outbound {@code WebClient}s the Jackson 2 configuration they had before + * Jackson 3: dates written as timestamps, properties in declaration order, unknown properties ignored. + * + *

Spring's default Jackson 3 codecs write dates as ISO strings and sort bean properties alphabetically, which changes + * the bytes of every request body that holds a bean or a date. A codec set explicitly wins over the default, so this sets + * both slots, with one mapper each, as the defaults do. + * + *

Limits: it covers only the clients that call it ({@link WebClientBuildHelper} and the exchange strategies declared by + * the code that does not go through the helper). A {@code WebClient} or {@code ExchangeStrategies} built anywhere else + * keeps Spring's defaults. The mappers are not the production mapper ({@code JsonUtils}): they register none of its + * subtypes. + */ +public final class JacksonClientCodecs { + + private JacksonClientCodecs() { + } + + /** Sets a JSON encoder and decoder with the Jackson 2 configuration on {@code configurer}'s default codecs. */ + public static void apply(ClientCodecConfigurer configurer) { + configurer.defaultCodecs().jacksonJsonEncoder(new JacksonJsonEncoder(mapper())); + configurer.defaultCodecs().jacksonJsonDecoder(new JacksonJsonDecoder(mapper())); + } + + private static JsonMapper mapper() { + return JsonMapper.builderWithJackson2Defaults() + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + } +} diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/WebClientBuildHelper.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/WebClientBuildHelper.java index c1d4620376..c04c663771 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/WebClientBuildHelper.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/WebClientBuildHelper.java @@ -129,9 +129,10 @@ public Builder toWebClientBuilder() { httpClient = httpClient.resolver(new SafeHostResolverGroup(disallowedHosts)); } return WebClient.builder() - .codecs(codecs -> codecs - .defaultCodecs() - .maxInMemorySize(maxInMemorySize)) + .codecs(codecs -> { + JacksonClientCodecs.apply(codecs); + codecs.defaultCodecs().maxInMemorySize(maxInMemorySize); + }) .clientConnector(new ReactorClientHttpConnector(httpClient)); } diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/WebClientRedirects.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/WebClientRedirects.java index dee90d056c..4927a397dd 100644 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/WebClientRedirects.java +++ b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/WebClientRedirects.java @@ -93,7 +93,7 @@ && equalsIgnoreCase(first.getHost(), second.getHost()) public static WebClient forAnotherOrigin(WebClient webClient) { return webClient.mutate() .defaultHeaders(headers -> { - List dropped = headers.keySet().stream() + List dropped = headers.headerNames().stream() .filter(name -> !HEADERS_KEPT_FOR_ANOTHER_ORIGIN.contains(name.toLowerCase(Locale.ROOT))) .toList(); dropped.forEach(headers::remove); diff --git a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/WebClients.java b/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/WebClients.java deleted file mode 100644 index a1a36a6c94..0000000000 --- a/server/api-service/lowcoder-sdk/src/main/java/org/lowcoder/sdk/webclient/WebClients.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.lowcoder.sdk.webclient; - -import org.springframework.web.reactive.function.client.WebClient; - -public class WebClients { - - private static final WebClient INSTANCE = WebClient.builder().build(); - - public static WebClient getInstance() { - return INSTANCE; - } -} diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/CanonicalJson.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/CanonicalJson.java index d4e656c49e..5fc9a2ffd9 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/CanonicalJson.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/CanonicalJson.java @@ -1,8 +1,8 @@ package org.lowcoder.sdk.contract; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; +import tools.jackson.core.JsonParser; +import tools.jackson.core.JsonToken; +import tools.jackson.core.json.JsonFactory; import java.io.IOException; import java.io.UncheckedIOException; @@ -29,7 +29,7 @@ * reported), the order of different object members, and the escape form of strings and keys. * *

The documents are read with Jackson's streaming {@link JsonParser}, never with a mapper: number tokens keep - * their lexeme ({@link JsonParser#getText()}) and every object keeps all its members, duplicates included, as a list + * their lexeme ({@link JsonParser#getString()}) and every object keeps all its members, duplicates included, as a list * of (key, value) pairs. Members are grouped by key; groups are compared regardless of key order, and values inside * a group in order. * @@ -100,7 +100,7 @@ private static Node read(JsonParser parser, String source) throws IOException { switch (token) { case START_OBJECT -> { List members = new ArrayList<>(); - while (parser.nextToken() == JsonToken.FIELD_NAME) { + while (parser.nextToken() == JsonToken.PROPERTY_NAME) { String key = parser.currentName(); String rawKey = rawText(parser, source); parser.nextToken(); @@ -116,11 +116,11 @@ private static Node read(JsonParser parser, String source) throws IOException { return new ArrayValue(elements); } case VALUE_STRING -> { - String value = parser.getText(); + String value = parser.getString(); return new ScalarValue(ScalarKind.STRING, value, rawText(parser, source)); } case VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT -> { - String lexeme = parser.getText(); + String lexeme = parser.getString(); return new ScalarValue(ScalarKind.NUMBER, lexeme, lexeme); } case VALUE_TRUE -> { diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ClientCodecs.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ClientCodecs.java index 9b02a7e495..d7ccb7f3db 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ClientCodecs.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ClientCodecs.java @@ -1,18 +1,19 @@ package org.lowcoder.sdk.contract; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; import org.lowcoder.sdk.util.JsonUtils; +import org.lowcoder.sdk.webclient.JacksonClientCodecs; import org.lowcoder.sdk.webclient.WebClientBuildHelper; import org.springframework.http.codec.DecoderHttpMessageReader; import org.springframework.http.codec.EncoderHttpMessageWriter; import org.springframework.http.codec.HttpMessageReader; import org.springframework.http.codec.HttpMessageWriter; -import org.springframework.http.codec.json.Jackson2JsonDecoder; -import org.springframework.http.codec.json.Jackson2JsonEncoder; +import org.springframework.http.codec.json.JacksonJsonDecoder; +import org.springframework.http.codec.json.JacksonJsonEncoder; import org.springframework.web.reactive.function.client.ExchangeStrategies; import org.springframework.web.reactive.function.client.WebClient; +import tools.jackson.databind.cfg.DateTimeFeature; import java.lang.reflect.Method; @@ -22,11 +23,12 @@ /** * Spring's default client codecs as the application builds them (docs/API_PAYLOAD_TEST_PLAN.md §1.1, §3.2, §5.4). * - *

All five {@code codecs(...)} constructions of the application set only {@code maxInMemorySize} on the default - * codecs: {@code WebClientBuildHelper.java:131-134} (20 MB by default), {@code JsLibraryController.java:62-65} (-1), - * {@code DatasourcePluginClient.java:42-45} (-1), {@code GraphQLExecutor.java:88-91} (10 MB) and - * {@code RestApiExecutor.java:102-105} (-1). {@link #strategies(int)} builds the same thing, so tests can encode and - * decode with the client codecs without a network client. + *

The application builds its client codecs in six places, and each sets {@link JacksonClientCodecs#apply} and then + * {@code maxInMemorySize} on the default codecs: {@code WebClientBuildHelper.java:131-136} (20 MB by default), + * {@code JsLibraryController.java:63-69} (-1), {@code DatasourcePluginClient.java:43-49} (-1), + * {@code GraphQLExecutor.java:90-96} (10 MB), {@code RestApiExecutor.java:104-110} (-1) and + * {@code MarketplaceRenderClient.java:23-28} (2 MiB). {@link #strategies(int)} builds the same thing, so tests can encode + * and decode with the client codecs without a network client. * *

Effective limit (plan §9, O11; evidence E14). {@code JsLibraryController}, {@code GraphQLExecutor} and * {@code RestApiExecutor} pass their strategies to a builder from {@code WebClientBuildHelper}, whose own @@ -35,8 +37,8 @@ * declared value is overwritten. {@link #effectiveThroughWebClientBuildHelper} returns what a request gets. * *

{@link #DEFAULT_CODEC_PROFILE} pins the configuration of the mapper inside those codecs as observed in E8 - * (docs/tools/plan-evidence.out). Spring builds that mapper with {@code Jackson2ObjectMapperBuilder}, which adds the - * well-known modules found on the classpath, so the profile depends on the classpath it is built on. + * (docs/tools/plan-evidence.out): the Jackson 2 settings that {@link JacksonClientCodecs} keeps. Jackson 3 has the + * java time and parameter name support built in, so the profile lists no module. */ public final class ClientCodecs { @@ -45,9 +47,7 @@ public final class ClientCodecs { private static final String INIT_EXCHANGE_STRATEGIES = "initExchangeStrategies"; /** E8: the codec mapper writes dates as timestamps, reads them as nanoseconds, ignores unknown properties. */ - public static final MapperProfile DEFAULT_CODEC_PROFILE = new MapperProfile(true, true, false, - List.of("com.fasterxml.jackson.datatype.jdk8.Jdk8Module", "jackson-module-parameter-names", - "jackson-datatype-jsr310")); + public static final MapperProfile DEFAULT_CODEC_PROFILE = new MapperProfile(true, true, false, List.of()); private ClientCodecs() { } @@ -58,17 +58,17 @@ public record MapperProfile(boolean writeDatesAsTimestamps, boolean readDateTime } public static MapperProfile profile(ObjectMapper mapper) { - return new MapperProfile(mapper.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS), - mapper.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS), + return new MapperProfile(mapper.isEnabled(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS), + mapper.isEnabled(DateTimeFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS), mapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES), - mapper.getRegisteredModuleIds().stream().map(String::valueOf).collect(Collectors.toList())); + mapper.registeredModules().stream().map(module -> String.valueOf(module.getRegistrationId())).collect(Collectors.toList())); } /** * The strategies a {@link WebClient} built by the application from {@code declared} really uses: a builder from * {@code WebClientBuildHelper.builder().systemProxy().toWebClientBuilder()} with {@code exchangeStrategies(declared)}, - * as {@code JsLibraryController.java:148-152}, {@code GraphQLExecutor.java:247-270} and - * {@code RestApiExecutor.java:236-262} build it. Their other builder calls (headers, cookies, filters, SSL, timeout, + * as {@code JsLibraryController.java:152-156}, {@code GraphQLExecutor.java:252-275} and + * {@code RestApiExecutor.java:241-267} build it. Their other builder calls (headers, cookies, filters, SSL, timeout, * disallowed hosts) do not touch the codecs. * *

Limit: it reads Spring's non-public {@code DefaultWebClientBuilder#initExchangeStrategies}, so a Spring upgrade @@ -89,18 +89,21 @@ public static ExchangeStrategies effective(WebClient.Builder builder) { } } - /** The exchange strategies of {@code ExchangeStrategies.builder().codecs(c -> c.defaultCodecs().maxInMemorySize(n))}. */ + /** The exchange strategies of the application's clients: {@link JacksonClientCodecs#apply}, then {@code maxInMemorySize(n)}. */ public static ExchangeStrategies strategies(int maxInMemorySize) { return ExchangeStrategies.builder() - .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(maxInMemorySize)) + .codecs(configurer -> { + JacksonClientCodecs.apply(configurer); + configurer.defaultCodecs().maxInMemorySize(maxInMemorySize); + }) .build(); } - public static Jackson2JsonEncoder encoder(ExchangeStrategies strategies) { + public static JacksonJsonEncoder encoder(ExchangeStrategies strategies) { return encoder(strategies.messageWriters()); } - public static Jackson2JsonDecoder decoder(ExchangeStrategies strategies) { + public static JacksonJsonDecoder decoder(ExchangeStrategies strategies) { return decoder(strategies.messageReaders()); } @@ -111,21 +114,21 @@ public static Jackson2JsonDecoder decoder(ExchangeStrategies strategies) { * builds an equal configuration. */ public static void assertDefaultClientCodecs(String construction, ExchangeStrategies real, int expectedMaxInMemorySize) { - Jackson2JsonEncoder encoder = encoder(real); - Jackson2JsonDecoder decoder = decoder(real); - MapperProfile encoderProfile = profile(encoder.getObjectMapper()); - MapperProfile decoderProfile = profile(decoder.getObjectMapper()); + JacksonJsonEncoder encoder = encoder(real); + JacksonJsonDecoder decoder = decoder(real); + MapperProfile encoderProfile = profile(encoder.getMapper()); + MapperProfile decoderProfile = profile(decoder.getMapper()); System.out.println("[client-codec-guard] " + construction + ": encoder " + encoderProfile + ", decoder " + decoderProfile + ", maxInMemorySize " + decoder.getMaxInMemorySize()); ObjectMapper production = JsonUtils.getObjectMapper(); - assertTrue(construction + ": encoder mapper must not be the production mapper", encoder.getObjectMapper() != production); - assertTrue(construction + ": decoder mapper must not be the production mapper", decoder.getObjectMapper() != production); - assertTrue(construction + ": encoder and decoder must have separate mappers", encoder.getObjectMapper() != decoder.getObjectMapper()); + assertTrue(construction + ": encoder mapper must not be the production mapper", encoder.getMapper() != production); + assertTrue(construction + ": decoder mapper must not be the production mapper", decoder.getMapper() != production); + assertTrue(construction + ": encoder and decoder must have separate mappers", encoder.getMapper() != decoder.getMapper()); assertEquals(construction + ": decoder maxInMemorySize", expectedMaxInMemorySize, decoder.getMaxInMemorySize()); assertEquals(construction + ": encoder mapper", DEFAULT_CODEC_PROFILE, encoderProfile); assertEquals(construction + ": decoder mapper", DEFAULT_CODEC_PROFILE, decoderProfile); ExchangeStrategies rebuilt = strategies(expectedMaxInMemorySize); - assertEquals(construction + ": ClientCodecs rebuild", encoderProfile, profile(encoder(rebuilt).getObjectMapper())); + assertEquals(construction + ": ClientCodecs rebuild", encoderProfile, profile(encoder(rebuilt).getMapper())); assertEquals(construction + ": ClientCodecs rebuild maxInMemorySize", expectedMaxInMemorySize, decoder(rebuilt).getMaxInMemorySize()); } @@ -143,22 +146,22 @@ private static void assertEquals(String message, Object expected, Object actual) } /** The Jackson JSON encoder among {@code writers}; fails if there is none. */ - public static Jackson2JsonEncoder encoder(List> writers) { + public static JacksonJsonEncoder encoder(List> writers) { return writers.stream() .filter(writer -> writer instanceof EncoderHttpMessageWriter encoderWriter - && encoderWriter.getEncoder() instanceof Jackson2JsonEncoder) - .map(writer -> (Jackson2JsonEncoder) ((EncoderHttpMessageWriter) writer).getEncoder()) + && encoderWriter.getEncoder() instanceof JacksonJsonEncoder) + .map(writer -> (JacksonJsonEncoder) ((EncoderHttpMessageWriter) writer).getEncoder()) .findFirst() - .orElseThrow(() -> new AssertionError("no Jackson2JsonEncoder among " + writers)); + .orElseThrow(() -> new AssertionError("no JacksonJsonEncoder among " + writers)); } /** The Jackson JSON decoder among {@code readers}; fails if there is none. */ - public static Jackson2JsonDecoder decoder(List> readers) { + public static JacksonJsonDecoder decoder(List> readers) { return readers.stream() .filter(reader -> reader instanceof DecoderHttpMessageReader decoderReader - && decoderReader.getDecoder() instanceof Jackson2JsonDecoder) - .map(reader -> (Jackson2JsonDecoder) ((DecoderHttpMessageReader) reader).getDecoder()) + && decoderReader.getDecoder() instanceof JacksonJsonDecoder) + .map(reader -> (JacksonJsonDecoder) ((DecoderHttpMessageReader) reader).getDecoder()) .findFirst() - .orElseThrow(() -> new AssertionError("no Jackson2JsonDecoder among " + readers)); + .orElseThrow(() -> new AssertionError("no JacksonJsonDecoder among " + readers)); } } diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ClientCodecsTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ClientCodecsTest.java index 9621e1370c..4f8ffd5867 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ClientCodecsTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ClientCodecsTest.java @@ -1,10 +1,10 @@ package org.lowcoder.sdk.contract; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; import org.junit.jupiter.api.Test; import org.lowcoder.sdk.util.JsonUtils; -import org.springframework.http.codec.json.Jackson2JsonDecoder; -import org.springframework.http.codec.json.Jackson2JsonEncoder; +import org.springframework.http.codec.json.JacksonJsonDecoder; +import org.springframework.http.codec.json.JacksonJsonEncoder; import org.springframework.web.reactive.function.client.ExchangeStrategies; import static org.assertj.core.api.Assertions.assertThat; @@ -21,27 +21,27 @@ public class ClientCodecsTest { @Test public void strategiesExposeSeparateEncoderAndDecoderMappers() { ExchangeStrategies strategies = ClientCodecs.strategies(ClientCodecs.UNLIMITED); - assertThat(ClientCodecs.encoder(strategies).getObjectMapper()) - .isNotSameAs(ClientCodecs.decoder(strategies).getObjectMapper()); + assertThat(ClientCodecs.encoder(strategies).getMapper()) + .isNotSameAs(ClientCodecs.decoder(strategies).getMapper()); assertThat(ClientCodecs.decoder(strategies).getMaxInMemorySize()).isEqualTo(ClientCodecs.UNLIMITED); } @Test public void guardRejectsTheProductionMapper() { - ObjectMapper production = JsonUtils.getObjectMapper(); + JsonMapper production = JsonUtils.getObjectMapper(); ExchangeStrategies drifted = ExchangeStrategies.builder().codecs(configurer -> { - configurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(production)); - configurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(new ObjectMapper())); + configurer.defaultCodecs().jacksonJsonEncoder(new JacksonJsonEncoder(production)); + configurer.defaultCodecs().jacksonJsonDecoder(new JacksonJsonDecoder(JsonMapper.builder().build())); }).build(); assertRejected(drifted, ClientCodecs.UNLIMITED, "encoder mapper must not be the production mapper"); } @Test public void guardRejectsOneSharedMapper() { - ObjectMapper shared = new ObjectMapper(); + JsonMapper shared = JsonMapper.builder().build(); ExchangeStrategies drifted = ExchangeStrategies.builder().codecs(configurer -> { - configurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(shared)); - configurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(shared)); + configurer.defaultCodecs().jacksonJsonEncoder(new JacksonJsonEncoder(shared)); + configurer.defaultCodecs().jacksonJsonDecoder(new JacksonJsonDecoder(shared)); }).build(); assertRejected(drifted, ClientCodecs.UNLIMITED, "encoder and decoder must have separate mappers"); } @@ -54,7 +54,7 @@ public void guardRejectsAnotherBufferLimit() { @Test public void guardRejectsAnotherMapperConfiguration() { ExchangeStrategies drifted = ExchangeStrategies.builder().codecs(configurer -> { - configurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(new ObjectMapper())); + configurer.defaultCodecs().jacksonJsonEncoder(new JacksonJsonEncoder(JsonMapper.builder().build())); configurer.defaultCodecs().maxInMemorySize(ClientCodecs.UNLIMITED); }).build(); assertRejected(drifted, ClientCodecs.UNLIMITED, "encoder mapper: expected " + ClientCodecs.DEFAULT_CODEC_PROFILE); diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ConfigBinding.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ConfigBinding.java index f06b9533ec..3be0734eb4 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ConfigBinding.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ConfigBinding.java @@ -1,12 +1,12 @@ package org.lowcoder.sdk.contract; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.util.RawValue; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.util.RawValue; import org.lowcoder.sdk.config.JsonViews; import org.lowcoder.sdk.exception.PluginException; import org.lowcoder.sdk.util.JsonUtils; +import tools.jackson.core.JacksonException; import java.util.LinkedHashMap; import java.util.Map; @@ -85,7 +85,7 @@ public static Map> forms(String json) { try { return MAPPER.readValue(json, new TypeReference>>() { }); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { throw new IllegalArgumentException("config-binding input is not an object of forms: " + e.getOriginalMessage(), e); } } @@ -146,7 +146,7 @@ public static String errorText(Throwable error) { public static String write(Object report) { try { return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(report); - } catch (JsonProcessingException e) { + } catch (JacksonException e) { throw new IllegalStateException("cannot write config-binding report", e); } } @@ -154,7 +154,7 @@ public static String write(Object report) { private static Object written(Object bound, Class view) { try { return new RawValue(view == null ? MAPPER.writeValueAsString(bound) : MAPPER.writerWithView(view).writeValueAsString(bound)); - } catch (JsonProcessingException | RuntimeException e) { + } catch (RuntimeException e) { return Map.of(ERROR_KEY, errorText(e)); } } diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ConfigBindingTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ConfigBindingTest.java index af7027c730..b75ccbdbaa 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ConfigBindingTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ConfigBindingTest.java @@ -1,7 +1,7 @@ package org.lowcoder.sdk.contract; import com.fasterxml.jackson.annotation.JsonView; -import com.fasterxml.jackson.databind.util.RawValue; +import tools.jackson.databind.util.RawValue; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.lowcoder.sdk.config.JsonViews; diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ContainerImages.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ContainerImages.java index d53fe8805b..4e23238c2c 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ContainerImages.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/ContainerImages.java @@ -18,14 +18,11 @@ *

Licences (confirmed from each image's documentation, 2026-10-04): MySQL GPLv2; PostgreSQL License; Redis 7.2.4 * BSD-3; MongoDB SSPL; ClickHouse Apache-2.0; SQL Server under its EULA (Developer/Express editions, no production use); * Elasticsearch 8.15 Elastic License 2.0; Oracle Database Free under the Oracle Free Use Terms (the image packaging - * Apache-2.0). They are used for tests only (owner decision D-5). + * Apache-2.0). smtp4dev BSD-3-Clause (the repository's licence on GitHub, 2026-11-20). They are used for tests only (owner decision D-5). */ public final class ContainerImages { - /** The server's tests: the line of the embedded mongod they ran against before (4.0.2). */ - public static final String MONGO_4_0 = - "mongo:4.0.28@sha256:4ca81c89ad08f4cfa9906005126112bffe8fb363800466ef5e50f6238f6f6af1"; - /** mongoPlugin's container tests. */ + /** The MongoDB container of lowcoder-server's Spring tests ({@code TestContainers}) and of mongoPlugin's container tests. */ public static final String MONGO_7_0 = "mongo:7.0@sha256:d5b3ca8c3f3cdce78d44870dc0871b76d5235e9b2ad4ea6bea5d1fbff8027703"; public static final String REDIS_7_2 = @@ -36,6 +33,14 @@ public final class ContainerImages { "mysql:8.0@sha256:7dcddc01f13bab2f15cde676d44d01f61fc9f99fe7785e86196dfc07d358ae2b"; public static final String CLICKHOUSE_24_8 = "clickhouse/clickhouse-server:24.8-alpine@sha256:b002e56ed5c16e224c312527f6fcba7e77216fec5d7a88a7828f59efc614feb5"; + /** + * An SMTP server that generates its own self-signed certificate at start and offers STARTTLS when started with + * {@code ServerOptions__TlsMode=StartTls} (smtpPlugin's STARTTLS tests); its HTTP API on port 80 lists the messages it received. + * The digest is the registry's index digest, read with {@code docker pull} and {@code docker inspect --format '{{index .RepoDigests 0}}'} + * on 2026-11-20. + */ + public static final String SMTP4DEV_3_6 = + "rnwood/smtp4dev:3.6.1@sha256:912304153668068188d83b612fe0b7c4ec852dddb45fb2946895c7a72e89c6f2"; /** Heavy: started only by tests tagged {@code heavy-container} (task P0-6). */ public static final String MSSQL_2022 = "mcr.microsoft.com/mssql/server:2022-CU27-ubuntu-22.04@sha256:4402d880dd4c34bfa7d8705e56a86cd6c88da80a1f6bbbe741f999e76264a090"; diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/FieldTree.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/FieldTree.java index 2efd3e2061..21e80e3e31 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/FieldTree.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/FieldTree.java @@ -1,6 +1,6 @@ package org.lowcoder.sdk.contract; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import java.lang.reflect.Array; import java.lang.reflect.Field; diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JacksonAnnotationGuard.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JacksonAnnotationGuard.java index 851bdf6cae..15752db624 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JacksonAnnotationGuard.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JacksonAnnotationGuard.java @@ -11,15 +11,15 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonView; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; -import com.fasterxml.jackson.databind.cfg.MapperConfig; -import com.fasterxml.jackson.databind.introspect.AnnotatedClass; -import com.fasterxml.jackson.databind.introspect.AnnotatedMember; -import com.fasterxml.jackson.databind.introspect.AnnotatedWithParams; -import com.fasterxml.jackson.databind.introspect.AnnotationMap; -import com.fasterxml.jackson.databind.util.ClassUtil; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.annotation.JsonDeserialize; +import tools.jackson.databind.annotation.JsonPOJOBuilder; +import tools.jackson.databind.cfg.MapperConfig; +import tools.jackson.databind.introspect.AnnotatedClass; +import tools.jackson.databind.introspect.AnnotatedMember; +import tools.jackson.databind.introspect.AnnotatedWithParams; +import tools.jackson.databind.introspect.AnnotationMap; +import tools.jackson.databind.util.ClassUtil; import java.lang.annotation.Annotation; import java.lang.reflect.Field; @@ -42,7 +42,7 @@ *

It reads the annotations of a type as Jackson's own introspection sees them, through the {@link AnnotatedClass} * of the given mapper's serialization and deserialization configurations (so mix-ins and annotations inherited from * supertypes are included, and spelling, imports and fully qualified names do not matter): the class annotations, - * {@link AnnotatedMember#getAllAnnotations()} of every field, member method, static method, constructor and factory, + * {@link AnnotatedMember#annotations()} of every field, member method, static method, constructor and factory, * and the annotations of their parameters. Enum constants are read by reflection, because Jackson's * {@link AnnotatedClass} does not list static fields. * @@ -58,7 +58,7 @@ public final class JacksonAnnotationGuard { public static final Set JACKSON_ANNOTATION_PACKAGES = Set.of( - "com.fasterxml.jackson.annotation", "com.fasterxml.jackson.databind.annotation"); + "com.fasterxml.jackson.annotation", "tools.jackson.databind.annotation"); public static final Set> ALLOWED = Set.of( JsonProperty.class, JsonAlias.class, JsonIgnore.class, JsonView.class, JsonInclude.class, JsonCreator.class, JsonTypeInfo.class, JsonSubTypes.class, JsonTypeName.class, @@ -87,12 +87,11 @@ public String toString() { public static List occurrences(ObjectMapper mapper, Class type) { SortedSet seen = new TreeSet<>(); List result = new ArrayList<>(); - for (MapperConfig config : List.of(mapper.getSerializationConfig(), mapper.getDeserializationConfig())) { - AnnotatedClass annotatedClass = config.introspectClassAnnotations(config.constructType(type)).getClassInfo(); + for (MapperConfig config : List.of(mapper.serializationConfig(), mapper.deserializationConfig())) { + AnnotatedClass annotatedClass = config.classIntrospectorInstance().forOperation(config).introspectClassAnnotations(config.constructType(type)); add(type, CLASS_MEMBER, classAnnotations(config, annotatedClass), seen, result); - annotatedClass.fields().forEach(field -> add(type, field.getFullName(), annotations(field.getAllAnnotations()), seen, result)); + annotatedClass.fields().forEach(field -> add(type, field.getFullName(), field.annotations().toList(), seen, result)); annotatedClass.memberMethods().forEach(method -> addWithParameters(type, method, seen, result)); - annotatedClass.getStaticMethods().forEach(method -> addWithParameters(type, method, seen, result)); annotatedClass.getFactoryMethods().forEach(method -> addWithParameters(type, method, seen, result)); annotatedClass.getConstructors().forEach(constructor -> addWithParameters(type, constructor, seen, result)); if (annotatedClass.getDefaultConstructor() != null) { @@ -164,7 +163,7 @@ private static boolean isDefault(Annotation annotation, Method attribute) { private static void addWithParameters(Class type, AnnotatedWithParams member, SortedSet seen, List result) { String name = member.getFullName() + "(" + member.getParameterCount() + " parameter(s))"; - add(type, name, annotations(member.getAllAnnotations()), seen, result); + add(type, name, member.annotations().toList(), seen, result); for (int i = 0; i < member.getParameterCount(); i++) { add(type, name + " parameter " + i, annotations(member.getParameterAnnotations(i)), seen, result); } @@ -180,13 +179,13 @@ private static Iterable classAnnotations(MapperConfig config, Ann Set> candidates = new LinkedHashSet<>(); List> sources = new ArrayList<>(); sources.add(annotatedClass.getRawType()); - sources.addAll(ClassUtil.findSuperTypes(annotatedClass.getRawType(), null)); + sources.addAll(ClassUtil.findRawSuperTypes(annotatedClass.getRawType(), null, false)); for (Class source : sources) { addCandidates(source.getAnnotations(), candidates); Class mixIn = config.findMixInClassFor(source); if (mixIn != null) { addCandidates(mixIn.getAnnotations(), candidates); - ClassUtil.findSuperTypes(mixIn, null).forEach(mixInSuper -> addCandidates(mixInSuper.getAnnotations(), candidates)); + ClassUtil.findRawSuperTypes(mixIn, null, false).forEach(mixInSuper -> addCandidates(mixInSuper.getAnnotations(), candidates)); } } List resolved = new ArrayList<>(); @@ -209,7 +208,7 @@ private static void addCandidates(Annotation[] annotations, Set annotations(AnnotationMap map) { - return map == null ? List.of() : map.annotations(); + return map == null ? List.of() : map.values().toList(); } private static void add(Class type, String member, Iterable annotations, SortedSet seen, List result) { diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JacksonAnnotationGuardTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JacksonAnnotationGuardTest.java index a3117b4571..ccb4aee10c 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JacksonAnnotationGuardTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JacksonAnnotationGuardTest.java @@ -10,14 +10,15 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonView; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.PropertyNamingStrategies; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonNaming; -import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.std.StringDeserializer; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.PropertyNamingStrategies; +import tools.jackson.databind.annotation.JsonDeserialize; +import tools.jackson.databind.annotation.JsonNaming; +import tools.jackson.databind.annotation.JsonPOJOBuilder; +import tools.jackson.databind.annotation.JsonSerialize; +import tools.jackson.databind.deser.jdk.StringDeserializer; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.ser.std.ToStringSerializer; import org.junit.jupiter.api.Test; import org.lowcoder.sdk.util.JsonUtils; @@ -223,7 +224,9 @@ public void classAnnotationsAreFoundOnTypeSupertypeAndMixIn() { assertViolation(PRODUCTION, ClassFormatted.class, JSON_FORMAT); assertViolation(PRODUCTION, InheritsClassFormat.class, JSON_FORMAT); assertViolation(PRODUCTION, ImplementsFormatted.class, "@JsonNaming"); - ObjectMapper withMixIn = new ObjectMapper().addMixIn(Plain.class, ClassFormatMixIn.class); + ObjectMapper withMixIn = JsonMapper.builder() + .addMixIn(Plain.class, ClassFormatMixIn.class) + .build(); assertViolation(withMixIn, Plain.class, "@JsonPropertyOrder"); } @@ -234,7 +237,9 @@ public void bundleMarkerIsItselfOutsideTheAllowList() { @Test public void mixInOfTheGivenMapperIsSeen() { - ObjectMapper withMixIn = new ObjectMapper().addMixIn(Plain.class, FormatMixIn.class); + ObjectMapper withMixIn = JsonMapper.builder() + .addMixIn(Plain.class, FormatMixIn.class) + .build(); assertThat(violationsOf(PRODUCTION, Plain.class)).isEmpty(); assertViolation(withMixIn, Plain.class, JSON_FORMAT); } diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JacksonIntrospection.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JacksonIntrospection.java new file mode 100644 index 0000000000..a3333ac902 --- /dev/null +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JacksonIntrospection.java @@ -0,0 +1,68 @@ +package org.lowcoder.sdk.contract; + +import tools.jackson.databind.BeanDescription; +import tools.jackson.databind.DeserializationConfig; +import tools.jackson.databind.JavaType; +import tools.jackson.databind.SerializationConfig; +import tools.jackson.databind.introspect.AnnotatedClass; +import tools.jackson.databind.introspect.ClassIntrospector; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.jsontype.NamedType; + +import java.util.Collection; + +/** + * Jackson's own view of a type, as the contract tests read it (what a mapper would serialize or bind), in one place: + * Jackson 3 hands the introspection out through the mapper's serialization and deserialization contexts and its + * configurations, not through the mapper itself. + */ +public final class JacksonIntrospection { + + private JacksonIntrospection() { + } + + /** The class annotations of {@code type}, with mix-ins and the annotations of its supertypes, for serialization. */ + public static AnnotatedClass serializationClass(JsonMapper mapper, JavaType type) { + return mapper._serializationContext().introspectClassAnnotations(type); + } + + /** The class annotations of {@code type}, with mix-ins and the annotations of its supertypes, for deserialization. */ + public static AnnotatedClass deserializationClass(JsonMapper mapper, JavaType type) { + return mapper._deserializationContext().introspectClassAnnotations(type); + } + + /** What {@code mapper} writes of {@code type}: its serialization description. */ + public static BeanDescription serialization(JsonMapper mapper, JavaType type) { + return mapper._serializationContext().introspectBeanDescription(type); + } + + /** What {@code mapper} reads into {@code type}: its deserialization description, not following a builder. */ + public static BeanDescription deserialization(JsonMapper mapper, JavaType type) { + return mapper._deserializationContext().introspectBeanDescription(type); + } + + /** The {@code @JsonPOJOBuilder} class that {@code mapper} binds {@code type} through, or {@code null}. */ + public static Class builderOf(JsonMapper mapper, BeanDescription deserialization) { + DeserializationConfig config = mapper.deserializationConfig(); + return config.getAnnotationIntrospector().findPOJOBuilder(config, deserialization.getClassInfo()); + } + + /** The description of {@code builder}, as the builder of {@code deserialization}'s type. */ + public static BeanDescription builderDescription(JsonMapper mapper, JavaType builder, BeanDescription deserialization) { + DeserializationConfig config = mapper.deserializationConfig(); + ClassIntrospector introspector = config.classIntrospectorInstance().forOperation(config); + return introspector.introspectForDeserializationWithBuilder(builder, deserialization); + } + + /** The registered subtypes of {@code type} with the class they stand for, as the serializer resolves them. */ + public static Collection subtypesByClass(JsonMapper mapper, AnnotatedClass type) { + SerializationConfig config = mapper.serializationConfig(); + return config.getSubtypeResolver().collectAndResolveSubtypesByClass(config, type); + } + + /** The registered subtypes of {@code type} with the type id they are read by, as the deserializer resolves them. */ + public static Collection subtypesByTypeId(JsonMapper mapper, AnnotatedClass type) { + DeserializationConfig config = mapper.deserializationConfig(); + return config.getSubtypeResolver().collectAndResolveSubtypesByTypeId(config, type); + } +} diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JavaValueWalker.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JavaValueWalker.java index 8514d35fdc..54ca628a85 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JavaValueWalker.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/JavaValueWalker.java @@ -1,6 +1,6 @@ package org.lowcoder.sdk.contract; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.Iterator; @@ -53,7 +53,7 @@ public static void walk(String pointer, Object value, Map classe } } else if (value instanceof JsonNode node && node.isObject()) { List keys = new ArrayList<>(); - for (Iterator> fields = node.fields(); fields.hasNext(); ) { + for (Iterator> fields = node.properties().iterator(); fields.hasNext(); ) { Map.Entry field = fields.next(); keys.add(field.getKey()); walk(pointer + "/" + escape(field.getKey()), field.getValue(), classes, keyOrder); diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/PayloadBoundsTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/PayloadBoundsTest.java index 2bf7e9d2fc..ede5eed5f5 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/PayloadBoundsTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/PayloadBoundsTest.java @@ -1,9 +1,9 @@ package org.lowcoder.sdk.contract; -import com.fasterxml.jackson.core.StreamReadConstraints; -import com.fasterxml.jackson.core.exc.StreamConstraintsException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.core.StreamReadConstraints; +import tools.jackson.core.exc.StreamConstraintsException; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.lowcoder.sdk.util.JsonUtils; @@ -21,16 +21,17 @@ /** * The read limits of the production mapper (docs/API_PAYLOAD_TEST_PLAN.md §4.8, R11, E3), on a DSL - * {@code Map}: {@code JsonUtils} sets no {@code StreamReadConstraints}, so the Jackson defaults apply and - * can change with an upgrade. Each limit is read at its value and one past it: nesting depth 1000, a number of 1000 - * digits, a string of 20,000,000 characters. The configured values are asserted too, so a changed default is named - * even where the behaviour still happens to pass. + * {@code Map}: {@code JsonUtils} sets the nesting depth and the string length of its + * {@code StreamReadConstraints} to the Jackson 2 values, because the Jackson 3 defaults differ (nesting depth 500, and a + * larger string length); the number length is left at the default, which is the same. Each limit is read at its value + * and one past it: nesting depth 1000, a number of 1000 digits, a string of 20,000,000 characters. The configured + * values are asserted too, so a changed default or a dropped setting is named even where the behaviour still happens + * to pass. * *

Inputs are generated as streams ({@link #repeated}), never held as text; the largest test holds the parsed * 20,000,000-character string and Jackson's buffer for it. These tests run in every build (owner decision C10-A6). - * Limits: the codec's 20 MB {@code maxInMemorySize} is the server module's {@code PayloadBoundsTest}; the other - * Jackson 2.15 has only these three read constraints; the document- and name-length limits of later versions are not - * seen here until an upgrade adds them to {@code StreamReadConstraints}. + * Limits: the codec's 20 MB {@code maxInMemorySize} is the server module's {@code PayloadBoundsTest}; the + * document-, name- and token-count limits of the Jackson defaults are not asserted here. */ public class PayloadBoundsTest { @@ -46,8 +47,8 @@ public class PayloadBoundsTest { private static final ObjectMapper MAPPER = JsonUtils.getObjectMapper(); @Test - public void theMapperUsesTheJacksonDefaultLimits() { - StreamReadConstraints constraints = MAPPER.getFactory().streamReadConstraints(); + public void theMapperHasTheConfiguredLimits() { + StreamReadConstraints constraints = MAPPER.tokenStreamFactory().streamReadConstraints(); System.out.println("[PayloadBoundsTest] read constraints: nesting " + constraints.getMaxNestingDepth() + ", number " + constraints.getMaxNumberLength() + ", string " + constraints.getMaxStringLength()); assertEquals(MAX_NESTING_DEPTH, constraints.getMaxNestingDepth()); diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/PluginConfigPolymorphismTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/PluginConfigPolymorphismTest.java index 54a52a4d28..fad9f4a23f 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/PluginConfigPolymorphismTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/PluginConfigPolymorphismTest.java @@ -1,15 +1,18 @@ package org.lowcoder.sdk.contract; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.introspect.AnnotatedClass; -import com.fasterxml.jackson.databind.jsontype.NamedType; +import tools.jackson.databind.DeserializationConfig; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.ObjectWriter; +import tools.jackson.databind.introspect.AnnotatedClass; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.jsontype.NamedType; import org.junit.jupiter.api.Test; import org.lowcoder.sdk.config.JsonViews; import org.lowcoder.sdk.plugin.common.ssl.SslConfig; import org.lowcoder.sdk.plugin.restapi.auth.AuthConfig; import org.lowcoder.sdk.util.JsonUtils; +import tools.jackson.core.JacksonException; import java.io.IOException; import java.util.ArrayList; @@ -53,7 +56,7 @@ public class PluginConfigPolymorphismTest { static final String FAILS_WITH = "failsWith "; private static final ObjectMapper MAPPER = JsonUtils.getObjectMapper(); - private static final ObjectMapper BARE = new ObjectMapper(); + private static final ObjectMapper BARE = JsonMapper.builderWithJackson2Defaults().build(); private static final GoldenJson GOLDEN = GoldenJson.forModule(); @Test @@ -70,9 +73,10 @@ public void sslConfigCasesAsPinned() throws IOException { public void registeredIdsAsPinned() throws IOException { Map> ids = new TreeMap<>(); for (Class base : List.of(AuthConfig.class, SslConfig.class)) { - AnnotatedClass annotated = MAPPER.getDeserializationConfig().introspectClassAnnotations(base).getClassInfo(); + DeserializationConfig config = MAPPER.deserializationConfig(); + AnnotatedClass annotated = config.classIntrospectorInstance().forOperation(config).introspectClassAnnotations(config.constructType(base)); Map byId = new TreeMap<>(); - for (NamedType subtype : MAPPER.getSubtypeResolver().collectAndResolveSubtypesByTypeId(MAPPER.getDeserializationConfig(), annotated)) { + for (NamedType subtype : config.getSubtypeResolver().collectAndResolveSubtypesByTypeId(config, annotated)) { if (subtype.hasName()) { byId.put(subtype.getName(), subtype.getType().getName()); } @@ -90,7 +94,7 @@ public void registeredIdsAsPinned() throws IOException { private static void assertCases(Class base) throws IOException { JsonNode inputs = BARE.readTree(GOLDEN.read(DIRECTORY + base.getSimpleName() + INPUTS_SUFFIX)); List cases = new ArrayList<>(); - Iterator> entries = inputs.fields(); + Iterator> entries = inputs.properties().iterator(); while (entries.hasNext()) { Map.Entry entry = entries.next(); String input = entry.getValue().toString(); @@ -98,7 +102,7 @@ private static void assertCases(Class base) throws IOException { Object bound; try { bound = MAPPER.readValue(input, base); - } catch (IOException e) { + } catch (JacksonException e) { outcome.append(',').append(quote(CLASS)).append(':').append(quote(FAILS_WITH + e.getClass().getName())).append('}'); cases.add(quote(entry.getKey()) + ":" + outcome); System.out.println("[PluginConfigPolymorphismTest] " + base.getSimpleName() + " " + entry.getKey() + ": " + outcome); @@ -125,7 +129,7 @@ private static String readBack(ObjectWriter writer, String output, Class base try { Object again = MAPPER.readValue(output, base); return "{" + quote(CLASS) + ":" + quote(again.getClass().getName()) + "," + quote(NO_VIEW) + ":" + writer.writeValueAsString(again) + "}"; - } catch (IOException e) { + } catch (JacksonException e) { return quote(FAILS_WITH + e.getClass().getName()); } } @@ -133,7 +137,7 @@ private static String readBack(ObjectWriter writer, String output, Class base private static String boundClass(ObjectMapper mapper, String input, Class base) { try { return mapper.readValue(input, base).getClass().getName(); - } catch (IOException e) { + } catch (JacksonException e) { return FAILS_WITH + e.getClass().getName(); } } @@ -141,7 +145,7 @@ private static String boundClass(ObjectMapper mapper, String input, Class bas private static String quote(String text) { try { return BARE.writeValueAsString(text); - } catch (IOException e) { + } catch (JacksonException e) { throw new IllegalStateException(e); } } diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/QueryResults.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/QueryResults.java index e6e28409ca..99a6414807 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/QueryResults.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/QueryResults.java @@ -1,8 +1,7 @@ package org.lowcoder.sdk.contract; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.fasterxml.jackson.databind.util.RawValue; +import tools.jackson.databind.node.ObjectNode; +import tools.jackson.databind.util.RawValue; import org.lowcoder.sdk.models.QueryExecutionResult; import org.lowcoder.sdk.util.JsonUtils; @@ -71,7 +70,7 @@ public static Map report(QueryExecutionResult result) { public static Object written(Object value) { try { return new RawValue(JsonUtils.getObjectMapper().writeValueAsString(value)); - } catch (JsonProcessingException | RuntimeException e) { + } catch (RuntimeException e) { return Map.of(ERROR_KEY, ConfigBinding.errorText(e)); } } diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/RecordingHttpServer.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/RecordingHttpServer.java index a84a2afdd3..c1913926ee 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/RecordingHttpServer.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/RecordingHttpServer.java @@ -1,8 +1,12 @@ package org.lowcoder.sdk.contract; -import com.fasterxml.jackson.databind.util.RawValue; +import tools.jackson.databind.util.RawValue; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; + +import javax.net.ssl.SSLContext; import java.io.IOException; import java.io.UncheckedIOException; @@ -21,6 +25,9 @@ * same technique as the {@code npm-outbound} tests of §4.9). The answer to a path is either fixed ({@link #start}) or * computed from the request ({@link #serve}), e.g. an echo of what the client sent. * + *

{@link #startSecure} and {@link #serveSecure} start the same server over TLS with the server certificate of the given + * {@link SSLContext} ({@code https://127.0.0.1:}); {@link SelfSignedCertificate} generates one in the test. + * *

Limits: it binds {@code 127.0.0.1} on a free port; the JDK server adds a {@code Date} header to every answer (the * tests drop it as volatile) and writes header values one byte per character, so a header value is sent as the * ISO-8859-1 bytes of its characters. A path without a response answers 404 with an empty body. @@ -76,10 +83,20 @@ public Map jsonBodyReport() { } private final HttpServer server; + private final String scheme; private final List requests = Collections.synchronizedList(new ArrayList<>()); - private RecordingHttpServer(Map handlers) throws IOException { - server = HttpServer.create(new InetSocketAddress(InetAddress.getByName(LOOPBACK), ANY_PORT), BACKLOG); + private RecordingHttpServer(Map handlers, SSLContext tls) throws IOException { + InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(LOOPBACK), ANY_PORT); + if (tls == null) { + server = HttpServer.create(address, BACKLOG); + scheme = "http"; + } else { + HttpsServer secure = HttpsServer.create(address, BACKLOG); + secure.setHttpsConfigurator(new HttpsConfigurator(tls)); + server = secure; + scheme = "https"; + } server.createContext("/", exchange -> answer(exchange, handlers)); server.start(); } @@ -93,16 +110,32 @@ public static RecordingHttpServer start(Map responses) { /** Starts a server answering each request with the handler of its exact path (without query). */ public static RecordingHttpServer serve(Map handlers) { + return serve(handlers, null); + } + + /** Starts a TLS server, with the certificate of {@code tls}, answering {@code responses} by exact path (without query). */ + public static RecordingHttpServer startSecure(SSLContext tls, Map responses) { + Map handlers = new LinkedHashMap<>(); + responses.forEach((path, response) -> handlers.put(path, request -> response)); + return serveSecure(tls, handlers); + } + + /** Starts a TLS server, with the certificate of {@code tls}, answering each request with the handler of its exact path (without query). */ + public static RecordingHttpServer serveSecure(SSLContext tls, Map handlers) { + return serve(handlers, tls); + } + + private static RecordingHttpServer serve(Map handlers, SSLContext tls) { try { - return new RecordingHttpServer(handlers); + return new RecordingHttpServer(handlers, tls); } catch (IOException e) { throw new UncheckedIOException("cannot start the local HTTP server", e); } } - /** {@code http://127.0.0.1:}. */ + /** {@code http://127.0.0.1:}, or {@code https://...} for a TLS server. */ public String baseUrl() { - return "http://" + LOOPBACK + ":" + server.getAddress().getPort(); + return scheme + "://" + LOOPBACK + ":" + server.getAddress().getPort(); } public int port() { diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/RecordingHttpServerSecureTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/RecordingHttpServerSecureTest.java new file mode 100644 index 0000000000..8c7632bc39 --- /dev/null +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/RecordingHttpServerSecureTest.java @@ -0,0 +1,117 @@ +package org.lowcoder.sdk.contract; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.lowcoder.sdk.contract.RecordingHttpServer.Response; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.TrustManagerFactory; +import java.io.ByteArrayInputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The TLS variant of {@link RecordingHttpServer} with a certificate of {@link SelfSignedCertificate}: a client that trusts + * only that certificate reads the answer and the server records the request; a client with the JDK's default trust refuses + * the handshake, so the server never sees a request. The test is the proof that the variant really serves TLS and that the + * generated certificate is the one the server presents. + */ +public class RecordingHttpServerSecureTest { + + static final String TAG = "[RecordingHttpServerSecureTest] "; + static final String PATH = "/secure"; + static final String ANSWER = "over tls"; + static final String HTTPS_PREFIX = "https://127.0.0.1:"; + static final Duration TIMEOUT = Duration.ofSeconds(20); + static final int OK = 200; + + @TempDir + static Path directory; + private static SelfSignedCertificate certificate; + + @BeforeAll + static void generate() { + certificate = SelfSignedCertificate.generate(directory, "recording"); + System.out.println(TAG + "certificate PEM starts with " + certificate.pem().lines().findFirst().orElse("")); + } + + private static Map answers() { + return Map.of(PATH, new Response(OK, Map.of(), ANSWER.getBytes(StandardCharsets.UTF_8))); + } + + private static SSLContext trusting(String pem) throws Exception { + X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509") + .generateCertificate(new ByteArrayInputStream(pem.getBytes(StandardCharsets.UTF_8))); + KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType()); + trust.load(null, null); + trust.setCertificateEntry("server", cert); + TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init(trust); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, factory.getTrustManagers(), null); + return context; + } + + private static HttpResponse get(HttpClient client, String url) throws Exception { + return client.send(HttpRequest.newBuilder(URI.create(url + PATH)).timeout(TIMEOUT).GET().build(), + HttpResponse.BodyHandlers.ofString()); + } + + @Test + public void aClientTrustingTheGeneratedCertificateReadsTheAnswerAndTheRequestIsRecorded() throws Exception { + try (RecordingHttpServer server = RecordingHttpServer.startSecure(certificate.serverContext(), answers())) { + assertTrue(server.baseUrl().startsWith(HTTPS_PREFIX), server.baseUrl()); + HttpClient client = HttpClient.newBuilder().sslContext(trusting(certificate.pem())).build(); + HttpResponse response = get(client, server.baseUrl()); + System.out.println(TAG + server.baseUrl() + PATH + " -> " + response.statusCode() + " " + response.body()); + assertEquals(OK, response.statusCode()); + assertEquals(ANSWER, response.body()); + List requests = server.requests(); + assertEquals(1, requests.size(), "the server recorded exactly the one request: " + requests); + assertEquals(PATH, requests.get(0).pathAndQuery()); + } + } + + @Test + public void aClientWithTheDefaultTrustRefusesTheSelfSignedHandshakeSoNoRequestIsRecorded() throws Exception { + try (RecordingHttpServer server = RecordingHttpServer.startSecure(certificate.serverContext(), answers())) { + HttpClient client = HttpClient.newHttpClient(); + Exception failure = assertThrows(Exception.class, () -> get(client, server.baseUrl())); + System.out.println(TAG + "default trust -> " + failure); + assertInstanceOf(SSLException.class, failure.getCause() == null ? failure : failure.getCause(), failure.toString()); + assertEquals(0, server.requests().size(), "a refused handshake reaches no handler: " + server.requests()); + } + } + + @Test + public void aCertificateOfAnotherGenerationIsNotTheOneTheServerPresents() throws Exception { + SelfSignedCertificate other = SelfSignedCertificate.generate(directory, "other"); + assertNotNull(other.pem()); + assertNotEquals(certificate.pem(), other.pem(), "two generations give two certificates"); + try (RecordingHttpServer server = RecordingHttpServer.startSecure(certificate.serverContext(), answers())) { + HttpClient client = HttpClient.newBuilder().sslContext(trusting(other.pem())).build(); + Exception failure = assertThrows(Exception.class, () -> get(client, server.baseUrl())); + System.out.println(TAG + "trusting the other certificate -> " + failure); + assertEquals(0, server.requests().size(), "no request passed a handshake against an untrusted certificate"); + } + } +} diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/RepresentativeInput.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/RepresentativeInput.java index 230a264fc5..a64d6aaea2 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/RepresentativeInput.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/RepresentativeInput.java @@ -1,8 +1,9 @@ package org.lowcoder.sdk.contract; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.JsonNode; import org.lowcoder.sdk.util.JsonUtils; +import tools.jackson.core.JacksonException; import java.io.IOException; import java.io.InputStream; @@ -35,8 +36,8 @@ public static Map map() { try { return JsonUtils.getObjectMapper().readValue(TEXT, new TypeReference>() { }); - } catch (IOException e) { - throw new UncheckedIOException("cannot read " + RESOURCE, e); + } catch (JacksonException e) { + throw new IllegalStateException("cannot read " + RESOURCE, e); } } @@ -44,8 +45,8 @@ public static Map map() { public static JsonNode node() { try { return JsonUtils.getObjectMapper().readTree(TEXT); - } catch (IOException e) { - throw new UncheckedIOException("cannot read " + RESOURCE, e); + } catch (JacksonException e) { + throw new IllegalStateException("cannot read " + RESOURCE, e); } } diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/SelfSignedCertificate.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/SelfSignedCertificate.java new file mode 100644 index 0000000000..1df6518c28 --- /dev/null +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/contract/SelfSignedCertificate.java @@ -0,0 +1,95 @@ +package org.lowcoder.sdk.contract; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.util.concurrent.TimeUnit; + +/** + * A self-signed server certificate generated in the test with the JDK's {@code keytool} (the technique of + * {@code WebClientBuildHelperTest}): a PKCS12 key store in the given directory, the certificate as PEM (what a datasource's + * "verify self-signed certificate" setting holds) and an {@link SSLContext} that serves it, for + * {@link RecordingHttpServer#startSecure}. The certificate names {@code CN=localhost} with the subject alternative names + * {@code 127.0.0.1} and {@code localhost}. Nothing is copied anywhere: the key store stays in the test's own directory. + */ +public final class SelfSignedCertificate { + + private static final String STORE_PASSWORD = "changeit"; + private static final String ALIAS = "test"; + private static final String STORE_TYPE = "PKCS12"; + private static final int KEY_SIZE = 2048; + private static final int VALIDITY_DAYS = 1; + private static final String SUBJECT = "CN=localhost"; + private static final String SUBJECT_ALTERNATIVE_NAMES = "san=ip:127.0.0.1,dns:localhost"; + private static final long KEYTOOL_TIMEOUT_SECONDS = 60; + private static final String TLS = "TLS"; + + private final Path keyStore; + private final String pem; + + private SelfSignedCertificate(Path keyStore, String pem) { + this.keyStore = keyStore; + this.pem = pem; + } + + /** Generates a certificate whose key store is {@code directory/.p12}. */ + public static SelfSignedCertificate generate(Path directory, String name) { + Path store = directory.resolve(name + ".p12"); + String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString(); + run(keytool, "-genkeypair", "-alias", ALIAS, "-keyalg", "RSA", "-keysize", String.valueOf(KEY_SIZE), "-dname", SUBJECT, + "-ext", SUBJECT_ALTERNATIVE_NAMES, "-validity", String.valueOf(VALIDITY_DAYS), "-storetype", STORE_TYPE, + "-keystore", store.toString(), "-storepass", STORE_PASSWORD, "-keypass", STORE_PASSWORD); + String pem = run(keytool, "-exportcert", "-alias", ALIAS, "-rfc", "-keystore", store.toString(), "-storepass", STORE_PASSWORD); + return new SelfSignedCertificate(store, pem); + } + + /** The certificate in PEM form ({@code -----BEGIN CERTIFICATE-----}...). */ + public String pem() { + return pem; + } + + /** An SSL context whose server identity is this certificate. */ + public SSLContext serverContext() { + try { + KeyStore keys = KeyStore.getInstance(STORE_TYPE); + try (InputStream in = Files.newInputStream(keyStore)) { + keys.load(in, STORE_PASSWORD.toCharArray()); + } + KeyManagerFactory keyManagers = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagers.init(keys, STORE_PASSWORD.toCharArray()); + SSLContext context = SSLContext.getInstance(TLS); + context.init(keyManagers.getKeyManagers(), null, null); + return context; + } catch (IOException e) { + throw new UncheckedIOException("cannot read the key store " + keyStore, e); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("cannot build the SSL context of " + keyStore, e); + } + } + + private static String run(String... command) { + try { + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (InputStream in = process.getInputStream()) { + output = new String(in.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(KEYTOOL_TIMEOUT_SECONDS, TimeUnit.SECONDS) || process.exitValue() != 0) { + throw new IllegalStateException(String.join(" ", command) + " failed:\n" + output); + } + return output; + } catch (IOException e) { + throw new UncheckedIOException("cannot run " + command[0], e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while running " + command[0], e); + } + } +} diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/models/QueryExecutionResultHttpCodeTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/models/QueryExecutionResultHttpCodeTest.java new file mode 100644 index 0000000000..eb3596aa62 --- /dev/null +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/models/QueryExecutionResultHttpCodeTest.java @@ -0,0 +1,41 @@ +package org.lowcoder.sdk.models; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +/** + * The {@code queryCode} of a REST API result is {@code "HTTP"} plus the name of the response's status, and apps compare it. + * Spring 7 renamed the constants of three status codes; the code stays what it was. + */ +class QueryExecutionResultHttpCodeTest { + + private static String queryCodeOf(HttpStatus status) { + QueryExecutionResult result = QueryExecutionResult.ofRestApiResult(status, null, null); + System.out.println("[QueryExecutionResultHttpCodeTest] " + status.value() + " " + status.name() + " -> " + result.getQueryCode()); + return result.getQueryCode(); + } + + /** Catches the renamed constants leaking into the code: 413, 421 and 422 keep their earlier names. */ + @Test + void renamedStatusesKeepTheirEarlierCodes() { + assertThat(queryCodeOf(HttpStatus.resolve(413))).as("413 as resolved by HttpStatus").isEqualTo("HTTPPAYLOAD_TOO_LARGE"); + assertThat(queryCodeOf(HttpStatus.resolve(421))).as("421 as resolved by HttpStatus").isEqualTo("HTTPDESTINATION_LOCKED"); + assertThat(queryCodeOf(HttpStatus.resolve(422))).as("422 as resolved by HttpStatus").isEqualTo("HTTPUNPROCESSABLE_ENTITY"); + } + + /** Catches the mapping touching statuses whose names did not change. */ + @Test + void otherStatusesUseTheirConstantName() { + assertThat(queryCodeOf(HttpStatus.NOT_FOUND)).as("404").isEqualTo("HTTPNOT_FOUND"); + assertThat(queryCodeOf(HttpStatus.INTERNAL_SERVER_ERROR)).as("500").isEqualTo("HTTPINTERNAL_SERVER_ERROR"); + assertThat(queryCodeOf(HttpStatus.URI_TOO_LONG)).as("414").isEqualTo("HTTPURI_TOO_LONG"); + } + + /** Catches a success status carrying a code: the code stays OK. */ + @Test + void successStatusKeepsTheOkCode() { + assertThat(queryCodeOf(HttpStatus.OK)).as("200").isEqualTo("OK"); + } +} diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/common/sql/ResultSetParserContractTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/common/sql/ResultSetParserContractTest.java index c7f3702a65..1b3da56e03 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/common/sql/ResultSetParserContractTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/common/sql/ResultSetParserContractTest.java @@ -70,6 +70,9 @@ public class ResultSetParserContractTest { static final Instant INSTANT = Instant.parse("2024-02-29T13:14:15.123Z"); static final byte[] BYTES = {0, 1, (byte) 0xFF, 'a'}; static final String TEXT = "žluťoučký kůň 🐎"; + /** The JDK's own message of {@code SerialClob.getAsciiStream}: JDK 17 spells it with the typo, JDK 25 without it. */ + static final String CLOB_MESSAGE_FIXED_BY_NEWER_JDK = "SerialClob cannot return the CLOB value"; + static final String CLOB_MESSAGE_PINNED = "SerialClob cannot return a the CLOB value"; private static final GoldenJson GOLDEN = GoldenJson.forModule(); private static TimeZone defaultZone; @@ -104,7 +107,8 @@ public void leafValuesAsPinned() throws SQLException { Map report = new LinkedHashMap<>(); report.put(COLUMNS_KEY, perColumn); report.put(ROW_KEY, QueryResults.report(QueryExecutionResult.success(rows))); - String actual = ConfigBinding.write(report); + String actual = ConfigBinding.write(report) + .replace(CLOB_MESSAGE_FIXED_BY_NEWER_JDK, CLOB_MESSAGE_PINNED); System.out.println("[ResultSetParserContractTest] " + rows.size() + " row, " + perColumn.size() + " columns\n" + actual); GOLDEN.assertJson(REPORT, actual); } diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/sheet/SheetChangeSetTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/sheet/SheetChangeSetTest.java index 53512f2fd2..a6a4273246 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/sheet/SheetChangeSetTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/sheet/SheetChangeSetTest.java @@ -8,8 +8,10 @@ import static org.lowcoder.sdk.plugin.common.constant.Constants.COMP_TYPE_KEY; import static org.lowcoder.sdk.plugin.common.constant.Constants.RECORD_FORM_KEY; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -32,6 +34,7 @@ import org.lowcoder.sdk.plugin.sheet.changeset.SheetKeyValuePairChangeSet; import org.lowcoder.sdk.plugin.sheet.changeset.SheetObjectChangeSet; import org.lowcoder.sdk.plugin.sqlcommand.changeset.KeyValuePairChangeSet; +import tools.jackson.core.JacksonException; /** * Parsing and rendering of the change sets of the sheet (Google Sheets) GUI commands: the twins of the @@ -46,7 +49,7 @@ class SheetChangeSetTest { private static final String PAIR_COLUMN = "a"; private static final String PAIR_VALUE = "1"; - private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final ObjectMapper MAPPER = JsonMapper.builderWithJackson2Defaults().build(); private static final String BLANK_EMPTY = ""; private static final String BLANK_SPACE = " "; private static final String BLANK_TAB_SPACE = "\t "; @@ -92,7 +95,7 @@ private static Map pair(Object column, Object value) { private static JsonNode json(String text) { try { return MAPPER.readTree(text); - } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + } catch (JacksonException e) { throw new IllegalArgumentException(text, e); } } diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetParseTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetParseTest.java index e39ef804ad..ee18b009e0 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetParseTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/plugin/sqlcommand/changeset/ChangeSetParseTest.java @@ -9,8 +9,10 @@ import static org.lowcoder.sdk.plugin.common.constant.Constants.PRIMARY_KEY_FORM_KEY; import static org.lowcoder.sdk.plugin.common.constant.Constants.RECORD_FORM_KEY; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -26,6 +28,7 @@ import org.junit.jupiter.params.provider.MethodSource; import org.lowcoder.sdk.exception.PluginCommonError; import org.lowcoder.sdk.exception.PluginException; +import tools.jackson.core.JacksonException; /** * Parsing and rendering of the change sets behind the GUI insert/update/upsert commands. The non-list {@code comp} @@ -39,7 +42,7 @@ class ChangeSetParseTest { private static final String PAIR_COLUMN = "a"; private static final int PAIR_VALUE = 1; - private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final ObjectMapper MAPPER = JsonMapper.builderWithJackson2Defaults().build(); private static void assertPluginError(Runnable action, String messageKey, Object... args) { assertThatThrownBy(action::run).isInstanceOfSatisfying(PluginException.class, e -> { @@ -211,7 +214,7 @@ void parseBulkRecordsAndPrimaryKeyRequireStrings() { private static JsonNode json(String text) { try { return MAPPER.readTree(text); - } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + } catch (JacksonException e) { throw new IllegalArgumentException(text, e); } } diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/HttpHeaderMapsTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/HttpHeaderMapsTest.java new file mode 100644 index 0000000000..f5381b0da6 --- /dev/null +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/HttpHeaderMapsTest.java @@ -0,0 +1,63 @@ +package org.lowcoder.sdk.util; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +/** What {@link HttpHeaderMaps#copyOf} keeps of {@link HttpHeaders}: names without regard to case, order, values and their JSON form. */ +class HttpHeaderMapsTest { + + private static HttpHeaders headers() { + HttpHeaders headers = new HttpHeaders(); + headers.add("Content-Type", "application/json"); + headers.add("X-Multi", "first"); + headers.add("X-Multi", "second, with comma"); + headers.add("Cookie", "session=1"); + return headers; + } + + /** Catches a copy that loses a value, a name's order or a name's case. */ + @Test + void theCopyHoldsEveryValueInOrder() { + MultiValueMap copy = HttpHeaderMaps.copyOf(headers()); + + System.out.println("[HttpHeaderMapsTest] copy " + copy); + assertThat(copy.keySet()).as("names in the order of the headers, in their first spelling") + .containsExactly("Content-Type", "X-Multi", "Cookie"); + assertThat(copy.get("X-Multi")).as("values of a repeated header").containsExactly("first", "second, with comma"); + } + + /** Catches a case-sensitive copy: removing a header by another spelling must work, as it does on HttpHeaders. */ + @Test + void namesAreComparedWithoutRegardToCase() { + MultiValueMap copy = HttpHeaderMaps.copyOf(headers()); + + assertThat(copy.remove("cookie")).as("removed by a lower-case spelling").containsExactly("session=1"); + copy.addIfAbsent("X-MULTI", "third"); + assertThat(copy.get("x-multi")).as("addIfAbsent did not add to the existing header").containsExactly("first", "second, with comma"); + assertThat(copy).as("the copy without the cookie").doesNotContainKey("Cookie"); + } + + /** Catches a view instead of a copy: the headers must not change when the copy does. */ + @Test + void theCopyIsIndependentOfTheHeaders() { + HttpHeaders original = headers(); + + HttpHeaderMaps.copyOf(original).remove("Cookie"); + HttpHeaderMaps.copyOf(original).add("X-Added", "1"); + + assertThat(original.containsHeader("Cookie")).as("original still has the cookie").isTrue(); + assertThat(original.containsHeader("X-Added")).as("original has no added header").isFalse(); + } + + /** Catches a copy that is not written as a JSON object of arrays, the form the results hold the response headers in. */ + @Test + void theCopyIsWrittenAsAnObjectOfArrays() { + String json = JsonUtils.toJson(HttpHeaderMaps.copyOf(headers())); + + System.out.println("[HttpHeaderMapsTest] json " + json); + assertThat(json).isEqualTo("{\"Content-Type\":[\"application/json\"],\"X-Multi\":[\"first\",\"second, with comma\"],\"Cookie\":[\"session=1\"]}"); + } +} diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/LegacyBeanNamingTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/LegacyBeanNamingTest.java new file mode 100644 index 0000000000..7622bbb290 --- /dev/null +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/LegacyBeanNamingTest.java @@ -0,0 +1,79 @@ +package org.lowcoder.sdk.util; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import tools.jackson.databind.json.JsonMapper; + +/** + * {@link LegacyBeanNaming}: accessor names with a leading run of upper-case letters get the Jackson 2 property name. + */ +class LegacyBeanNamingTest { + + @ParameterizedTest(name = "[{index}] ''{0}'' -> ''{1}''") + @CsvSource({ + "SQLTypeName, sqltypeName", + "URL, url", + "URLPath, urlpath", + "Name, name", + "A, a", + "name, name", + "sqlType, sqlType"}) + void lowerCaseLeadingRunGivesTheJackson2Name(String implicitName, String expected) { + String actual = LegacyBeanNaming.lowerCaseLeadingRun(implicitName); + + System.out.println("[LegacyBeanNamingTest] " + implicitName + " -> " + actual); + assertThat(actual).isEqualTo(expected); + } + + @Test + void lowerCaseLeadingRunKeepsAnEmptyName() { + assertThat(LegacyBeanNaming.lowerCaseLeadingRun("")).isEmpty(); + } + + @Test + void aMapperWithTheStrategyWritesAndReadsTheJackson2Names() throws Exception { + JsonMapper mapper = JsonMapper.builder().propertyNamingStrategy(new LegacyBeanNaming()).build(); + + String json = mapper.writeValueAsString(new Bean("t", "u")); + System.out.println("[LegacyBeanNamingTest] written: " + json); + assertThat(json).contains("\"sqltypeName\":\"t\"").contains("\"url\":\"u\""); + + Bean read = mapper.readValue("{\"sqltypeName\":\"a\",\"url\":\"b\"}", Bean.class); + assertThat(read.getSQLTypeName()).isEqualTo("a"); + assertThat(read.getURL()).isEqualTo("b"); + } + + /** The accessors whose Jackson 3 default names ({@code SQLTypeName}, {@code URL}) differ from Jackson 2's. */ + public static class Bean { + private String sqlTypeName; + private String url; + + public Bean() { + } + + Bean(String sqlTypeName, String url) { + this.sqlTypeName = sqlTypeName; + this.url = url; + } + + public String getSQLTypeName() { + return sqlTypeName; + } + + public void setSQLTypeName(String value) { + this.sqlTypeName = value; + } + + public String getURL() { + return url; + } + + public void setURL(String value) { + this.url = value; + } + } +} diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/MustacheHelperEdgeCasesTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/MustacheHelperEdgeCasesTest.java index 1b897fbc57..f1606b183b 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/MustacheHelperEdgeCasesTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/MustacheHelperEdgeCasesTest.java @@ -3,7 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; @@ -220,11 +220,11 @@ void jsonRenderingResolvesStringsKeysAndSingleTokens() { assertThat(renderJson("{\"{{k}}\": 1}", params).toString()).as("an object key is resolved too").isEqualTo("{\"key\":1}"); assertThat(renderJson("{\"a\": \" \"}", params).toString()).as("a blank string value becomes empty").isEqualTo("{\"a\":\"\"}"); assertThat(renderJson("{\"a\": {{nul}}}", params).toString()).isEqualTo("{\"a\":null}"); - assertThat(renderJson("{{ x }}", params).textValue()).isEqualTo("X"); - assertThat(renderJson("{{e}}", params).textValue()).isEmpty(); + assertThat(renderJson("{{ x }}", params).stringValue()).isEqualTo("X"); + assertThat(renderJson("{{e}}", params).stringValue()).isEmpty(); assertThat(renderJson("{{nul}}", params).isNull()).isTrue(); assertThat(renderJson("{{missing}}", params).isNull()).isTrue(); - assertThat(renderJson("plain text", params).textValue()).isEqualTo("plain text"); + assertThat(renderJson("plain text", params).stringValue()).isEqualTo("plain text"); } @Test diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/NodeConversionContractTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/NodeConversionContractTest.java index 59ed6acdbe..584ef887ad 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/NodeConversionContractTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/NodeConversionContractTest.java @@ -1,6 +1,6 @@ package org.lowcoder.sdk.util; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import org.junit.jupiter.api.Test; import org.lowcoder.sdk.contract.BoundarySites; import org.lowcoder.sdk.contract.ConfigBinding; diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/TreeTextContractTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/TreeTextContractTest.java index 3d8d86f83f..88623872fc 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/TreeTextContractTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/util/TreeTextContractTest.java @@ -1,8 +1,7 @@ package org.lowcoder.sdk.util; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import com.fasterxml.jackson.databind.node.ObjectNode; +import tools.jackson.databind.node.JsonNodeFactory; +import tools.jackson.databind.node.ObjectNode; import org.junit.jupiter.api.Test; import org.lowcoder.sdk.contract.BoundarySites; import org.lowcoder.sdk.contract.ConfigBinding; @@ -80,7 +79,7 @@ public void rawHttpRequestBody() { * as embedded error text, since its mapper registers no modules; the production mapper writes it as a number. */ @Test - public void toStringIsNotTheProductionMapper() throws JsonProcessingException { + public void toStringIsNotTheProductionMapper() { ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put(DECIMAL_KEY, new BigDecimal(DECIMAL_TEXT)); node.putPOJO(INSTANT_KEY, Instant.EPOCH); diff --git a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/webclient/WebClientRedirectsTest.java b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/webclient/WebClientRedirectsTest.java index ef0a9ca0ef..2285e29031 100644 --- a/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/webclient/WebClientRedirectsTest.java +++ b/server/api-service/lowcoder-sdk/src/test/java/org/lowcoder/sdk/webclient/WebClientRedirectsTest.java @@ -92,7 +92,7 @@ void forAnotherOriginKeepsOnlyTheContentHeadersAndDropsEveryOtherDefaultHeaderAn assertThat(original.headers().get(HttpHeaders.AUTHORIZATION)).containsExactly("Basic dXNlcjpzZWNyZXQ="); assertThat(original.headers().get("X-Api-Key")).containsExactly("key"); assertThat(original.cookies().get("a")).containsExactly("1"); - assertThat(other.headers().keySet().stream().map(name -> name.toLowerCase(Locale.ROOT))) + assertThat(other.headers().headerNames().stream().map(name -> name.toLowerCase(Locale.ROOT))) .as("header names are compared without case").containsExactlyInAnyOrder("accept", "accept-language", "content-type", "user-agent"); assertThat(other.headers().getAccept()).hasToString("[application/json]"); assertThat(other.cookies()).isEmpty(); diff --git a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/config-binding/GraphQLDatasourceConfig.json b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/config-binding/GraphQLDatasourceConfig.json index c4b9e351b1..17289e49d7 100644 --- a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/config-binding/GraphQLDatasourceConfig.json +++ b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/config-binding/GraphQLDatasourceConfig.json @@ -247,13 +247,13 @@ "/authConfig/type" : "null" }, "noView" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null (through reference chain: org.lowcoder.sdk.plugin.graphql.GraphQLDatasourceConfig[\"oauth2InheritFromLogin\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null\n at [No location information] (through reference chain: org.lowcoder.sdk.plugin.graphql.GraphQLDatasourceConfig[\"oauth2InheritFromLogin\"])" }, "Public" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null (through reference chain: org.lowcoder.sdk.plugin.graphql.GraphQLDatasourceConfig[\"oauth2InheritFromLogin\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null\n at [No location information] (through reference chain: org.lowcoder.sdk.plugin.graphql.GraphQLDatasourceConfig[\"oauth2InheritFromLogin\"])" }, "Internal" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null (through reference chain: org.lowcoder.sdk.plugin.graphql.GraphQLDatasourceConfig[\"oauth2InheritFromLogin\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null\n at [No location information] (through reference chain: org.lowcoder.sdk.plugin.graphql.GraphQLDatasourceConfig[\"oauth2InheritFromLogin\"])" } }, "unknownAuthType" : { diff --git a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/config-binding/RestApiDatasourceConfig.json b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/config-binding/RestApiDatasourceConfig.json index 43626a0792..c98847583a 100644 --- a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/config-binding/RestApiDatasourceConfig.json +++ b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/config-binding/RestApiDatasourceConfig.json @@ -273,13 +273,13 @@ "/sslConfig/sslCertVerificationType" : "null" }, "noView" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null (through reference chain: org.lowcoder.sdk.plugin.restapi.RestApiDatasourceConfig[\"oauth2InheritFromLogin\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null\n at [No location information] (through reference chain: org.lowcoder.sdk.plugin.restapi.RestApiDatasourceConfig[\"oauth2InheritFromLogin\"])" }, "Public" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null (through reference chain: org.lowcoder.sdk.plugin.restapi.RestApiDatasourceConfig[\"oauth2InheritFromLogin\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null\n at [No location information] (through reference chain: org.lowcoder.sdk.plugin.restapi.RestApiDatasourceConfig[\"oauth2InheritFromLogin\"])" }, "Internal" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null (through reference chain: org.lowcoder.sdk.plugin.restapi.RestApiDatasourceConfig[\"oauth2InheritFromLogin\"])" + "error" : "tools.jackson.databind.DatabindException: Cannot invoke \"org.lowcoder.sdk.plugin.restapi.auth.RestApiAuthType.name()\" because the return value of \"org.lowcoder.sdk.plugin.restapi.auth.AuthConfig.getType()\" is null\n at [No location information] (through reference chain: org.lowcoder.sdk.plugin.restapi.RestApiDatasourceConfig[\"oauth2InheritFromLogin\"])" } }, "unknownAuthType" : { diff --git a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/node-conversion/renderMustacheJson.json b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/node-conversion/renderMustacheJson.json index c710e8d790..07433558bd 100644 --- a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/node-conversion/renderMustacheJson.json +++ b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/node-conversion/renderMustacheJson.json @@ -2,7 +2,7 @@ "param:int" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.IntNode" + "" : "tools.jackson.databind.node.IntNode" }, "keyOrder" : { } }, @@ -11,7 +11,7 @@ "param:long" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.LongNode" + "" : "tools.jackson.databind.node.LongNode" }, "keyOrder" : { } }, @@ -20,7 +20,7 @@ "param:double" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.DoubleNode" + "" : "tools.jackson.databind.node.DoubleNode" }, "keyOrder" : { } }, @@ -29,7 +29,7 @@ "param:bigDecimal" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.DecimalNode" + "" : "tools.jackson.databind.node.DecimalNode" }, "keyOrder" : { } }, @@ -38,7 +38,7 @@ "param:bigInteger" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.BigIntegerNode" + "" : "tools.jackson.databind.node.BigIntegerNode" }, "keyOrder" : { } }, @@ -47,7 +47,7 @@ "param:bool" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.BooleanNode" + "" : "tools.jackson.databind.node.BooleanNode" }, "keyOrder" : { } }, @@ -56,7 +56,7 @@ "param:nothing" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.NullNode" + "" : "tools.jackson.databind.node.NullNode" }, "keyOrder" : { } }, @@ -65,7 +65,7 @@ "param:str" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.TextNode" + "" : "tools.jackson.databind.node.StringNode" }, "keyOrder" : { } }, @@ -74,13 +74,13 @@ "param:map" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/zeta" : "com.fasterxml.jackson.databind.node.IntNode", - "/alpha" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/alpha/0" : "com.fasterxml.jackson.databind.node.LongNode", - "/alpha/1" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/alpha/2" : "com.fasterxml.jackson.databind.node.NullNode", - "/alpha/3" : "com.fasterxml.jackson.databind.node.DecimalNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/zeta" : "tools.jackson.databind.node.IntNode", + "/alpha" : "tools.jackson.databind.node.ArrayNode", + "/alpha/0" : "tools.jackson.databind.node.LongNode", + "/alpha/1" : "tools.jackson.databind.node.DoubleNode", + "/alpha/2" : "tools.jackson.databind.node.NullNode", + "/alpha/3" : "tools.jackson.databind.node.DecimalNode" }, "keyOrder" : { "" : [ "zeta", "alpha" ] @@ -91,12 +91,12 @@ "param:list" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0" : "com.fasterxml.jackson.databind.node.IntNode", - "/1" : "com.fasterxml.jackson.databind.node.TextNode", - "/2" : "com.fasterxml.jackson.databind.node.NullNode", - "/3" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/3/0" : "com.fasterxml.jackson.databind.node.BooleanNode" + "" : "tools.jackson.databind.node.ArrayNode", + "/0" : "tools.jackson.databind.node.IntNode", + "/1" : "tools.jackson.databind.node.StringNode", + "/2" : "tools.jackson.databind.node.NullNode", + "/3" : "tools.jackson.databind.node.ArrayNode", + "/3/0" : "tools.jackson.databind.node.BooleanNode" }, "keyOrder" : { } }, @@ -105,7 +105,7 @@ "missingParam" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.NullNode" + "" : "tools.jackson.databind.node.NullNode" }, "keyOrder" : { } }, @@ -114,7 +114,7 @@ "int" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.IntNode" + "" : "tools.jackson.databind.node.IntNode" }, "keyOrder" : { } }, @@ -123,7 +123,7 @@ "intMaxPlusOne" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.LongNode" + "" : "tools.jackson.databind.node.LongNode" }, "keyOrder" : { } }, @@ -132,7 +132,7 @@ "longMaxPlusOne" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.BigIntegerNode" + "" : "tools.jackson.databind.node.BigIntegerNode" }, "keyOrder" : { } }, @@ -141,7 +141,7 @@ "decimal" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.FloatNode" + "" : "tools.jackson.databind.node.FloatNode" }, "keyOrder" : { } }, @@ -150,7 +150,7 @@ "decimalPastFloat" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.DoubleNode" + "" : "tools.jackson.databind.node.DoubleNode" }, "keyOrder" : { } }, @@ -159,7 +159,7 @@ "longDecimal" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.FloatNode" + "" : "tools.jackson.databind.node.FloatNode" }, "keyOrder" : { } }, @@ -168,7 +168,7 @@ "exponent" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.FloatNode" + "" : "tools.jackson.databind.node.FloatNode" }, "keyOrder" : { } }, @@ -177,7 +177,7 @@ "true" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.BooleanNode" + "" : "tools.jackson.databind.node.BooleanNode" }, "keyOrder" : { } }, @@ -186,7 +186,7 @@ "null" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.NullNode" + "" : "tools.jackson.databind.node.NullNode" }, "keyOrder" : { } }, @@ -195,7 +195,7 @@ "quoted" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.TextNode" + "" : "tools.jackson.databind.node.StringNode" }, "keyOrder" : { } }, @@ -204,7 +204,7 @@ "text" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.TextNode" + "" : "tools.jackson.databind.node.StringNode" }, "keyOrder" : { } }, @@ -213,7 +213,7 @@ "dateTime" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.TextNode" + "" : "tools.jackson.databind.node.StringNode" }, "keyOrder" : { } }, @@ -225,18 +225,18 @@ "array" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/0" : "com.fasterxml.jackson.databind.node.IntNode", - "/1" : "com.fasterxml.jackson.databind.node.IntNode", - "/2" : "com.fasterxml.jackson.databind.node.TextNode", - "/3" : "com.fasterxml.jackson.databind.node.FloatNode", - "/4" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/4/zeta" : "com.fasterxml.jackson.databind.node.IntNode", - "/4/alpha" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/4/alpha/0" : "com.fasterxml.jackson.databind.node.LongNode", - "/4/alpha/1" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/4/alpha/2" : "com.fasterxml.jackson.databind.node.NullNode", - "/4/alpha/3" : "com.fasterxml.jackson.databind.node.DecimalNode" + "" : "tools.jackson.databind.node.ArrayNode", + "/0" : "tools.jackson.databind.node.IntNode", + "/1" : "tools.jackson.databind.node.IntNode", + "/2" : "tools.jackson.databind.node.StringNode", + "/3" : "tools.jackson.databind.node.FloatNode", + "/4" : "tools.jackson.databind.node.ObjectNode", + "/4/zeta" : "tools.jackson.databind.node.IntNode", + "/4/alpha" : "tools.jackson.databind.node.ArrayNode", + "/4/alpha/0" : "tools.jackson.databind.node.LongNode", + "/4/alpha/1" : "tools.jackson.databind.node.DoubleNode", + "/4/alpha/2" : "tools.jackson.databind.node.NullNode", + "/4/alpha/3" : "tools.jackson.databind.node.DecimalNode" }, "keyOrder" : { "/4" : [ "zeta", "alpha" ] @@ -247,16 +247,16 @@ "object" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/a" : "com.fasterxml.jackson.databind.node.ObjectNode", - "/a/zeta" : "com.fasterxml.jackson.databind.node.IntNode", - "/a/alpha" : "com.fasterxml.jackson.databind.node.ArrayNode", - "/a/alpha/0" : "com.fasterxml.jackson.databind.node.LongNode", - "/a/alpha/1" : "com.fasterxml.jackson.databind.node.DoubleNode", - "/a/alpha/2" : "com.fasterxml.jackson.databind.node.NullNode", - "/a/alpha/3" : "com.fasterxml.jackson.databind.node.DecimalNode", - "/b" : "com.fasterxml.jackson.databind.node.FloatNode", - "/žluť \"quoted\"" : "com.fasterxml.jackson.databind.node.LongNode" + "" : "tools.jackson.databind.node.ObjectNode", + "/a" : "tools.jackson.databind.node.ObjectNode", + "/a/zeta" : "tools.jackson.databind.node.IntNode", + "/a/alpha" : "tools.jackson.databind.node.ArrayNode", + "/a/alpha/0" : "tools.jackson.databind.node.LongNode", + "/a/alpha/1" : "tools.jackson.databind.node.DoubleNode", + "/a/alpha/2" : "tools.jackson.databind.node.NullNode", + "/a/alpha/3" : "tools.jackson.databind.node.DecimalNode", + "/b" : "tools.jackson.databind.node.FloatNode", + "/žluť \"quoted\"" : "tools.jackson.databind.node.LongNode" }, "keyOrder" : { "/a" : [ "zeta", "alpha" ], @@ -268,7 +268,7 @@ "escapedMustache" : { "node" : { "classes" : { - "" : "com.fasterxml.jackson.databind.node.TextNode" + "" : "tools.jackson.databind.node.StringNode" }, "keyOrder" : { } }, diff --git a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/polymorphism/AuthConfig.json b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/polymorphism/AuthConfig.json index 2fd34b3be6..898d0f3a9f 100644 --- a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/polymorphism/AuthConfig.json +++ b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/polymorphism/AuthConfig.json @@ -1 +1 @@ -{"BASIC_AUTH":{"bareMapperClass":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","class":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","noView":{"type":"DIGEST_AUTH","type":"BASIC_AUTH","username":"AuthConfig.BASIC_AUTH.username","password":"SECRET-AuthConfig.BASIC_AUTH.password"},"readBack":{"class":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","noView":{"type":"DIGEST_AUTH","type":"BASIC_AUTH","username":"AuthConfig.BASIC_AUTH.username","password":"SECRET-AuthConfig.BASIC_AUTH.password"}},"Public":{"type":"DIGEST_AUTH","type":"BASIC_AUTH","username":"AuthConfig.BASIC_AUTH.username"},"Internal":{"type":"DIGEST_AUTH","type":"BASIC_AUTH","username":"AuthConfig.BASIC_AUTH.username","password":"SECRET-AuthConfig.BASIC_AUTH.password"}},"DIGEST_AUTH":{"bareMapperClass":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","class":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","noView":{"type":"DIGEST_AUTH","type":"DIGEST_AUTH","username":"AuthConfig.DIGEST_AUTH.username","password":"SECRET-AuthConfig.DIGEST_AUTH.password"},"readBack":{"class":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","noView":{"type":"DIGEST_AUTH","type":"DIGEST_AUTH","username":"AuthConfig.DIGEST_AUTH.username","password":"SECRET-AuthConfig.DIGEST_AUTH.password"}},"Public":{"type":"DIGEST_AUTH","type":"DIGEST_AUTH","username":"AuthConfig.DIGEST_AUTH.username"},"Internal":{"type":"DIGEST_AUTH","type":"DIGEST_AUTH","username":"AuthConfig.DIGEST_AUTH.username","password":"SECRET-AuthConfig.DIGEST_AUTH.password"}},"NO_AUTH":{"bareMapperClass":"org.lowcoder.sdk.plugin.restapi.auth.NoneAuthConfig","class":"org.lowcoder.sdk.plugin.restapi.auth.NoneAuthConfig","noView":{"type":"NO_AUTH","type":"NO_AUTH"},"readBack":{"class":"org.lowcoder.sdk.plugin.restapi.auth.NoneAuthConfig","noView":{"type":"NO_AUTH","type":"NO_AUTH"}},"Public":{"type":"NO_AUTH","type":"NO_AUTH"},"Internal":{"type":"NO_AUTH","type":"NO_AUTH"}},"OAUTH2_INHERIT_FROM_LOGIN":{"bareMapperClass":"org.lowcoder.sdk.plugin.restapi.auth.OAuthInheritAuthConfig","class":"org.lowcoder.sdk.plugin.restapi.auth.OAuthInheritAuthConfig","noView":{"type":"OAUTH2_INHERIT_FROM_LOGIN","type":"OAUTH2_INHERIT_FROM_LOGIN","authId":"AuthConfig.OAUTH2_INHERIT_FROM_LOGIN.authId"},"readBack":{"class":"org.lowcoder.sdk.plugin.restapi.auth.OAuthInheritAuthConfig","noView":{"type":"OAUTH2_INHERIT_FROM_LOGIN","type":"OAUTH2_INHERIT_FROM_LOGIN","authId":"AuthConfig.OAUTH2_INHERIT_FROM_LOGIN.authId"}},"Public":{"type":"OAUTH2_INHERIT_FROM_LOGIN","type":"OAUTH2_INHERIT_FROM_LOGIN","authId":"AuthConfig.OAUTH2_INHERIT_FROM_LOGIN.authId"},"Internal":{"type":"OAUTH2_INHERIT_FROM_LOGIN","type":"OAUTH2_INHERIT_FROM_LOGIN","authId":"AuthConfig.OAUTH2_INHERIT_FROM_LOGIN.authId"}},"unregisteredConstant":{"bareMapperClass":"failsWith com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException","class":"org.lowcoder.sdk.plugin.restapi.auth.DefaultAuthConfig","noView":{"type":"DefaultAuthConfig","type":"BEARER_TOKEN_AUTH"},"readBack":"failsWith com.fasterxml.jackson.databind.exc.InvalidFormatException","Public":{"type":"DefaultAuthConfig","type":"BEARER_TOKEN_AUTH"},"Internal":{"type":"DefaultAuthConfig","type":"BEARER_TOKEN_AUTH"}},"unknownId":{"bareMapperClass":"failsWith com.fasterxml.jackson.databind.exc.InvalidFormatException","class":"failsWith com.fasterxml.jackson.databind.exc.InvalidFormatException"},"missingId":{"bareMapperClass":"failsWith com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException","class":"org.lowcoder.sdk.plugin.restapi.auth.DefaultAuthConfig","noView":{"type":"DefaultAuthConfig","type":null},"readBack":"failsWith com.fasterxml.jackson.databind.exc.InvalidFormatException","Public":{"type":"DefaultAuthConfig","type":null},"Internal":{"type":"DefaultAuthConfig","type":null}}} \ No newline at end of file +{"BASIC_AUTH":{"bareMapperClass":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","class":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","noView":{"type":"DIGEST_AUTH","type":"BASIC_AUTH","username":"AuthConfig.BASIC_AUTH.username","password":"SECRET-AuthConfig.BASIC_AUTH.password"},"readBack":{"class":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","noView":{"type":"DIGEST_AUTH","type":"BASIC_AUTH","username":"AuthConfig.BASIC_AUTH.username","password":"SECRET-AuthConfig.BASIC_AUTH.password"}},"Public":{"type":"DIGEST_AUTH","type":"BASIC_AUTH","username":"AuthConfig.BASIC_AUTH.username"},"Internal":{"type":"DIGEST_AUTH","type":"BASIC_AUTH","username":"AuthConfig.BASIC_AUTH.username","password":"SECRET-AuthConfig.BASIC_AUTH.password"}},"DIGEST_AUTH":{"bareMapperClass":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","class":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","noView":{"type":"DIGEST_AUTH","type":"DIGEST_AUTH","username":"AuthConfig.DIGEST_AUTH.username","password":"SECRET-AuthConfig.DIGEST_AUTH.password"},"readBack":{"class":"org.lowcoder.sdk.plugin.restapi.auth.BasicAuthConfig","noView":{"type":"DIGEST_AUTH","type":"DIGEST_AUTH","username":"AuthConfig.DIGEST_AUTH.username","password":"SECRET-AuthConfig.DIGEST_AUTH.password"}},"Public":{"type":"DIGEST_AUTH","type":"DIGEST_AUTH","username":"AuthConfig.DIGEST_AUTH.username"},"Internal":{"type":"DIGEST_AUTH","type":"DIGEST_AUTH","username":"AuthConfig.DIGEST_AUTH.username","password":"SECRET-AuthConfig.DIGEST_AUTH.password"}},"NO_AUTH":{"bareMapperClass":"org.lowcoder.sdk.plugin.restapi.auth.NoneAuthConfig","class":"org.lowcoder.sdk.plugin.restapi.auth.NoneAuthConfig","noView":{"type":"NO_AUTH","type":"NO_AUTH"},"readBack":{"class":"org.lowcoder.sdk.plugin.restapi.auth.NoneAuthConfig","noView":{"type":"NO_AUTH","type":"NO_AUTH"}},"Public":{"type":"NO_AUTH","type":"NO_AUTH"},"Internal":{"type":"NO_AUTH","type":"NO_AUTH"}},"OAUTH2_INHERIT_FROM_LOGIN":{"bareMapperClass":"org.lowcoder.sdk.plugin.restapi.auth.OAuthInheritAuthConfig","class":"org.lowcoder.sdk.plugin.restapi.auth.OAuthInheritAuthConfig","noView":{"type":"OAUTH2_INHERIT_FROM_LOGIN","type":"OAUTH2_INHERIT_FROM_LOGIN","authId":"AuthConfig.OAUTH2_INHERIT_FROM_LOGIN.authId"},"readBack":{"class":"org.lowcoder.sdk.plugin.restapi.auth.OAuthInheritAuthConfig","noView":{"type":"OAUTH2_INHERIT_FROM_LOGIN","type":"OAUTH2_INHERIT_FROM_LOGIN","authId":"AuthConfig.OAUTH2_INHERIT_FROM_LOGIN.authId"}},"Public":{"type":"OAUTH2_INHERIT_FROM_LOGIN","type":"OAUTH2_INHERIT_FROM_LOGIN","authId":"AuthConfig.OAUTH2_INHERIT_FROM_LOGIN.authId"},"Internal":{"type":"OAUTH2_INHERIT_FROM_LOGIN","type":"OAUTH2_INHERIT_FROM_LOGIN","authId":"AuthConfig.OAUTH2_INHERIT_FROM_LOGIN.authId"}},"unregisteredConstant":{"bareMapperClass":"failsWith tools.jackson.databind.exc.UnrecognizedPropertyException","class":"org.lowcoder.sdk.plugin.restapi.auth.DefaultAuthConfig","noView":{"type":"DefaultAuthConfig","type":"BEARER_TOKEN_AUTH"},"readBack":"failsWith tools.jackson.databind.exc.InvalidFormatException","Public":{"type":"DefaultAuthConfig","type":"BEARER_TOKEN_AUTH"},"Internal":{"type":"DefaultAuthConfig","type":"BEARER_TOKEN_AUTH"}},"unknownId":{"bareMapperClass":"failsWith tools.jackson.databind.exc.InvalidFormatException","class":"failsWith tools.jackson.databind.exc.InvalidFormatException"},"missingId":{"bareMapperClass":"failsWith tools.jackson.databind.exc.UnrecognizedPropertyException","class":"org.lowcoder.sdk.plugin.restapi.auth.DefaultAuthConfig","noView":{"type":"DefaultAuthConfig","type":null},"readBack":"failsWith tools.jackson.databind.exc.InvalidFormatException","Public":{"type":"DefaultAuthConfig","type":null},"Internal":{"type":"DefaultAuthConfig","type":null}}} \ No newline at end of file diff --git a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/polymorphism/SslConfig.json b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/polymorphism/SslConfig.json index 16e1e09e78..b1b1df3cef 100644 --- a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/polymorphism/SslConfig.json +++ b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/polymorphism/SslConfig.json @@ -1 +1 @@ -{"DISABLED":{"bareMapperClass":"org.lowcoder.sdk.plugin.common.ssl.DisableVerifySslConfig","class":"org.lowcoder.sdk.plugin.common.ssl.DisableVerifySslConfig","noView":{"sslCertVerificationType":"DISABLED","sslCertVerificationType":"DISABLED"},"readBack":{"class":"org.lowcoder.sdk.plugin.common.ssl.DisableVerifySslConfig","noView":{"sslCertVerificationType":"DISABLED","sslCertVerificationType":"DISABLED"}},"Public":{"sslCertVerificationType":"DISABLED","sslCertVerificationType":"DISABLED"},"Internal":{"sslCertVerificationType":"DISABLED","sslCertVerificationType":"DISABLED"}},"VERIFY_SELF_SIGNED_CERT":{"bareMapperClass":"org.lowcoder.sdk.plugin.common.ssl.VerifySelfSignedCertSslConfig","class":"org.lowcoder.sdk.plugin.common.ssl.VerifySelfSignedCertSslConfig","noView":{"sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","selfSignedCert":"SECRET-SslConfig.VERIFY_SELF_SIGNED_CERT.selfSignedCert"},"readBack":{"class":"org.lowcoder.sdk.plugin.common.ssl.VerifySelfSignedCertSslConfig","noView":{"sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","selfSignedCert":"SECRET-SslConfig.VERIFY_SELF_SIGNED_CERT.selfSignedCert"}},"Public":{"sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT"},"Internal":{"sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","selfSignedCert":"SECRET-SslConfig.VERIFY_SELF_SIGNED_CERT.selfSignedCert"}},"unregisteredConstant":{"bareMapperClass":"org.lowcoder.sdk.plugin.common.ssl.VerifyCACertSslConfig","class":"org.lowcoder.sdk.plugin.common.ssl.VerifyCACertSslConfig","noView":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":"VERIFY_CA_CERT"},"readBack":"failsWith com.fasterxml.jackson.databind.exc.InvalidFormatException","Public":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":"VERIFY_CA_CERT"},"Internal":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":"VERIFY_CA_CERT"}},"unknownId":{"bareMapperClass":"failsWith com.fasterxml.jackson.databind.exc.InvalidFormatException","class":"failsWith com.fasterxml.jackson.databind.exc.InvalidFormatException"},"missingId":{"bareMapperClass":"failsWith com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException","class":"org.lowcoder.sdk.plugin.common.ssl.VerifyCACertSslConfig","noView":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":null},"readBack":"failsWith com.fasterxml.jackson.databind.exc.InvalidFormatException","Public":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":null},"Internal":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":null}}} \ No newline at end of file +{"DISABLED":{"bareMapperClass":"org.lowcoder.sdk.plugin.common.ssl.DisableVerifySslConfig","class":"org.lowcoder.sdk.plugin.common.ssl.DisableVerifySslConfig","noView":{"sslCertVerificationType":"DISABLED","sslCertVerificationType":"DISABLED"},"readBack":{"class":"org.lowcoder.sdk.plugin.common.ssl.DisableVerifySslConfig","noView":{"sslCertVerificationType":"DISABLED","sslCertVerificationType":"DISABLED"}},"Public":{"sslCertVerificationType":"DISABLED","sslCertVerificationType":"DISABLED"},"Internal":{"sslCertVerificationType":"DISABLED","sslCertVerificationType":"DISABLED"}},"VERIFY_SELF_SIGNED_CERT":{"bareMapperClass":"org.lowcoder.sdk.plugin.common.ssl.VerifySelfSignedCertSslConfig","class":"org.lowcoder.sdk.plugin.common.ssl.VerifySelfSignedCertSslConfig","noView":{"sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","selfSignedCert":"SECRET-SslConfig.VERIFY_SELF_SIGNED_CERT.selfSignedCert"},"readBack":{"class":"org.lowcoder.sdk.plugin.common.ssl.VerifySelfSignedCertSslConfig","noView":{"sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","selfSignedCert":"SECRET-SslConfig.VERIFY_SELF_SIGNED_CERT.selfSignedCert"}},"Public":{"sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT"},"Internal":{"sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","sslCertVerificationType":"VERIFY_SELF_SIGNED_CERT","selfSignedCert":"SECRET-SslConfig.VERIFY_SELF_SIGNED_CERT.selfSignedCert"}},"unregisteredConstant":{"bareMapperClass":"org.lowcoder.sdk.plugin.common.ssl.VerifyCACertSslConfig","class":"org.lowcoder.sdk.plugin.common.ssl.VerifyCACertSslConfig","noView":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":"VERIFY_CA_CERT"},"readBack":"failsWith tools.jackson.databind.exc.InvalidFormatException","Public":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":"VERIFY_CA_CERT"},"Internal":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":"VERIFY_CA_CERT"}},"unknownId":{"bareMapperClass":"failsWith tools.jackson.databind.exc.InvalidFormatException","class":"failsWith tools.jackson.databind.exc.InvalidFormatException"},"missingId":{"bareMapperClass":"failsWith tools.jackson.databind.exc.UnrecognizedPropertyException","class":"org.lowcoder.sdk.plugin.common.ssl.VerifyCACertSslConfig","noView":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":null},"readBack":"failsWith tools.jackson.databind.exc.InvalidFormatException","Public":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":null},"Internal":{"sslCertVerificationType":"VerifyCACertSslConfig","sslCertVerificationType":null}}} \ No newline at end of file diff --git a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/query-results/ResultSetParser.leaves.json b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/query-results/ResultSetParser.leaves.json index 6cd1e394f2..66080d92d9 100644 --- a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/query-results/ResultSetParser.leaves.json +++ b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/query-results/ResultSetParser.leaves.json @@ -64,14 +64,14 @@ "typeName" : "OTHER", "class" : "javax.sql.rowset.serial.SerialClob", "written" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Unsupported operation. SerialClob cannot return a the CLOB value as an ascii stream, unless instantiated with a fully implemented Clob object. (through reference chain: javax.sql.rowset.serial.SerialClob[\"asciiStream\"])" + "error" : "tools.jackson.databind.DatabindException: Unsupported operation. SerialClob cannot return a the CLOB value as an ascii stream, unless instantiated with a fully implemented Clob object.\n at [No location information] (through reference chain: javax.sql.rowset.serial.SerialClob[\"asciiStream\"])" } }, "nclob" : { "typeName" : "OTHER", "class" : "org.lowcoder.sdk.plugin.common.sql.ResultSetParserContractTest$TestNClob", "written" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Unsupported operation. SerialClob cannot return a the CLOB value as an ascii stream, unless instantiated with a fully implemented Clob object. (through reference chain: org.lowcoder.sdk.plugin.common.sql.ResultSetParserContractTest$TestNClob[\"asciiStream\"])" + "error" : "tools.jackson.databind.DatabindException: Unsupported operation. SerialClob cannot return a the CLOB value as an ascii stream, unless instantiated with a fully implemented Clob object.\n at [No location information] (through reference chain: org.lowcoder.sdk.plugin.common.sql.ResultSetParserContractTest$TestNClob[\"asciiStream\"])" } }, "blobLeaf" : { @@ -83,7 +83,7 @@ "typeName" : "OTHER", "class" : "javax.sql.rowset.serial.SerialArray", "written" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: (was javax.sql.rowset.serial.SerialException) (through reference chain: javax.sql.rowset.serial.SerialArray[\"resultSet\"])" + "error" : "tools.jackson.databind.DatabindException: (was javax.sql.rowset.serial.SerialException)\n at [No location information] (through reference chain: javax.sql.rowset.serial.SerialArray[\"resultSet\"])" } }, "struct" : { @@ -187,7 +187,7 @@ } }, "written" : { - "error" : "com.fasterxml.jackson.databind.JsonMappingException: Unsupported operation. SerialClob cannot return a the CLOB value as an ascii stream, unless instantiated with a fully implemented Clob object. (through reference chain: org.lowcoder.sdk.models.QueryExecutionResult[\"data\"]->java.util.ArrayList[0]->java.util.LinkedHashMap[\"clob\"]->javax.sql.rowset.serial.SerialClob[\"asciiStream\"])" + "error" : "tools.jackson.databind.DatabindException: Unsupported operation. SerialClob cannot return a the CLOB value as an ascii stream, unless instantiated with a fully implemented Clob object.\n at [No location information] (through reference chain: org.lowcoder.sdk.models.QueryExecutionResult[\"data\"]->java.util.ArrayList[0]->java.util.LinkedHashMap[\"clob\"]->javax.sql.rowset.serial.SerialClob[\"asciiStream\"])" } } } \ No newline at end of file diff --git a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/tree-text/E13.txt b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/tree-text/E13.txt index 04a1951d3d..e913d26f71 100644 --- a/server/api-service/lowcoder-sdk/src/test/resources/json-contract/tree-text/E13.txt +++ b/server/api-service/lowcoder-sdk/src/test/resources/json-contract/tree-text/E13.txt @@ -1,2 +1,2 @@ production {"decimal":1.10,"instant":0.0} -toString {"decimal":1.10,"instant":"[ERROR: (com.fasterxml.jackson.databind.exc.InvalidDefinitionException) Java 8 date/time type `java.time.Instant` not supported by default: add Module \"com.fasterxml.jackson.datatype:jackson-datatype-jsr310\" to enable handling]"} +toString {"decimal":1.10,"instant":"1970-01-01T00:00:00Z"} diff --git a/server/api-service/lowcoder-server/pom.xml b/server/api-service/lowcoder-server/pom.xml index 4a95d9f37f..16b6d5b577 100644 --- a/server/api-service/lowcoder-server/pom.xml +++ b/server/api-service/lowcoder-server/pom.xml @@ -32,13 +32,6 @@ ${keystore.password} - - - local_libs - Temporary local libraries - file://${maven.multiModuleProjectDirectory}/local-repo - - @@ -93,11 +86,6 @@ org.springdoc springdoc-openapi-starter-webflux-ui - - org.springdoc - springdoc-openapi-webflux-ui - 1.8.0 - io.projectreactor.tools blockhound @@ -135,7 +123,7 @@ io.sentry - sentry-spring-boot-starter-jakarta + sentry-spring-boot-4 org.apache.httpcomponents @@ -165,11 +153,6 @@ io.projectreactor reactor-tools - - org.mockito - mockito-inline - test - org.mockito mockito-core @@ -179,10 +162,18 @@ org.springframework.boot spring-boot-starter-test test + + + + com.vaadin.external.google + android-json + + - org.springframework.security - spring-security-test + org.springframework.boot + spring-boot-starter-security-test test @@ -191,7 +182,7 @@ test + the version comes from the Spring Boot dependency management in lowcoder-dependencies --> org.testcontainers testcontainers-mongodb @@ -203,6 +194,20 @@ testcontainers test + + + com.icegreen + greenmail + 2.1.15 + test + + + junit + junit + + + com.jayway.jsonpath json-path @@ -215,31 +220,31 @@ com.auth0 java-jwt - 4.4.0 + 4.6.2 org.passay passay - 1.6.3 + 2.0.0 io.jsonwebtoken jjwt-api - 0.11.5 + 0.13.0 compile io.jsonwebtoken jjwt-jackson - 0.11.5 + 0.13.0 compile io.jsonwebtoken jjwt-impl - 0.11.5 + 0.13.0 runtime @@ -249,13 +254,24 @@ org.wiremock wiremock-jetty12 - 3.6.0 + 3.13.2 test + + + org.eclipse.jetty.ee10 + jetty-ee10-bom + 12.1.15 + pom + import + org.lowcoder lowcoder-dependencies @@ -282,26 +298,6 @@ ${assembly.lib.directory} runtime - rjson - - - - copy-rjson-snapshot - package - - copy - - - - - tv.twelvetone.rjson - rjson - 1.3.1-SNAPSHOT - true - ${assembly.lib.directory} - - - false @@ -309,7 +305,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.3.0 + 3.5.1 @@ -326,7 +322,7 @@ org.apache.maven.plugins maven-jarsigner-plugin - 3.0.0 + 3.1.0 sign @@ -352,7 +348,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.1.2 + 3.6.1 ${skipUnitTests} @@ -384,7 +380,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.2.5 + 3.6.1 ${skipIntegrationTests} + full true true true true - 0.8.14 + 0.8.16 false @@ -83,15 +86,36 @@ + + org.apache.maven.plugins + maven-enforcer-plugin + 3.7.0 + + + require-jdk-25 + validate + + enforce + + + + + [25,) + + + + + + org.codehaus.mojo license-maven-plugin - 2.4.0 + 2.9.0 org.apache.maven.plugins maven-dependency-plugin - 3.6.1 + 3.11.0