001/*
002 * Copyright 2022-2025 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 javax.annotation.Nonnull;
020import javax.annotation.Nullable;
021import javax.annotation.concurrent.ThreadSafe;
022import java.util.Map;
023import java.util.Objects;
024import java.util.Optional;
025import java.util.Set;
026
027import static com.soklet.Utilities.trimAggressivelyToEmpty;
028import static com.soklet.Utilities.trimAggressivelyToNull;
029import static java.util.Objects.requireNonNull;
030
031/**
032 * Encapsulates <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">non-preflight CORS</a> HTTP request data.
033 * <p>
034 * Data for <a href="https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request">preflight</a> requests is represented by {@link CorsPreflight}.
035 * <p>
036 * Instances can be acquired via these factory methods:
037 * <ul>
038 *   <li>{@link #withOrigin(HttpMethod, String)} (uses {@code Origin} header value)</li>
039 *   <li>{@link #fromHeaders(HttpMethod, Map)} (parses raw headers)</li>
040 * </ul>
041 * <p>
042 * See <a href="https://www.soklet.com/docs/cors">https://www.soklet.com/docs/cors</a> for detailed documentation.
043 *
044 * @author <a href="https://www.revetkn.com">Mark Allen</a>
045 */
046@ThreadSafe
047public final class Cors {
048        @Nullable
049        private final HttpMethod httpMethod;
050        @Nonnull
051        private final String origin;
052
053        /**
054         * Acquires a CORS <strong>non-preflight</strong> request representation for the given HTTP request data.
055         *
056         * @param httpMethod the request's HTTP method
057         * @param origin     HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin">{@code Origin}</a> request header value
058         * @return a {@link Cors} instance
059         */
060        @Nonnull
061        public static Cors withOrigin(@Nonnull HttpMethod httpMethod,
062                                                                                                                                @Nonnull String origin) {
063                requireNonNull(httpMethod);
064                requireNonNull(origin);
065
066                return new Cors(httpMethod, origin);
067        }
068
069        /**
070         * Extracts a CORS <strong>non-preflight</strong> request representation from the given HTTP request data.
071         *
072         * @param httpMethod the request's HTTP method
073         * @param headers    the request headers
074         * @return the CORS non-preflight data for this request, or {@link Optional#empty()} if insufficent data is present
075         */
076        @Nonnull
077        public static Optional<Cors> fromHeaders(@Nonnull HttpMethod httpMethod,
078                                                                                                                                                                         @Nonnull Map<String, Set<String>> headers) {
079                requireNonNull(httpMethod);
080                requireNonNull(headers);
081
082                Set<String> originHeaderValues = headers.entrySet().stream()
083                                .filter(e -> e.getKey() != null && "origin".equalsIgnoreCase(trimAggressivelyToEmpty(e.getKey())))
084                                .map(Map.Entry::getValue)
085                                .filter(Objects::nonNull)
086                                .findFirst()
087                                .orElse(null);
088
089                if (originHeaderValues == null || originHeaderValues.size() == 0)
090                        return Optional.empty();
091
092                String originHeaderValue = trimAggressivelyToNull(originHeaderValues.stream().findFirst().orElse(null));
093
094                if (originHeaderValue == null)
095                        return Optional.empty();
096
097                return Optional.of(new Cors(httpMethod, originHeaderValue));
098        }
099
100        private Cors(@Nonnull HttpMethod httpMethod,
101                                                         @Nonnull String origin) {
102                requireNonNull(httpMethod);
103                requireNonNull(origin);
104
105                this.httpMethod = httpMethod;
106                this.origin = origin;
107        }
108
109        @Override
110        @Nonnull
111        public String toString() {
112                return String.format("%s{httpMethod=%s, origin=%s}", getClass().getSimpleName(), getHttpMethod().name(), getOrigin());
113        }
114
115        @Override
116        public boolean equals(@Nullable Object object) {
117                if (this == object)
118                        return true;
119
120                if (!(object instanceof Cors cors))
121                        return false;
122
123                return Objects.equals(getHttpMethod(), cors.getHttpMethod())
124                                && Objects.equals(getOrigin(), cors.getOrigin());
125        }
126
127        @Override
128        public int hashCode() {
129                return Objects.hash(getHttpMethod(), getOrigin());
130        }
131
132        /**
133         * The HTTP method for this request.
134         *
135         * @return the HTTP method
136         */
137        @Nullable
138        public HttpMethod getHttpMethod() {
139                return this.httpMethod;
140        }
141
142        /**
143         * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin">{@code Origin}</a> header value for this request.
144         *
145         * @return the header value
146         */
147        @Nonnull
148        public String getOrigin() {
149                return this.origin;
150        }
151}