This is an automated email from the ASF dual-hosted git repository. papegaaij pushed a commit to branch islands in repository https://gitbox.apache.org/repos/asf/wicket.git
commit 58195ec45c214673bda872ab42d404de4c0593b0 Author: Emond Papegaaij <[email protected]> AuthorDate: Fri Nov 6 06:57:25 2026 +0100 Give page-less endpoints page context through handles, and island modules the CSP nonce A page-less endpoint could not know which record the page shows unless the client told it, and anything the client sends can be changed: the members of one board could be asked for another by editing an id. An island now passes a context with usePageless(name, endpointId, model). When the island renders, the context goes into the application's IIslandHandleStore and the island state carries only an opaque handle, which the runtime sends with each call in the X-Wicket-Islands-Handle header. The endpoint reads the context with PagelessCall#getHandle. The default SessionHandleStore keeps up to 1000 handles per session in the session's metadata, each 24 random bytes from the application's secure random supplier and bound to the endpoint it was issued for; issuing one binds a temporary session. A handle that does not resolve (unknown, from another session, for another endpoint, or pushed out by newer ones) is answered as expired before the endpoint runs, and getHandle on a call without a handle rejects it as invalid. An island keeps its handle while the context stays equal. A handle is not an authorization: the endpoint still checks access to the context, as the Javadoc says where the methods are. The "pageless" entries of the island state change from a URL to an object with the URL and an optional handle; the runtime reads the new form. Nothing has been released, so no application is affected. Component libraries that inject style elements, Mantine and TipTap among them, need the page's CSP nonce, as Wicket's strict policy allows inline styles only with it. Every island now renders the csp-nonce meta tag that only the dev-server loader rendered before, and the runtime exports cspNonce() to read it; the React adapter re-exports it. Co-Authored-By: Claude Opus 5.5 <[email protected]> --- .../npm/packages/react/src/index.tsx | 2 +- .../npm/packages/runtime/src/index.ts | 10 ++ .../npm/packages/runtime/src/runtime.ts | 25 +++- .../npm/packages/runtime/test/runtime.test.ts | 40 +++++- .../npm/packages/runtime/test/wicket-fixture.ts | 2 +- .../java/org/apache/wicket/islands/FormIsland.java | 31 ++++- .../apache/wicket/islands/IIslandHandleStore.java | 62 +++++++++ .../java/org/apache/wicket/islands/Island.java | 39 +++++- .../org/apache/wicket/islands/IslandSettings.java | 22 +++ .../org/apache/wicket/islands/IslandSupport.java | 89 ++++++++++-- .../org/apache/wicket/islands/PagelessCall.java | 31 ++++- .../wicket/islands/PagelessEndpointResource.java | 14 +- .../apache/wicket/islands/SessionHandleStore.java | 153 +++++++++++++++++++++ .../islands/modules/ViteDevServerModuleLoader.java | 18 +-- .../apache/wicket/islands/IslandRenderTest.java | 13 ++ .../org/apache/wicket/islands/IslandTestPage.java | 3 + .../wicket/islands/PagelessEndpointTest.java | 141 +++++++++++++++++-- 17 files changed, 643 insertions(+), 52 deletions(-) diff --git a/wicket-experimental/wicket-islands/npm/packages/react/src/index.tsx b/wicket-experimental/wicket-islands/npm/packages/react/src/index.tsx index 4de68ad115..bec2462a63 100644 --- a/wicket-experimental/wicket-islands/npm/packages/react/src/index.tsx +++ b/wicket-experimental/wicket-islands/npm/packages/react/src/index.tsx @@ -22,7 +22,7 @@ import { createRoot } from 'react-dom/client'; import type { FormBinding, FormState, IslandCallError, IslandContext, IslandModule } from 'wicket-islands'; -export { IslandCallError } from 'wicket-islands'; +export { IslandCallError, cspNonce } from 'wicket-islands'; export type { FormState, IslandCallErrorKind } from 'wicket-islands'; interface PropsStore<P> { diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts b/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts index 9ae49eb723..3af80ecf64 100644 --- a/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts @@ -35,6 +35,16 @@ export function runtime(): IslandRuntime { return scope[GLOBAL_KEY] ??= new IslandRuntime(); } +/** + * The nonce of the page's Content Security Policy, for style or script elements a component + * library injects; undefined when the policy uses no nonces. Wicket renders it in a + * <code>csp-nonce</code> meta tag, as Vite expects. + */ +export function cspNonce(): string | undefined { + const meta = document.querySelector<HTMLMetaElement>('meta[property="csp-nonce"]'); + return meta?.nonce || meta?.getAttribute('nonce') || undefined; +} + /** * Registers the module for an island type and mounts every island of that type on the page. * Called by the entry modules the Vite plugin generates. diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts b/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts index b8c0074aa5..6fcdc61091 100644 --- a/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts @@ -34,15 +34,25 @@ const PARAM_CALL_ID = 'island-call-id'; const PARAM_PAYLOAD = 'island-payload'; const PARAM_KEY = 'island-key'; const PAGELESS_HEADER = 'X-Wicket-Islands'; +const HANDLE_HEADER = 'X-Wicket-Islands-Handle'; interface IslandState { props: unknown; calls: string[]; ajax: WicketAjaxAttributes; - pageless?: Record<string, string>; + pageless?: Record<string, PagelessCall>; form?: FormState; } +/** + * A page-less endpoint as the island state names it: its URL, and the handle standing for the + * context the server keeps for the island's calls. + */ +interface PagelessCall { + url: string; + handle?: string; +} + interface MountedIsland { readonly type: string; readonly key: string; @@ -257,13 +267,20 @@ export class IslandRuntime { }); } - private async callPageless(url: string, payload: unknown): Promise<unknown> { + private async callPageless(pageless: PagelessCall, payload: unknown): Promise<unknown> { + const headers: Record<string, string> = { + 'Content-Type': 'application/json', + [PAGELESS_HEADER]: '1' + }; + if (pageless.handle) { + headers[HANDLE_HEADER] = pageless.handle; + } let response: Response; try { - response = await fetch(url, { + response = await fetch(pageless.url, { method: 'POST', credentials: 'same-origin', - headers: { 'Content-Type': 'application/json', [PAGELESS_HEADER]: '1' }, + headers, body: payload === undefined ? '' : JSON.stringify(payload) }); } catch { diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts b/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts index aad47897bc..647fc8ceb0 100644 --- a/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts @@ -16,7 +16,7 @@ */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { IslandCallError, IslandRuntime, type IslandContext, type IslandModule } from '../src/index'; +import { cspNonce, IslandCallError, IslandRuntime, type IslandContext, type IslandModule } from '../src/index'; import { component, data, failRequest, formHost, host, requests, respond, setUpWicket } from './wicket-fixture'; interface Props { @@ -318,7 +318,10 @@ describe('IslandRuntime', () => { beforeEach(() => { document.body.innerHTML = `<div id="panel">${host('board1', 'board', 'k1', { label: 'one' }, - './call?board1', { scores: './wicket-islands-call/scores' })}</div>`; + './call?board1', { + scores: { url: './wicket-islands-call/scores' }, + members: { url: './wicket-islands-call/members', handle: 'h-1' } + })}</div>`; runtime.register('board', recorder.module()); }); @@ -336,6 +339,23 @@ describe('IslandRuntime', () => { expect(fetched[0].init.method).toBe('POST'); expect(fetched[0].init.body).toBe('{"size":"SMALL"}'); expect((fetched[0].init.headers as Record<string, string>)['X-Wicket-Islands']).toBe('1'); + expect(fetched[0].init.headers).not.toHaveProperty('X-Wicket-Islands-Handle'); + }); + + it('sends the handle the island was rendered with', async () => { + answer(200, { ok: true, value: [], invalidate: [] }); + + await recorder.context.call('members', { prefix: 'a' }); + + expect(fetched[0].url).toBe('./wicket-islands-call/members'); + expect((fetched[0].init.headers as Record<string, string>)['X-Wicket-Islands-Handle']) + .toBe('h-1'); + }); + + it('rejects a call whose handle the server no longer knows as expired', async () => { + answer(200, { ok: false, error: { kind: 'expired', messages: ['gone'] }, invalidate: [] }); + + await expect(recorder.context.call('members')).rejects.toMatchObject({ kind: 'expired' }); }); it('rejects a failed page-less call', async () => { @@ -387,3 +407,19 @@ describe('IslandRuntime', () => { expect(invalidated).toEqual([['scores']]); }); }); + +describe('cspNonce', () => { + afterEach(() => { + document.head.innerHTML = ''; + }); + + it('reads the nonce Wicket renders for the page', () => { + document.head.innerHTML = '<meta property="csp-nonce" nonce="n0nce">'; + + expect(cspNonce()).toBe('n0nce'); + }); + + it('is undefined when the page has no nonce', () => { + expect(cspNonce()).toBeUndefined(); + }); +}); diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts b/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts index 1a2ddc08d7..ffb0c554be 100644 --- a/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts @@ -94,7 +94,7 @@ export function data(value: unknown): string { * The markup of an island host, as Island renders it. */ export function host(id: string, type: string, key: string, props: unknown, url = `./call?${id}`, - pageless?: Record<string, string>): string { + pageless?: Record<string, { url: string; handle?: string }>): string { return hostWith(id, type, key, { props, pageless }, '', url); } diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/FormIsland.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/FormIsland.java index e2330b9fea..6cca46708f 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/FormIsland.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/FormIsland.java @@ -16,6 +16,7 @@ */ package org.apache.wicket.islands; +import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -245,7 +246,34 @@ public class FormIsland<T, P> extends FormComponent<T> */ public final FormIsland<T, P> usePageless(String name, String endpointId) { - island.addPageless(name, endpointId); + island.addPageless(name, endpointId, null); + return this; + } + + /** + * Makes a page-less endpoint callable by the client-side peer under the given name, with a + * handle for the given context. The context is read when the island renders and kept on the + * server, in the {@link IslandSettings#getHandleStore() handle store}; the client only holds the + * handle and sends it with each call, and the endpoint reads the context with + * {@link PagelessCall#getHandle(Class)}. Use it for context the client must not choose, such as + * the record the page shows. The handle is reissued when the context changes. + * <p> + * <strong>A handle is not an authorization mechanism.</strong> The endpoint still checks that + * the session may access the context. + * + * @param name + * the name the client calls + * @param endpointId + * the id the endpoint is registered under in {@link PagelessEndpoints} + * @param context + * the context of the calls; small, serializable and with a meaningful + * {@code equals} + * @return {@code this} + */ + public final FormIsland<T, P> usePageless(String name, String endpointId, + IModel<? extends Serializable> context) + { + island.addPageless(name, endpointId, Args.notNull(context, "context")); return this; } @@ -340,6 +368,7 @@ public class FormIsland<T, P> extends FormComponent<T> { props.detach(); } + island.detach(); super.onDetach(); } } diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IIslandHandleStore.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IIslandHandleStore.java new file mode 100644 index 0000000000..60b83fa27a --- /dev/null +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IIslandHandleStore.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.wicket.islands; + +import java.io.Serializable; + +/** + * Keeps the context of page-less calls behind handles. An island issues a handle when it renders; + * the client sends it with each call, and the endpoint reads the context with + * {@link PagelessCall#getHandle(Class)}. The client cannot forge a context this way: it only ever + * holds the handle. + * <p> + * A handle must be unguessable and must only resolve in the session that it was issued in, for + * the endpoint it was issued for. It is still a token: it can leak or be replayed within its + * session. <strong>A handle is not an authorization mechanism</strong>; an endpoint checks + * whether the session may access the context on its own terms. + * <p> + * Handles are issued while a page renders and resolved by page-less calls, which run in parallel + * without the page lock, so an implementation must be thread-safe. + * + * @see SessionHandleStore + * @since 12.0.0 + */ +public interface IIslandHandleStore +{ + /** + * Issues a handle in the current session. + * + * @param endpointId + * the endpoint the handle is valid for + * @param context + * the context the handle stands for + * @return the handle + */ + String issue(String endpointId, Serializable context); + + /** + * Resolves a handle sent by the client in the current session. + * + * @param endpointId + * the endpoint that was called + * @param handle + * the handle, untrusted + * @return the context, or {@code null} when the handle is unknown in this session, was issued + * for another endpoint, or is no longer kept + */ + Serializable resolve(String endpointId, String handle); +} diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java index 659fb75360..2616881733 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java @@ -16,12 +16,15 @@ */ package org.apache.wicket.islands; +import java.io.Serializable; + import org.apache.wicket.IGenericComponent; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.html.WebComponent; import org.apache.wicket.model.IModel; +import org.apache.wicket.util.lang.Args; /** * A component whose body is rendered in the browser by a JavaScript framework component, its @@ -178,7 +181,34 @@ public class Island<P> extends WebComponent implements IGenericComponent<P, Isla */ public final Island<P> usePageless(String name, String endpointId) { - island.addPageless(name, endpointId); + island.addPageless(name, endpointId, null); + return this; + } + + /** + * Makes a page-less endpoint callable by the client-side peer under the given name, with a + * handle for the given context. The context is read when the island renders and kept on the + * server, in the {@link IslandSettings#getHandleStore() handle store}; the client only holds the + * handle and sends it with each call, and the endpoint reads the context with + * {@link PagelessCall#getHandle(Class)}. Use it for context the client must not choose, such as + * the record the page shows. The handle is reissued when the context changes. + * <p> + * <strong>A handle is not an authorization mechanism.</strong> The endpoint still checks that + * the session may access the context. + * + * @param name + * the name the client calls + * @param endpointId + * the id the endpoint is registered under in {@link PagelessEndpoints} + * @param context + * the context of the calls; small, serializable and with a meaningful + * {@code equals} + * @return {@code this} + */ + public final Island<P> usePageless(String name, String endpointId, + IModel<? extends Serializable> context) + { + island.addPageless(name, endpointId, Args.notNull(context, "context")); return this; } @@ -213,4 +243,11 @@ public class Island<P> extends WebComponent implements IGenericComponent<P, Isla island.renderHead(response); } + + @Override + protected void onDetach() + { + island.detach(); + super.onDetach(); + } } diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java index 5215e48ebf..4fcf4e6193 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java @@ -87,6 +87,8 @@ public class IslandSettings private final PagelessEndpoints pagelessEndpoints = new PagelessEndpoints(); + private IIslandHandleStore handleStore = new SessionHandleStore(); + /** * Installs the settings in an application, mounts the resource serving the built files, * registers the listener that answers island calls failing before they reach their island, and @@ -164,6 +166,26 @@ public class IslandSettings return pagelessEndpoints; } + /** + * @return the store of the handles islands issue for page-less calls, by default a + * {@link SessionHandleStore} + */ + public IIslandHandleStore getHandleStore() + { + return handleStore; + } + + /** + * @param handleStore + * the store of the handles islands issue for page-less calls + * @return {@code this} + */ + public IslandSettings setHandleStore(IIslandHandleStore handleStore) + { + this.handleStore = Args.notNull(handleStore, "handleStore"); + return this; + } + ResourceReference getEndpointReference() { return endpoints; diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java index 075133085f..4b433c4d89 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java @@ -16,15 +16,20 @@ */ package org.apache.wicket.islands; +import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; +import org.apache.wicket.csp.ContentSecurityPolicySettings; import org.apache.wicket.islands.serializer.IIslandSerializer; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.IHeaderResponse; +import org.apache.wicket.markup.head.MetaDataHeaderItem; import org.apache.wicket.markup.parser.XmlTag.TagType; +import org.apache.wicket.model.IModel; +import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.io.IClusterable; @@ -45,13 +50,53 @@ final class IslandSupport implements IClusterable { } + /** + * A page-less endpoint the island calls, with the context of its handle and the handle last + * issued for it. + */ + private static final class Pageless implements IClusterable + { + private static final long serialVersionUID = 1L; + + private final String endpointId; + + private final IModel<? extends Serializable> context; + + private Serializable issuedFor; + + private String handle; + + private Pageless(String endpointId, IModel<? extends Serializable> context) + { + this.endpointId = endpointId; + this.context = context; + } + + private String handle() + { + if (context == null) + { + return null; + } + Serializable current = Args.notNull(context.getObject(), "context"); + IIslandHandleStore store = IslandSettings.get().getHandleStore(); + if (handle == null || !current.equals(issuedFor) || + store.resolve(endpointId, handle) == null) + { + handle = store.issue(endpointId, current); + issuedFor = current; + } + return handle; + } + } + private final String type; private final String key; private final Map<String, Endpoint> endpoints = new LinkedHashMap<>(); - private final Map<String, String> pageless = new LinkedHashMap<>(); + private final Map<String, Pageless> pageless = new LinkedHashMap<>(); private final IslandEndpointBehavior behavior = new IslandEndpointBehavior(); @@ -93,11 +138,11 @@ final class IslandSupport implements IClusterable endpoints.put(name, new Endpoint(requestType, (IslandCallHandler<Object, Object>)handler)); } - void addPageless(String name, String endpointId) + void addPageless(String name, String endpointId, IModel<? extends Serializable> context) { Args.notEmpty(name, "name"); Args.notEmpty(endpointId, "endpointId"); - pageless.put(name, endpointId); + pageless.put(name, new Pageless(endpointId, context)); } static <Q> IslandCallHandler<Q, Void> withoutResult(IslandCallConsumer<Q> consumer) @@ -154,30 +199,54 @@ final class IslandSupport implements IClusterable IIslandSerializer serializer = serializer(); String state = "{\"props\":" + serializer.toJson(props) + ",\"calls\":" + serializer.toJson(endpoints.keySet()) + ",\"ajax\":" + behavior.renderAttributes() + - ",\"pageless\":" + serializer.toJson(pagelessUrls()) + + ",\"pageless\":" + serializer.toJson(renderPageless()) + (form != null ? ",\"form\":" + form : "") + "}"; return "<script type=\"application/json\" " + Island.ATTR_STATE + ">" + IslandJson.escapeForScript(state) + "</script><div " + Island.ATTR_ROOT + "></div>"; } - private Map<String, String> pagelessUrls() + private Map<String, Map<String, String>> renderPageless() { - Map<String, String> urls = new LinkedHashMap<>(); - pageless.forEach((name, id) -> { + Map<String, Map<String, String>> rendered = new LinkedHashMap<>(); + pageless.forEach((name, use) -> { PageParameters parameters = new PageParameters(); - parameters.set(0, id); - urls.put(name, RequestCycle.get() + parameters.set(0, use.endpointId); + Map<String, String> call = new LinkedHashMap<>(); + call.put("url", RequestCycle.get() .urlFor(IslandSettings.get().getEndpointReference(), parameters) .toString()); + String handle = use.handle(); + if (handle != null) + { + call.put("handle", handle); + } + rendered.put(name, call); }); - return urls; + return rendered; } void renderHead(IHeaderResponse response) { + ContentSecurityPolicySettings csp = WebApplication.get().getCspSettings(); + if (csp.isNonceEnabled()) + { + response.render(new MetaDataHeaderItem(MetaDataHeaderItem.META_TAG) + .addTagAttribute("property", "csp-nonce") + .addTagAttribute("nonce", csp.getNonce(RequestCycle.get()))); + } IslandSettings.get().getModuleLoader().renderHead(type, response); } + void detach() + { + pageless.values().forEach(use -> { + if (use.context != null) + { + use.context.detach(); + } + }); + } + static IIslandSerializer serializer() { return IslandSettings.get().getSerializer(); diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessCall.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessCall.java index 21b9c07a36..03fcb64dc4 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessCall.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessCall.java @@ -16,6 +16,7 @@ */ package org.apache.wicket.islands; +import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -38,10 +39,13 @@ public final class PagelessCall private final List<String> invalidations = new ArrayList<>(); - PagelessCall(String endpoint, WebRequest request) + private final Serializable handle; + + PagelessCall(String endpoint, WebRequest request, Serializable handle) { this.endpoint = endpoint; this.request = request; + this.handle = handle; } /** @@ -68,6 +72,31 @@ public final class PagelessCall return Session.get(); } + /** + * Returns the context of the handle the call was made with: the context the island passed to + * {@code usePageless} when it rendered. The client cannot choose it, but a handle is no + * permission: check that the session may access the context. + * + * @param <C> + * the type of the context + * @param type + * the type of the context + * @return the context + * @throws IslandCallRejectedException + * when the call came without a handle; throw it on, so the call is answered as + * invalid + * @throws ClassCastException + * when the context is not of the given type + */ + public <C> C getHandle(Class<C> type) + { + if (handle == null) + { + throw reject("The call has no handle."); + } + return type.cast(handle); + } + /** * Creates the exception that rejects this call. Throw it. * diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessEndpointResource.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessEndpointResource.java index 5547b892f6..8037904c4b 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessEndpointResource.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessEndpointResource.java @@ -18,6 +18,7 @@ package org.apache.wicket.islands; import java.io.IOException; import java.io.InputStream; +import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.List; @@ -39,6 +40,9 @@ import jakarta.servlet.http.HttpServletRequest; * a CORS preflight that is never granted, and refuses a request whose <code>Sec-Fetch-Site</code> * is not <code>same-origin</code>. These checks apply whether or not the application uses * resource isolation for its pages. + * <p> + * A call made with a handle the session does not know, for example one issued before the session + * expired, is answered as expired. */ final class PagelessEndpointResource extends AbstractResource { @@ -48,6 +52,8 @@ final class PagelessEndpointResource extends AbstractResource static final String HEADER = "X-Wicket-Islands"; + static final String HANDLE_HEADER = "X-Wicket-Islands-Handle"; + private static final int MAX_PAYLOAD = 1024 * 1024; @Override @@ -92,7 +98,13 @@ final class PagelessEndpointResource extends AbstractResource return response; } - String answer = answer(id, registration, new PagelessCall(id, request), body); + String handleHeader = request.getHeader(HANDLE_HEADER); + Serializable handle = handleHeader == null ? null + : IslandSettings.get().getHandleStore().resolve(id, handleHeader); + String answer = handleHeader != null && handle == null + ? IslandAnswer.failure(IslandSettings.get().getSerializer(), null, "expired", + List.of("The page this call belongs to has expired."), List.of()) + : answer(id, registration, new PagelessCall(id, request, handle), body); response.setContentType("application/json"); response.setTextEncoding("UTF-8"); response.setWriteCallback(new WriteCallback() diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/SessionHandleStore.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/SessionHandleStore.java new file mode 100644 index 0000000000..d53c97c3b3 --- /dev/null +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/SessionHandleStore.java @@ -0,0 +1,153 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.wicket.islands; + +import java.io.Serializable; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.wicket.Application; +import org.apache.wicket.MetaDataKey; +import org.apache.wicket.Session; +import org.apache.wicket.util.lang.Args; + +/** + * Keeps handles in the session, the most recently used ones up to a capacity. A handle is a random + * token from the application's secure random supplier; it dies with the session and does not + * resolve in another one. Issuing a handle binds a temporary session. + * <p> + * The contexts are stored in the session, so they must be small; the session is replicated with + * them where the application replicates sessions. A handle that has been pushed out by newer ones + * no longer resolves, and the call is answered as expired. + * + * @since 12.0.0 + */ +public class SessionHandleStore implements IIslandHandleStore +{ + /** + * The number of handles a session keeps by default. + */ + public static final int DEFAULT_CAPACITY = 1000; + + private static final int HANDLE_BYTES = 24; + + private static final MetaDataKey<Handles> KEY = new MetaDataKey<>() + { + private static final long serialVersionUID = 1L; + }; + + private record Issued(String endpointId, Serializable context) implements Serializable + { + } + + private static final class Handles implements Serializable + { + private static final long serialVersionUID = 1L; + + private final Map<String, Issued> entries; + + private Handles(int capacity) + { + entries = new LinkedHashMap<>(16, 0.75f, true) + { + private static final long serialVersionUID = 1L; + + @Override + protected boolean removeEldestEntry(Map.Entry<String, Issued> eldest) + { + return size() > capacity; + } + }; + } + + private synchronized void put(String handle, Issued issued) + { + entries.put(handle, issued); + } + + private synchronized Issued get(String handle) + { + return entries.get(handle); + } + } + + private final int capacity; + + /** + * Keeps {@value #DEFAULT_CAPACITY} handles per session. + */ + public SessionHandleStore() + { + this(DEFAULT_CAPACITY); + } + + /** + * @param capacity + * the number of handles a session keeps + */ + public SessionHandleStore(int capacity) + { + this.capacity = Args.withinRange(1, Integer.MAX_VALUE, capacity, "capacity"); + } + + @Override + public String issue(String endpointId, Serializable context) + { + Args.notNull(endpointId, "endpointId"); + Args.notNull(context, "context"); + + Session session = Session.get(); + if (session.isTemporary()) + { + session.bind(); + } + String handle = Application.get() + .getSecuritySettings() + .getRandomSupplier() + .getRandomBase64(HANDLE_BYTES); + Handles handles = handles(session, true); + handles.put(handle, new Issued(endpointId, context)); + session.setMetaData(KEY, handles); + return handle; + } + + @Override + public Serializable resolve(String endpointId, String handle) + { + if (handle == null) + { + return null; + } + Handles handles = handles(Session.get(), false); + Issued issued = handles == null ? null : handles.get(handle); + return issued != null && issued.endpointId().equals(endpointId) ? issued.context() : null; + } + + private Handles handles(Session session, boolean create) + { + synchronized (session) + { + Handles handles = session.getMetaData(KEY); + if (handles == null && create) + { + handles = new Handles(capacity); + session.setMetaData(KEY, handles); + } + return handles; + } + } +} diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteDevServerModuleLoader.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteDevServerModuleLoader.java index 65c459b67f..fc5fc9a6c5 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteDevServerModuleLoader.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteDevServerModuleLoader.java @@ -16,13 +16,9 @@ */ package org.apache.wicket.islands.modules; -import org.apache.wicket.csp.ContentSecurityPolicySettings; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.JavaScriptHeaderItem; import org.apache.wicket.markup.head.JavaScriptReferenceType; -import org.apache.wicket.markup.head.MetaDataHeaderItem; -import org.apache.wicket.protocol.http.WebApplication; -import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.util.lang.Args; import org.apache.wicket.util.string.Strings; @@ -31,10 +27,9 @@ import org.apache.wicket.util.string.Strings; * development. * <p> * Renders Vite's client and, for each island type, the module the Wicket Islands Vite plugin - * serves at <code>/@wicket-islands/<type></code>. When the page has a Content Security Policy - * with nonces, it also renders the nonce in the <code>csp-nonce</code> meta tag Vite reads, so the - * style elements Vite injects carry it. The dev server's origin must be allowed for connections, - * for Vite's hot module replacement. + * serves at <code>/@wicket-islands/<type></code>. The style elements Vite injects take the + * nonce of a Content Security Policy from the <code>csp-nonce</code> meta tag every island renders. + * The dev server's origin must be allowed for connections, for Vite's hot module replacement. * * @since 12.0.0 */ @@ -54,13 +49,6 @@ public class ViteDevServerModuleLoader implements IIslandModuleLoader @Override public void renderHead(String islandType, IHeaderResponse response) { - ContentSecurityPolicySettings csp = WebApplication.get().getCspSettings(); - if (csp.isNonceEnabled()) - { - response.render(new MetaDataHeaderItem(MetaDataHeaderItem.META_TAG) - .addTagAttribute("property", "csp-nonce") - .addTagAttribute("nonce", csp.getNonce(RequestCycle.get()))); - } response.render(JavaScriptHeaderItem.forUrl(devServerUrl + "/@vite/client") .setType(JavaScriptReferenceType.MODULE)); response.render(JavaScriptHeaderItem.forUrl(devServerUrl + "/@wicket-islands/" + islandType) diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandRenderTest.java b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandRenderTest.java index fb55439c56..0e58bb3570 100644 --- a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandRenderTest.java +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandRenderTest.java @@ -40,6 +40,19 @@ class IslandRenderTest extends IslandTestCase private static final Pattern STATE = Pattern.compile( "<script type=\"application/json\" data-wicket-island-state>(.*?)</script>", Pattern.DOTALL); + @Test + void rendersTheCspNonceForStylesTheModulesInject() + { + tester.getApplication().getCspSettings().blocking().strict(); + + tester.startPage(IslandTestPage.class); + + String response = tester.getLastResponseAsString(); + assertTrue(Pattern.compile("<meta property=\"csp-nonce\" nonce=\"[^\"]+\"") + .matcher(response) + .find(), response); + } + @Test void rendersHostWithTypeAndKey() { diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.java b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.java index 9daa0a66fa..8f2da21b00 100644 --- a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.java +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.java @@ -47,6 +47,8 @@ public class IslandTestPage extends WebPage private int count; + String customer = "c1"; + final Label label; final Island<TestProps> island; @@ -74,6 +76,7 @@ public class IslandTestPage extends WebPage }); island.usePageless("echo"); island.usePageless("sum", "echo"); + island.usePageless("customer", "whoami", () -> customer); add(island); add(new AjaxLink<Void>("invalidate") diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/PagelessEndpointTest.java b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/PagelessEndpointTest.java index 179a5cb9a8..b690d32ed1 100644 --- a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/PagelessEndpointTest.java +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/PagelessEndpointTest.java @@ -17,6 +17,10 @@ package org.apache.wicket.islands; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; @@ -26,6 +30,7 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.wicket.ThreadContext; import org.apache.wicket.islands.IslandTestPage.Add; import org.apache.wicket.islands.IslandTestPage.Sum; import org.apache.wicket.mock.MockWebResponse; @@ -59,7 +64,9 @@ class PagelessEndpointTest extends IslandTestCase .register("secret", Void.class, (none, call) -> "secret", call -> false) .register("boom", Void.class, (none, call) -> { throw new IllegalStateException("broken"); - }, IPagelessAuthorization.PERMIT_ALL); + }, IPagelessAuthorization.PERMIT_ALL) + .register("whoami", Void.class, (none, call) -> call.getHandle(String.class), + IPagelessAuthorization.PERMIT_ALL); } @Test @@ -115,31 +122,108 @@ class PagelessEndpointTest extends IslandTestCase @Test void requestWithoutTheHeaderIsRefused() { - assertEquals(403, send("echo", "POST", "{\"amount\":1}", null, false).getStatus()); + assertEquals(403, send("echo", "POST", "{\"amount\":1}", null, false, null).getStatus()); } @Test void getIsRefused() { - assertEquals(405, send("echo", "GET", "", null, true).getStatus()); + assertEquals(405, send("echo", "GET", "", null, true, null).getStatus()); } @Test - @SuppressWarnings("unchecked") void islandStateHoldsTheUrlsOfItsPagelessCalls() { tester.startPage(IslandTestPage.class); - Matcher matcher = Pattern.compile( - "data-wicket-island-state>(.*?)</script>", Pattern.DOTALL) - .matcher(tester.getLastResponseAsString()); - assertTrue(matcher.find()); - Map<String, String> pageless = (Map<String, String>)JSON - .readValue(matcher.group(1), Map.class) - .get("pageless"); - assertEquals(List.of("echo", "sum"), List.copyOf(pageless.keySet())); - assertTrue(pageless.get("echo").endsWith("wicket-islands-call/echo"), pageless.toString()); + Map<String, Map<String, String>> pageless = renderedPageless(); + assertEquals(List.of("echo", "sum", "customer"), List.copyOf(pageless.keySet())); + assertTrue(pageless.get("echo").get("url").endsWith("wicket-islands-call/echo"), + pageless.toString()); assertEquals(pageless.get("echo"), pageless.get("sum")); + assertFalse(pageless.get("echo").containsKey("handle")); + assertTrue(pageless.get("customer").get("url").endsWith("wicket-islands-call/whoami"), + pageless.toString()); + } + + @Test + void handleCarriesTheContextTheIslandRendered() + { + tester.startPage(IslandTestPage.class); + + Map<String, Object> answer = answer(call("whoami", handle("customer"))); + + assertEquals(Boolean.TRUE, answer.get("ok")); + assertEquals("c1", answer.get("value")); + } + + @Test + void handleIsKeptWhileTheContextIsTheSame() + { + IslandTestPage page = tester.startPage(IslandTestPage.class); + String first = handle("customer"); + + tester.startPage(page); + assertEquals(first, handle("customer")); + + page.customer = "c2"; + tester.startPage(page); + String second = handle("customer"); + assertNotEquals(first, second); + assertEquals("c2", answer(call("whoami", second)).get("value")); + } + + @Test + void callWithoutHandleIsInvalidWhenTheEndpointNeedsOne() + { + assertEquals("invalid", error(answer(call("whoami", null))).get("kind")); + } + + @Test + void unknownHandleIsExpired() + { + tester.startPage(IslandTestPage.class); + + assertEquals("expired", error(answer(call("whoami", "made-up"))).get("kind")); + } + + @Test + void handleOfAnotherEndpointIsExpired() + { + tester.startPage(IslandTestPage.class); + + Map<String, Object> answer = answer( + send("echo", "POST", "{\"amount\":1}", null, true, handle("customer"))); + + assertEquals("expired", error(answer).get("kind")); + } + + @Test + void handleOfAnotherSessionIsExpired() + { + tester.startPage(IslandTestPage.class); + String handle = handle("customer"); + + ThreadContext.setSession( + tester.getApplication().newSession(tester.getRequestCycle().getRequest(), + tester.getRequestCycle().getResponse())); + + assertEquals("expired", error(answer(call("whoami", handle))).get("kind")); + } + + @Test + void storeKeepsTheMostRecentlyUsedHandles() + { + SessionHandleStore store = new SessionHandleStore(2); + + String first = store.issue("whoami", "a"); + String second = store.issue("whoami", "b"); + assertEquals("a", store.resolve("whoami", first)); + String third = store.issue("whoami", "c"); + + assertEquals("a", store.resolve("whoami", first)); + assertNull(store.resolve("whoami", second)); + assertEquals("c", store.resolve("whoami", third)); } @Test @@ -156,11 +240,34 @@ class PagelessEndpointTest extends IslandTestCase private MockWebResponse post(String id, String body, String fetchSite) { - return send(id, "POST", body, fetchSite, true); + return send(id, "POST", body, fetchSite, true, null); + } + + private MockWebResponse call(String id, String handle) + { + return send(id, "POST", "", "same-origin", true, handle); + } + + @SuppressWarnings("unchecked") + private Map<String, Map<String, String>> renderedPageless() + { + Matcher matcher = Pattern.compile( + "data-wicket-island-state>(.*?)</script>", Pattern.DOTALL) + .matcher(tester.getLastResponseAsString()); + assertTrue(matcher.find()); + return (Map<String, Map<String, String>>)JSON.readValue(matcher.group(1), Map.class) + .get("pageless"); + } + + private String handle(String name) + { + String handle = renderedPageless().get(name).get("handle"); + assertNotNull(handle); + return handle; } private MockWebResponse send(String id, String method, String body, String fetchSite, - boolean header) + boolean header, String handle) { byte[] bytes = body.getBytes(StandardCharsets.UTF_8); MockHttpServletRequest http = new MockHttpServletRequest(tester.getApplication(), @@ -206,6 +313,10 @@ class PagelessEndpointTest extends IslandTestCase { http.addHeader("Sec-Fetch-Site", fetchSite); } + if (handle != null) + { + http.addHeader(PagelessEndpointResource.HANDLE_HEADER, handle); + } MockWebResponse response = new MockWebResponse(); new PagelessEndpointResource().respond(new IResource.Attributes( new ServletWebRequest(http, ""), response, new PageParameters().set(0, id)));
