001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.revetsec.servlet.jakarta;
017
018import com.google.errorprone.annotations.CheckReturnValue;
019import com.revetsec.saml.SamlAuthenticationRequestResult;
020import com.revetsec.saml.SamlLogoutRedirectResult;
021import com.revetsec.saml.SamlLogoutResponseRedirectResult;
022import com.revetsec.saml.SamlLogoutPostResult;
023import com.revetsec.saml.SamlLogoutResponsePostResult;
024import com.revetsec.saml.SamlPostBindingMessage;
025import com.revetsec.saml.SamlPostBindingParseResult;
026import com.revetsec.saml.SamlPostForm;
027import com.revetsec.saml.SamlRedirectBindingMessage;
028import com.revetsec.saml.SamlRedirectBindingParseResult;
029import jakarta.servlet.http.HttpServletRequest;
030import jakarta.servlet.http.HttpServletResponse;
031import org.jspecify.annotations.NonNull;
032import org.jspecify.annotations.Nullable;
033
034import javax.annotation.concurrent.ThreadSafe;
035import java.io.IOException;
036import java.net.URI;
037import java.nio.charset.StandardCharsets;
038import java.util.ArrayList;
039import java.util.Enumeration;
040import java.util.List;
041import java.util.Map;
042
043import static java.util.Objects.requireNonNull;
044
045/**
046 * Thin SAML transport helpers for application-routed Jakarta Servlet endpoints. Core performs
047 * binding, signature, pending-state and replay validation; the application owns cookies,
048 * sessions and IdP selection. Call these before any servlet parameter parser consumes the body.
049 *
050 * @since 1.0.0
051 */
052@ThreadSafe
053public final class ServletSaml {
054    // Mirrors core's SAML POST bound: three encoded fields plus framing.
055    private static final int MAXIMUM_ADAPTER_BODY_BYTES = 1_061_128;
056
057    private ServletSaml() { }
058
059    /**
060     * Reads the original bounded POST body, at most two Content-Type values, and the raw query.
061     * A second occurrence preserves core's duplicate rejection without reading the enumeration tail
062     * or accessing the body. Trusted edge/container framing, allocation and time limits still apply.
063     *
064     * @param request application-routed ACS request
065     * @return core's untrusted POST-binding parse result
066     * @throws IOException if the servlet input stream fails
067     * @since 1.0.0
068     */
069    @CheckReturnValue
070    public static @NonNull SamlPostBindingParseResult postBindingResultFor(
071            @NonNull HttpServletRequest request) throws IOException {
072        requireNonNull(request);
073        if (!"POST".equals(request.getMethod()))
074            throw new IllegalArgumentException("SAML ACS route requires POST");
075        return postBindingResult(request, false);
076    }
077
078    /**
079     * Reads the original bounded logout POST body, at most two Content-Type values and the raw query.
080     * A second occurrence preserves core's duplicate rejection without further header probes or body access.
081     * The application supplies browser-bound pending state to core when completing SP logout;
082     * a pending cookie for a cross-site POST requires Secure, HttpOnly and SameSite=None.
083     *
084     * @param request application-routed logout POST request
085     * @return core's untrusted logout POST-binding parse result
086     * @throws IOException if the servlet input stream fails
087     * @since 1.0.0
088     */
089    @CheckReturnValue
090    public static @NonNull SamlPostBindingParseResult postLogoutBindingResultFor(
091            @NonNull HttpServletRequest request) throws IOException {
092        requireNonNull(request);
093        if (!"POST".equals(request.getMethod()))
094            throw new IllegalArgumentException("SAML logout route requires POST");
095        return postBindingResult(request, true);
096    }
097
098    private static @NonNull SamlPostBindingParseResult postBindingResult(
099            @NonNull HttpServletRequest request, boolean logout) throws IOException {
100        List<String> contentTypes = new ArrayList<>(2);
101        Enumeration<String> values = request.getHeaders("Content-Type");
102        // A second occurrence is sufficient for core refusal; never probe or read its tail.
103        if (values != null) while (contentTypes.size() < 2 && values.hasMoreElements())
104            contentTypes.add(values.nextElement());
105        String rawQuery = request.getQueryString();
106        // Let core reject invalid framing before allocating or reading an untrusted body.
107        byte[] framingProbe = { 'x' };
108        SamlPostBindingParseResult framing = logout
109                ? SamlPostBindingMessage.fromLogoutFormBodyResult(framingProbe, List.copyOf(contentTypes), rawQuery)
110                : SamlPostBindingMessage.fromFormBodyResult(framingProbe, List.copyOf(contentTypes), rawQuery);
111        if (framing instanceof SamlPostBindingParseResult.Rejected rejection
112                && rejection.getReason() == SamlPostBindingParseResult.Reason.CONTENT_TYPE) return framing;
113        byte[] body = request.getInputStream().readNBytes(MAXIMUM_ADAPTER_BODY_BYTES + 1);
114        if (body.length > MAXIMUM_ADAPTER_BODY_BYTES) body = new byte[0];
115        return logout ? SamlPostBindingMessage.fromLogoutFormBodyResult(body, List.copyOf(contentTypes),
116                rawQuery) : SamlPostBindingMessage.fromFormBodyResult(body,
117                List.copyOf(contentTypes), rawQuery);
118    }
119
120    /**
121     * Parses the original HTTP-Redirect query octets for signed logout messages.
122     *
123     * @param request application-routed logout request
124     * @return core's untrusted Redirect-binding parse result
125     * @since 1.0.0
126     */
127    @CheckReturnValue
128    public static @NonNull SamlRedirectBindingParseResult redirectBindingResultFor(
129            @NonNull HttpServletRequest request) {
130        requireNonNull(request);
131        if (!"GET".equals(request.getMethod()))
132            return SamlRedirectBindingParseResult.Rejected.INSTANCE;
133        String rawQuery = request.getQueryString();
134        return SamlRedirectBindingMessage.fromRawQueryResult(rawQuery == null ? "" : rawQuery);
135    }
136
137    /**
138     * Writes a core-prepared authentication redirect without servlet URL rewriting.
139     *
140     * @param response application-owned response, including any pending cookie
141     * @param prepared core-prepared authentication request
142     * @since 1.0.0
143     */
144    public static void writeAuthenticationRedirect(@NonNull HttpServletResponse response,
145            SamlAuthenticationRequestResult.@NonNull Prepared prepared) {
146        writeRedirect(response, requireNonNull(prepared).getRedirectUri());
147    }
148
149    /**
150     * Writes a core-prepared SP logout redirect.
151     *
152     * @param response application-owned response
153     * @param prepared core-prepared logout request
154     * @since 1.0.0
155     */
156    public static void writeLogoutRedirect(@NonNull HttpServletResponse response,
157            SamlLogoutRedirectResult.@NonNull Prepared prepared) {
158        writeRedirect(response, requireNonNull(prepared).getRedirectUri());
159    }
160
161    /**
162     * Writes a core-prepared answer to an IdP logout request.
163     *
164     * @param response application-owned response
165     * @param prepared core-prepared logout response
166     * @since 1.0.0
167     */
168    public static void writeLogoutResponseRedirect(@NonNull HttpServletResponse response,
169            SamlLogoutResponseRedirectResult.@NonNull Prepared prepared) {
170        writeRedirect(response, requireNonNull(prepared).getRedirectUri());
171    }
172
173    /**
174     * Writes a core-prepared SP logout POST form. Set the browser-bound pending cookie and CSP
175     * before delivery; a cross-site POST pending cookie requires Secure, HttpOnly and SameSite=None.
176     *
177     * @param response application-owned response
178     * @param prepared core-prepared logout request
179     * @param cspNonce application-generated CSP nonce, or null for manual submission
180     * @throws IOException if the servlet output stream fails
181     * @since 1.0.0
182     */
183    public static void writeLogoutPostForm(@NonNull HttpServletResponse response,
184            SamlLogoutPostResult.@NonNull Prepared prepared, @Nullable String cspNonce) throws IOException {
185        writePostForm(response, requireNonNull(prepared).getPostForm(), cspNonce);
186    }
187
188    /**
189     * Writes a core-prepared POST answer to an IdP logout request. The application sets its CSP.
190     *
191     * @param response application-owned response
192     * @param prepared core-prepared logout response
193     * @param cspNonce application-generated CSP nonce, or null for manual submission
194     * @throws IOException if the servlet output stream fails
195     * @since 1.0.0
196     */
197    public static void writeLogoutResponsePostForm(@NonNull HttpServletResponse response,
198            SamlLogoutResponsePostResult.@NonNull Prepared prepared, @Nullable String cspNonce)
199            throws IOException {
200        writePostForm(response, requireNonNull(prepared).getPostForm(), cspNonce);
201    }
202
203    private static void writeRedirect(@NonNull HttpServletResponse response, @NonNull URI destination) {
204        requireNonNull(response);
205        requireNonNull(destination);
206        if (!"https".equalsIgnoreCase(destination.getScheme()) || destination.getHost() == null
207                || destination.getRawUserInfo() != null || destination.getRawFragment() != null)
208            throw new IllegalArgumentException("SAML Redirect requires an HTTPS host");
209        response.setStatus(HttpServletResponse.SC_FOUND);
210        response.setHeader("Location", destination.toASCIIString());
211        response.setHeader("Cache-Control", "no-store");
212        response.setHeader("Pragma", "no-cache");
213        response.setHeader("Referrer-Policy", "no-referrer");
214        response.setHeader("X-Content-Type-Options", "nosniff");
215    }
216
217    /**
218     * Writes a core-prepared POST form. The application sets its CSP and pending cookie first.
219     *
220     * @param response application-owned response
221     * @param form core-prepared SAML authentication or logout form
222     * @param cspNonce application-generated CSP nonce, or null for manual submission
223     * @throws IOException if the servlet output stream fails
224     * @since 1.0.0
225     */
226    public static void writePostForm(@NonNull HttpServletResponse response, @NonNull SamlPostForm form,
227            @Nullable String cspNonce) throws IOException {
228        requireNonNull(response);
229        requireNonNull(form);
230        byte[] body = form.toHtml(cspNonce).getBytes(StandardCharsets.UTF_8);
231        response.setStatus(HttpServletResponse.SC_OK);
232        for (Map.Entry<String, String> header : form.getHeaders().entrySet())
233            response.setHeader(header.getKey(), header.getValue());
234        response.setContentLength(body.length);
235        response.getOutputStream().write(body);
236    }
237}