001/*
002 * Copyright 2022-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 */
016
017package com.soklet;
018
019import org.jspecify.annotations.NonNull;
020import org.jspecify.annotations.Nullable;
021
022import javax.annotation.concurrent.NotThreadSafe;
023import javax.annotation.concurrent.ThreadSafe;
024import java.net.InetSocketAddress;
025import java.nio.ByteBuffer;
026import java.util.Arrays;
027import java.util.Objects;
028import java.util.Optional;
029
030import static java.util.Objects.requireNonNull;
031
032/**
033 * Immutable snapshot of incoming bytes rejected by a server before a valid
034 * {@link Request} could be constructed.
035 * <p>
036 * The built-in HTTP and SSE transports retain at most 64 KiB of wire input
037 * attributed to the rejected request through its rejection boundary. For parsing
038 * failures this is the parser-proven boundary; for a partial read timeout it is
039 * the end of the received input. HTTP validation failures after parsing (such as
040 * invalid URI encoding or body decompression failures) report the observed wire
041 * count with an empty capture and a truncated flag, without retaining another
042 * raw copy of every successfully parsed request.
043 * {@link #getObservedByteCount()} reports the number of attributed bytes through
044 * that boundary, while {@link #isCaptureTruncated()} indicates whether the
045 * retained prefix omits any of those bytes. Bytes already read from the socket
046 * beyond the boundary are not counted because they might belong to a pipelined
047 * request. Captured bytes are untrusted and may contain credentials or other
048 * sensitive values; applications should apply their own redaction and retention
049 * policies before logging or storing them.
050 * <p>
051 * Diagnostic rendering intentionally omits both captured bytes and the remote
052 * address.
053 *
054 * @author <a href="https://www.revetkn.com">Mark Allen</a>
055 */
056@ThreadSafe
057public final class UnparsedRequest {
058        @NonNull
059        private final ServerType serverType;
060        @NonNull
061        private final UnparsedRequestReason reason;
062        @Nullable
063        private final InetSocketAddress remoteAddress;
064        private final byte @NonNull [] capturedBytes;
065        @NonNull
066        private final Long observedByteCount;
067        @NonNull
068        private final Boolean captureTruncated;
069
070        /**
071         * Acquires a builder for an unparsed request.
072         *
073         * @param serverType the type of server that rejected the incoming bytes
074         * @param reason the typed reason no valid request could be constructed
075         * @return an unparsed-request builder
076         * @throws NullPointerException if an argument is {@code null}
077         */
078        @NonNull
079        public static Builder withServerTypeAndReason(
080                        @NonNull ServerType serverType,
081                        @NonNull UnparsedRequestReason reason) {
082                return new Builder(serverType, reason);
083        }
084
085        private UnparsedRequest(@NonNull Builder builder) {
086                Builder exactBuilder = requireNonNull(builder);
087                this.serverType = exactBuilder.serverType;
088                this.reason = exactBuilder.reason;
089                this.remoteAddress = exactBuilder.remoteAddress;
090                this.capturedBytes = exactBuilder.capturedBytes.clone();
091                this.observedByteCount = exactBuilder.observedByteCount;
092                this.captureTruncated = exactBuilder.captureTruncated;
093
094                if (this.observedByteCount < this.capturedBytes.length)
095                        throw new IllegalArgumentException(
096                                        "Observed byte count must not be smaller than the captured byte-prefix length.");
097                if (this.captureTruncated
098                                && this.observedByteCount <= this.capturedBytes.length)
099                        throw new IllegalArgumentException(
100                                        "A truncated capture must omit at least one observed byte.");
101                if (!this.captureTruncated
102                                && this.observedByteCount != this.capturedBytes.length)
103                        throw new IllegalArgumentException(
104                                        "A complete capture must contain every observed byte.");
105        }
106
107        /** @return the type of server that rejected the incoming bytes */
108        @NonNull
109        public ServerType getServerType() {
110                return this.serverType;
111        }
112
113        /** @return the typed reason no valid request could be constructed */
114        @NonNull
115        public UnparsedRequestReason getReason() {
116                return this.reason;
117        }
118
119        /**
120         * Returns the best-effort remote network address for the rejected request.
121         *
122         * @return the remote address, or {@link Optional#empty()} if unavailable
123         */
124        @NonNull
125        public Optional<@NonNull InetSocketAddress> getRemoteAddress() {
126                return Optional.ofNullable(this.remoteAddress);
127        }
128
129        /**
130         * Returns the retained prefix of exact wire bytes attributed to the rejected
131         * request through the rejection boundary.
132         * <p>
133         * Each invocation returns a fresh read-only view with position {@code 0} and
134         * no accessible backing array.
135         *
136         * @return a fresh read-only view of the captured byte prefix
137         */
138        @NonNull
139        public ByteBuffer getCapturedBytes() {
140                return ByteBuffer.wrap(this.capturedBytes).asReadOnlyBuffer();
141        }
142
143        /**
144         * Returns the number of wire bytes attributed to this rejected request through
145         * the rejection boundary. This can be larger than the number
146         * returned by
147         * {@link ByteBuffer#remaining()} on {@link #getCapturedBytes()}.
148         * <p>
149         * The value does not include bytes already read from the socket beyond that
150         * boundary because they might belong to a pipelined request.
151         *
152         * @return the attributed wire-byte count through the failure boundary
153         */
154        @NonNull
155        public Long getObservedByteCount() {
156                return this.observedByteCount;
157        }
158
159        /**
160         * Indicates whether {@link #getCapturedBytes()} is an incomplete prefix of
161         * the wire input attributed to the rejected request through its
162         * rejection boundary.
163         *
164         * @return {@code true} if captured bytes were truncated
165         */
166        @NonNull
167        public Boolean isCaptureTruncated() {
168                return this.captureTruncated;
169        }
170
171        /** @return whether all captured request components are equal */
172        @Override
173        public boolean equals(@Nullable Object other) {
174                return this == other
175                                || other instanceof UnparsedRequest request
176                                && this.serverType == request.serverType
177                                && this.reason == request.reason
178                                && Objects.equals(this.remoteAddress, request.remoteAddress)
179                                && Arrays.equals(this.capturedBytes, request.capturedBytes)
180                                && Objects.equals(this.observedByteCount,
181                                                request.observedByteCount)
182                                && Objects.equals(this.captureTruncated,
183                                                request.captureTruncated);
184        }
185
186        /** @return value-based hash code */
187        @Override
188        public int hashCode() {
189                int result = Objects.hash(this.serverType, this.reason,
190                                this.remoteAddress, this.observedByteCount,
191                                this.captureTruncated);
192                return 31 * result + Arrays.hashCode(this.capturedBytes);
193        }
194
195        /** @return diagnostic rendering that omits captured bytes and address */
196        @Override
197        @NonNull
198        public String toString() {
199                return "%s{serverType=%s, reason=%s, observedByteCount=%s, captureTruncated=%s}"
200                                .formatted(getClass().getSimpleName(), getServerType(), getReason(),
201                                                getObservedByteCount(), isCaptureTruncated());
202        }
203
204        /**
205         * Builder used to construct an immutable {@link UnparsedRequest}.
206         * <p>
207         * This class is intended for use by a single thread.
208         *
209         * @author <a href="https://www.revetkn.com">Mark Allen</a>
210         */
211        @NotThreadSafe
212        public static final class Builder {
213                @NonNull
214                private final ServerType serverType;
215                @NonNull
216                private final UnparsedRequestReason reason;
217                @Nullable
218                private InetSocketAddress remoteAddress;
219                private byte @NonNull [] capturedBytes;
220                @NonNull
221                private Long observedByteCount;
222                @NonNull
223                private Boolean captureTruncated;
224
225                private Builder(@NonNull ServerType serverType,
226                                @NonNull UnparsedRequestReason reason) {
227                        this.serverType = requireNonNull(serverType);
228                        this.reason = requireNonNull(reason);
229                        this.capturedBytes = new byte[0];
230                        this.observedByteCount = 0L;
231                        this.captureTruncated = false;
232                }
233
234                /**
235                 * Sets the best-effort remote network address. Passing {@code null}
236                 * clears any previously configured address.
237                 *
238                 * @param remoteAddress the remote address, or {@code null} if unavailable
239                 * @return this builder
240                 */
241                @NonNull
242                public Builder remoteAddress(
243                                @Nullable InetSocketAddress remoteAddress) {
244                        this.remoteAddress = remoteAddress;
245                        return this;
246                }
247
248                /**
249                 * Sets the retained prefix of exact wire bytes attributed to the rejected
250                 * request through its failure boundary. The bytes are defensively copied when
251                 * {@link #build()} is invoked.
252                 *
253                 * @param capturedBytes captured wire-byte prefix
254                 * @return this builder
255                 * @throws NullPointerException if {@code capturedBytes} is {@code null}
256                 */
257                @NonNull
258                public Builder capturedBytes(byte @NonNull [] capturedBytes) {
259                        this.capturedBytes = requireNonNull(capturedBytes);
260                        return this;
261                }
262
263                /**
264                 * Sets the number of wire bytes attributed to this rejected request through
265                 * its failure boundary.
266                 *
267                 * @param observedByteCount attributed wire-byte count through the failure
268                 * boundary
269                 * @return this builder
270                 * @throws NullPointerException if {@code observedByteCount} is {@code null}
271                 * @throws IllegalArgumentException if the count is negative
272                 */
273                @NonNull
274                public Builder observedByteCount(@NonNull Long observedByteCount) {
275                        requireNonNull(observedByteCount);
276                        if (observedByteCount < 0)
277                                throw new IllegalArgumentException(
278                                                "Observed byte count must be >= 0.");
279                        this.observedByteCount = observedByteCount;
280                        return this;
281                }
282
283                /**
284                 * Specifies whether the captured bytes are an incomplete prefix of the
285                 * wire input attributed to the rejected request through its failure boundary.
286                 *
287                 * @param captureTruncated {@code true} if the capture is incomplete
288                 * @return this builder
289                 * @throws NullPointerException if {@code captureTruncated} is {@code null}
290                 */
291                @NonNull
292                public Builder captureTruncated(@NonNull Boolean captureTruncated) {
293                        this.captureTruncated = requireNonNull(captureTruncated);
294                        return this;
295                }
296
297                /**
298                 * Builds an immutable unparsed-request snapshot.
299                 *
300                 * @return an immutable unparsed request
301                 * @throws IllegalArgumentException if captured-byte metadata is
302                 * inconsistent
303                 */
304                @NonNull
305                public UnparsedRequest build() {
306                        return new UnparsedRequest(this);
307                }
308        }
309}