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.scim.ScimAttributeSelectionResult;
020import com.revetsec.scim.ScimError;
021import com.revetsec.scim.ScimIfMatchResult;
022import com.revetsec.scim.ScimIfNoneMatchResult;
023import com.revetsec.scim.ScimQueryParseResult;
024import com.revetsec.scim.ScimResource;
025import com.revetsec.scim.ScimResourceType;
026import com.revetsec.scim.ScimResponse;
027import com.revetsec.scim.ScimServiceProvider;
028import jakarta.servlet.http.HttpServletRequest;
029import jakarta.servlet.http.HttpServletResponse;
030import org.jspecify.annotations.NonNull;
031import org.jspecify.annotations.Nullable;
032import javax.annotation.concurrent.ThreadSafe;
033import java.io.IOException;
034import java.io.InterruptedIOException;
035import java.net.SocketTimeoutException;
036import java.util.AbstractList;
037import java.util.ArrayList;
038import java.util.Enumeration;
039import java.util.List;
040import java.util.Map;
041import static java.util.Objects.requireNonNull;
042
043/** Thin raw-input SCIM transport helpers for application-routed Servlet endpoints.
044 * The application selects the caller, tenant, resource type and transaction. Acquire raw
045 * headers and the body before Servlet parameter decoding; then invoke core's header-aware parser.
046 * Container and trusted-edge limits must also bound upstream body/header allocation.
047 * @since 1.0.0
048 */
049@ThreadSafe
050public final class ServletScim {
051    private ServletScim() { }
052
053    /** Parses the unchanged resource-list query without Servlet parameter decoding.
054     * @param provider the configured service provider
055     * @param resourceType the application-selected registered resource type
056     * @param request the routed request
057     * @return the core query result
058     * @since 1.0.0
059     */
060    @CheckReturnValue
061    public static @NonNull ScimQueryParseResult queryResultFor(@NonNull ScimServiceProvider provider,
062            @NonNull ScimResourceType resourceType, @NonNull HttpServletRequest request) {
063        requireNonNull(provider); requireNonNull(resourceType); requireNonNull(request);
064        String query = request.getQueryString();
065        return provider.parseQueryResult(resourceType, query == null ? "" : query);
066    }
067
068    /** Parses response projection from the unchanged query.
069     * @param provider the configured service provider
070     * @param resourceType the application-selected registered resource type
071     * @param request the routed request
072     * @return the core selection result
073     * @since 1.0.0
074     */
075    @CheckReturnValue
076    public static @NonNull ScimAttributeSelectionResult attributeSelectionResultFor(
077            @NonNull ScimServiceProvider provider, @NonNull ScimResourceType resourceType,
078            @NonNull HttpServletRequest request) {
079        requireNonNull(provider); requireNonNull(resourceType); requireNonNull(request);
080        String query = request.getQueryString();
081        return provider.parseAttributeSelectionResult(resourceType, query == null ? "" : query);
082    }
083
084    /** Checks original If-Match occurrences against the same resource used by the transaction.
085     * @param provider the configured service provider
086     * @param current the authoritative current resource
087     * @param request the routed request
088     * @return the core conditional result
089     * @since 1.0.0
090     */
091    @CheckReturnValue
092    public static @NonNull ScimIfMatchResult ifMatchResultFor(@NonNull ScimServiceProvider provider,
093            @NonNull ScimResource current, @NonNull HttpServletRequest request) {
094        requireNonNull(provider); requireNonNull(current); requireNonNull(request);
095        return provider.checkIfMatchResult(headerValues(request, "If-Match",
096                provider.getLimits().getMaximumConditionalTags() + 1), current);
097    }
098
099    /** Checks original If-None-Match occurrences for application-routed GET or HEAD handling.
100     * @param provider the configured service provider
101     * @param current the authoritative current resource
102     * @param request the routed request
103     * @return the core conditional result
104     * @since 1.0.0
105     */
106    @CheckReturnValue
107    public static @NonNull ScimIfNoneMatchResult ifNoneMatchResultFor(@NonNull ScimServiceProvider provider,
108            @NonNull ScimResource current, @NonNull HttpServletRequest request) {
109        requireNonNull(provider); requireNonNull(current); requireNonNull(request);
110        return provider.checkIfNoneMatchResult(headerValues(request, "If-None-Match",
111                provider.getLimits().getMaximumConditionalTags() + 1), current);
112    }
113
114    /** Returns original Content-Type occurrences, read lazily up to the rejecting second occurrence.
115     * The list is scoped to this request; it never joins, splits or decodes header values.
116     * @param request the routed request
117     * @return the bounded original occurrences for core's header-aware body parser
118     * @since 1.0.0
119     */
120    @CheckReturnValue
121    public static @NonNull List<@NonNull String> contentTypeHeaderValuesFor(@NonNull HttpServletRequest request) {
122        return headerValues(requireNonNull(request), "Content-Type", 2);
123    }
124
125    /** Reads at most the provider's body limit plus one overflow byte without closing its stream.
126     * Overflow releases no bytes. I/O failure releases no partial bytes; interrupted reads preserve
127     * the interrupt flag. A thread already interrupted does not acquire the stream.
128     * @param provider the configured service provider supplying the body cap
129     * @param request the routed request whose body has not been consumed
130     * @return unchanged bounded bytes, an explicit size rejection, or unavailable input
131     * @since 1.0.0
132     */
133    @CheckReturnValue
134    public static @NonNull ServletScimBodyResult bodyResultFor(@NonNull ScimServiceProvider provider,
135            @NonNull HttpServletRequest request) {
136        requireNonNull(provider); requireNonNull(request);
137        if (Thread.currentThread().isInterrupted()) return ServletScimBodyResult.Unavailable.INSTANCE;
138        int cap = provider.getLimits().getMaximumBodyBytes();
139        try {
140            byte[] bytes = request.getInputStream().readNBytes(cap + 1);
141            if (Thread.currentThread().isInterrupted()) return ServletScimBodyResult.Unavailable.INSTANCE;
142            return bytes.length > cap
143                    ? new ServletScimBodyResult.Rejected(ScimError.requestTooLargeInstance())
144                    : new ServletScimBodyResult.Read(bytes);
145        } catch (InterruptedIOException failure) {
146            if (!(failure instanceof SocketTimeoutException)) Thread.currentThread().interrupt();
147            return ServletScimBodyResult.Unavailable.INSTANCE;
148        } catch (IOException failure) {
149            return ServletScimBodyResult.Unavailable.INSTANCE;
150        }
151    }
152
153    /** Writes exact prepared status, physical header values and personal-data body bytes.
154     * Call only after confirmed persistence for writes. No flushing, stream closing, URL rewriting
155     * or JSON marshalling is performed. The application owns HEAD suppression where applicable.
156     * @param response the application-owned transport response
157     * @param prepared the core-prepared bounded response
158     * @throws IOException if the Servlet output stream fails
159     * @since 1.0.0
160     */
161    public static void writeResponse(@NonNull HttpServletResponse response, @NonNull ScimResponse prepared)
162            throws IOException {
163        requireNonNull(response); requireNonNull(prepared);
164        response.setStatus(prepared.getStatusCode());
165        for (Map.Entry<String, List<String>> header : prepared.getHeaders().entrySet()) {
166            boolean first = true;
167            for (String value : header.getValue()) {
168                if (first) response.setHeader(header.getKey(), value);
169                else response.addHeader(header.getKey(), value);
170                first = false;
171            }
172        }
173        byte[] bytes = prepared.toHttpBodyWithPersonalData();
174        if (bytes.length != 0) response.getOutputStream().write(bytes);
175    }
176
177    private static @NonNull List<@NonNull String> headerValues(@NonNull HttpServletRequest request,
178            @NonNull String name, int maximumOccurrences) {
179        return new HeaderValues(request, name, maximumOccurrences);
180    }
181
182    /** A request-scoped list that stops enumeration as soon as excess occurrences guarantee rejection. */
183    private static final class HeaderValues extends AbstractList<@NonNull String> {
184        private final @NonNull HttpServletRequest request;
185        private final @NonNull String name;
186        private final int maximumOccurrences;
187        private @Nullable List<@NonNull String> snapshot;
188        private HeaderValues(@NonNull HttpServletRequest request, @NonNull String name, int maximumOccurrences) {
189            this.request = request; this.name = name; this.maximumOccurrences = maximumOccurrences;
190        }
191        private @NonNull List<@NonNull String> snapshot() {
192            List<String> current = snapshot;
193            if (current != null) return current;
194            List<String> values = new ArrayList<>();
195            Enumeration<String> original = request.getHeaders(name);
196            if (original != null) while (values.size() < maximumOccurrences && original.hasMoreElements())
197                values.add(requireNonNull(original.nextElement()));
198            current = List.copyOf(values);
199            snapshot = current;
200            return current;
201        }
202        @Override public int size() { return snapshot().size(); }
203        @Override public @NonNull String get(int index) { return snapshot().get(index); }
204    }
205}