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 */
016
017package com.revetsec.soklet;
018
019import com.revetsec.oauth.AuthorizationResponse;
020import com.soklet.HttpMethod;
021import com.soklet.Request;
022import com.soklet.Response;
023import com.soklet.ResponseCookie;
024import org.jspecify.annotations.NonNull;
025
026import javax.annotation.concurrent.ThreadSafe;
027import java.net.URI;
028import java.util.AbstractList;
029import java.util.List;
030import java.util.Map;
031import java.util.Set;
032
033import static java.util.Objects.requireNonNull;
034
035/**
036 * Thin OAuth transport helpers for Soklet. Callback input remains untrusted until Revetsec core completes the
037 * authorization transaction. These helpers select no provider and make no authentication or authorization decision.
038 *
039 * @author <a href="https://www.revetkn.com">Mark Allen</a>
040 * @since 1.0.0
041 */
042@ThreadSafe
043public final class SokletOAuth {
044
045        private SokletOAuth() {
046                // Non-instantiable
047        }
048
049        /**
050         * Parses a callback using the route's GET or POST method. GET supplies the unchanged raw query; POST supplies
051         * the unchanged body, raw query and every materialized Content-Type value to core's form parser. No decoded
052         * query or form map is used. Other methods, including HEAD, return Rejected before callback input is
053         * inspected, even if Soklet discarded a body. The application selects the HTTP response (for example,
054         * a route-level 405) and must not load or consume pending login state for that rejection.
055         * This parsing grants no identity and does not validate pending transaction state.
056         * <p>
057         * Soklet 4 preserves header values as lists. Every materialized occurrence, including identical physical
058         * duplicates and differently cased names, is passed to core for ambiguity checks.
059         *
060         * @param request the application-routed callback request
061         * @return parsed, rejected or oversized callback outcome
062         * @throws NullPointerException if request is null
063         * @since 1.0.0
064         */
065        public static @NonNull SokletOAuthCallbackResult authorizationResponseResultFor(@NonNull Request request) {
066                requireNonNull(request);
067                HttpMethod method = request.getHttpMethod();
068                if (method != HttpMethod.GET && method != HttpMethod.POST)
069                        return SokletOAuthCallbackResult.fromRejected();
070                if (Boolean.TRUE.equals(request.isContentTooLarge()))
071                        return SokletOAuthCallbackResult.fromTooLarge();
072                if (method == HttpMethod.GET)
073                        return SokletOAuthCallbackResult.fromParseResult(AuthorizationResponse.fromQueryStringResult(request.getRawQuery().orElse("")));
074                return SokletOAuthCallbackResult.fromParseResult(AuthorizationResponse.fromFormBodyResult(bodyBytesFor(request),
075                                collectHeaderValues(request, "Content-Type"), request.getRawQuery().orElse(null)));
076        }
077
078        /**
079         * Builds a 302 redirect with no-store and no-referrer headers. The application supplies a trusted destination;
080         * core remains responsible for selecting and validating provider endpoints used in its authorization flow.
081         *
082         * @param location the absolute HTTP(S) destination, without userinfo or control characters
083         * @return the redirect response
084         * @throws IllegalArgumentException if location is unsafe for an HTTP redirect
085         * @throws NullPointerException if location is null
086         * @since 1.0.0
087         */
088        public static @NonNull Response redirect(@NonNull URI location) {
089                return redirect(location, Set.of());
090        }
091
092        /**
093         * Builds a 302 redirect with application-owned cookies, no-store and no-referrer headers. Cookie selection
094         * and security attributes belong to the application. The destination is not derived from request headers.
095         *
096         * @param location the absolute HTTP(S) destination, without userinfo or control characters
097         * @param cookies the application's response cookies
098         * @return the redirect response
099         * @throws IllegalArgumentException if location is unsafe for an HTTP redirect
100         * @throws NullPointerException if a required argument or cookie is null
101         * @since 1.0.0
102         */
103        public static @NonNull Response redirect(@NonNull URI location,
104                        @NonNull Set<@NonNull ResponseCookie> cookies) {
105                String value = redirectLocation(requireNonNull(location));
106                return Response.withStatusCode(302).cookies(List.copyOf(requireNonNull(cookies))).headers(Map.of(
107                                "Location", List.of(value),
108                                "Cache-Control", List.of("no-store"),
109                                "Referrer-Policy", List.of("no-referrer"))).build();
110        }
111
112        static @NonNull List<@NonNull String> collectHeaderValues(@NonNull Request request, @NonNull String name) {
113                requireNonNull(request);
114                requireNonNull(name);
115                Map<String, List<String>> fields = request.getHeaders();
116                return new AbstractList<>() {
117                        @Override public int size() {
118                                int count = 0;
119                                for (Map.Entry<String, List<String>> entry : fields.entrySet())
120                                        if (name.equalsIgnoreCase(entry.getKey())) {
121                                                int length = entry.getValue().size();
122                                                if (count > Integer.MAX_VALUE - length) return Integer.MAX_VALUE;
123                                                count += length;
124                                        }
125                                return count;
126                        }
127                        @Override public @NonNull String get(int index) {
128                                if (index < 0) throw new IndexOutOfBoundsException();
129                                for (Map.Entry<String, List<String>> entry : fields.entrySet())
130                                        if (name.equalsIgnoreCase(entry.getKey())) {
131                                                List<String> values = entry.getValue();
132                                                if (index < values.size()) return requireNonNull(values.get(index));
133                                                index -= values.size();
134                                        }
135                                throw new IndexOutOfBoundsException();
136                        }
137                };
138        }
139
140        static byte @NonNull [] bodyBytesFor(@NonNull Request request) {
141                requireNonNull(request);
142                return request.getBody().orElseGet(() -> new byte[0]);
143        }
144
145        static @NonNull String redirectLocation(@NonNull URI location) {
146                String scheme = location.getScheme();
147                if (!location.isAbsolute() || location.isOpaque() || location.getHost() == null
148                                || location.getHost().isEmpty() || location.getRawUserInfo() != null
149                                || location.getPort() < -1 || location.getPort() > 65_535
150                                || !("https".equalsIgnoreCase(scheme) || "http".equalsIgnoreCase(scheme)))
151                        throw unsafeRedirect();
152                String value = location.toASCIIString();
153                for (int index = 0; index < value.length(); index++) {
154                        char character = value.charAt(index);
155                        if (character <= 0x20 || character >= 0x7f)
156                                throw unsafeRedirect();
157                        if (character == '%' && index + 2 < value.length()) {
158                                int high = Character.digit(value.charAt(index + 1), 16);
159                                int low = Character.digit(value.charAt(index + 2), 16);
160                                int decoded = high * 16 + low;
161                                if (high >= 0 && low >= 0 && (decoded < 0x20 || decoded == 0x7f))
162                                        throw unsafeRedirect();
163                        }
164                }
165                return value;
166        }
167
168        private static @NonNull IllegalArgumentException unsafeRedirect() {
169                return new IllegalArgumentException("OAuth redirect requires a safe absolute HTTP(S) URI without userinfo");
170        }
171}