001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.mcp.v20260728;
018
019import java.security.Principal;
020import java.util.*;
021
022import org.apache.juneau.commons.concurrent.*;
023
024/**
025 * Pluggable SPI for sealing/unsealing the opaque {@code requestState} continuation token (MCP {@code 2026-07-28}
026 * SEP-2322 Multi-Round-Trip Requests).
027 *
028 * <p>
029 * Mirrors the "pluggable SPI + built-in default" shape sub-project E established for the client-side
030 * {@code McpResponseCache} (not on this module's classpath): this interface plus {@link AeadRequestStateCodec}
031 * (the built-in default) is the server-side, seal/unseal counterpart.
032 *
033 * <p>
034 * Implementations must treat any verification failure (tamper, AAD mismatch, or an implementation-specific
035 * integrity check) as an {@link Optional#empty()} return from {@link #unseal(String, String)} &mdash; never a
036 * thrown exception. Expiry is checked by the caller ({@code McpRevision}) against
037 * {@link McpRequestState#expiresAtMs()}, not by the codec itself, since expiry is a dispatcher-level policy (see
038 * {@link McpMrtrConfig}), not a codec integrity concern.
039 *
040 * <p>
041 * <b>Trust model &mdash; {@code requestState} is a bearer token.</b> The sealed token is a replayable credential:
042 * anyone who holds it can resume the paused operation until it expires, and it carries no caller identity. A
043 * codec (and every call site) must treat it accordingly &mdash; transport only over authenticated TLS, and
044 * <b>never log</b> a {@code requestState}. <b>Single-use by default:</b> {@link McpMrtrConfig} wires an
045 * {@link InMemoryReplayCache} unless the operator replaces it (see {@link McpMrtrConfig#setReplayCache(ReplayCache)});
046 * it is per-process only, so cross-node single-use requires a shared implementation. With the check disabled a
047 * handler must write idempotent resume side effects; the max-rounds cap bounds chain depth, not replay count (see
048 * {@link McpMrtrConfig}).
049 *
050 * <p>
051 * <b>Canonical AAD format.</b> The dispatcher binds each token to the request that produced it by passing a
052 * single canonical AAD string: {@code method + '\u0000' + protocolVersion + '\u0000' + target} &mdash; the
053 * JSON-RPC method name, the negotiated protocol version, and the operation target (the tool {@code name} for
054 * {@code tools/call}, the prompt {@code name} for {@code prompts/get}, or the resource {@code uri} for
055 * {@code resources/read}; empty for any other method), all NUL ({@code U+0000})-separated (see
056 * {@code McpRevision#aad}). NUL is chosen because it can never appear in a method name, a protocol-version
057 * literal, or the trailing target field, so the concatenation is unambiguous. The trailing target field binds
058 * the token to the specific operation it paused against, not merely the method, so a token minted while paused
059 * on one tool/prompt/resource cannot be resumed against a different one of the same kind. An implementation
060 * only needs to treat the AAD as opaque bytes; the format is documented here so seal and unseal call sites (and
061 * any custom codec) agree on exactly what is authenticated.
062 *
063 * <p>
064 * <b>Authenticated principal.</b> Both {@link #seal(McpRequestState, String, Principal)} and
065 * {@link #unseal(String, String, Principal)} receive the caller's authenticated {@link Principal} &mdash; the same
066 * identity the resource-server layer establishes (see {@code McpResourceServerSupport#principal}). This is the
067 * <i>seam</i> a hardened codec uses to fold the caller identity into its authenticated data, so a
068 * {@code requestState} minted for principal A cannot be resumed by principal B. The built-in
069 * {@link AeadRequestStateCodec} binds exactly that: it folds a canonical, deterministic {@code iss|sub} identity
070 * (see {@link AeadRequestStateCodec#principalIdentity(Principal)}) into its AEAD authenticated data, so a
071 * mismatched principal fails the GCM tag check and {@link #unseal} returns {@link Optional#empty()}. The
072 * dispatcher guarantees the principal is delivered to the codec at both seal and unseal; a custom codec
073 * remains free to bind a different identity attribute (subject claim, issuer+subject, full claim set) or none at
074 * all. The principal is <b>nullable</b>: when RS auth is disabled or the caller is anonymous it is <jk>null</jk>,
075 * and every codec must seal/unseal cleanly (no NPE) in that case. The two-argument
076 * {@link #seal(McpRequestState, String)} / {@link #unseal(String, String)} convenience overloads simply pass a
077 * <jk>null</jk> (no-principal) identity.
078 */
079public interface RequestStateCodec {
080
081   /**
082    * Seals a payload into an opaque token, exposing the authenticated caller identity to the codec.
083    *
084    * @param state The payload to seal. Must not be <jk>null</jk>.
085    * @param aad Additional authenticated data (the dispatcher passes the canonical
086    *    {@code method + '\u0000' + protocolVersion + '\u0000' + target} form &mdash; see the class Javadoc). Must
087    *    not be <jk>null</jk>.
088    * @param principal The authenticated caller (see the class Javadoc). May be <jk>null</jk> for an anonymous
089    *    caller or when resource-server auth is disabled.
090    * @return The opaque token. Never <jk>null</jk>.
091    */
092   String seal(McpRequestState state, String aad, Principal principal);
093
094   /**
095    * Unseals a token, verifying integrity against the supplied AAD, with the authenticated caller identity
096    * available to the codec.
097    *
098    * <p>
099    * <b>The {@code token} is arbitrary, untrusted client input.</b> It arrives verbatim from the follow-up
100    * request's {@code requestState} field, so an implementation must assume nothing about its length or content:
101    * it must not allocate buffers sized from the raw token, and it must not throw &mdash; any malformed, oversized,
102    * tampered, or AAD-mismatched input must return {@link Optional#empty()} (see the class Javadoc contract).
103    *
104    * @param token The token previously returned by {@link #seal(McpRequestState, String, Principal)}. Must not be
105    *    <jk>null</jk>.
106    * @param aad The AAD to verify against. Must match the value passed to
107    *    {@link #seal(McpRequestState, String, Principal)} exactly, or verification fails.
108    * @param principal The authenticated caller (see the class Javadoc). May be <jk>null</jk> for an anonymous
109    *    caller or when resource-server auth is disabled. A codec that binds the principal must fail
110    *    verification when it differs from the sealing principal.
111    * @return The original payload, or {@link Optional#empty()} if verification fails for any reason (tamper,
112    *    AAD mismatch, malformed token, principal mismatch).
113    */
114   Optional<McpRequestState> unseal(String token, String aad, Principal principal);
115
116   /**
117    * No-principal convenience overload of {@link #seal(McpRequestState, String, Principal)} (anonymous caller).
118    *
119    * @param state The payload to seal. Must not be <jk>null</jk>.
120    * @param aad Additional authenticated data. Must not be <jk>null</jk>.
121    * @return The opaque token. Never <jk>null</jk>.
122    */
123   default String seal(McpRequestState state, String aad) {
124      return seal(state, aad, null);
125   }
126
127   /**
128    * No-principal convenience overload of {@link #unseal(String, String, Principal)} (anonymous caller).
129    *
130    * @param token The token previously returned by {@link #seal(McpRequestState, String)}. Must not be <jk>null</jk>.
131    * @param aad The AAD to verify against.
132    * @return The original payload, or {@link Optional#empty()} if verification fails for any reason.
133    */
134   default Optional<McpRequestState> unseal(String token, String aad) {
135      return unseal(token, aad, null);
136   }
137}