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.oauth;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import com.revetsec.internal.Limits;
021import org.jspecify.annotations.NonNull;
022
023import javax.annotation.concurrent.Immutable;
024import java.util.List;
025
026import static java.util.Objects.requireNonNull;
027
028/**
029 * An unverified credential parsed from exactly one Authorization field (RFC 6750 section 2.1).
030 * Parsing grants no identity or permission. No public accessor exposes the credential; equality is reference
031 * identity and diagnostic text is redacted. Query, form and cookie credentials are not accepted here.
032 *
033 * @author <a href="https://www.revetkn.com">Mark Allen</a>
034 * @since 1.0.0
035 */
036@Immutable
037public final class BearerToken {
038        private static final int PREFIX_ALLOWANCE = 64;
039        private final @NonNull String value;
040
041        private BearerToken(@NonNull String value) { this.value = value; }
042
043        /**
044         * Parses materialized header values with a 64 KiB credential limit and a 64-byte prefix allowance,
045         * returning absent, present or malformed. Other schemes and duplicate fields are malformed, including identical
046         * duplicates. Applications must preserve duplicates or reject them at a trusted edge. A present credential
047         * remains unverified and grants no identity or permission.
048         * @param values all materialized Authorization values, preserving duplicates
049         * @return the header parsing outcome
050         * @throws NullPointerException if the list or its sole value is null
051         * @since 1.0.0
052         */
053        @CheckReturnValue
054        public static @NonNull BearerTokenResult fromAuthorizationHeaderValuesResult(@NonNull List<@NonNull String> values) {
055                return fromAuthorizationHeaderValuesResult(values, Limits.BEARER_CREDENTIAL_SIZE.getDefaultIntValue());
056        }
057
058        /**
059         * Parses one case-insensitive Bearer scheme, one to 58 ASCII spaces, and RFC 6750 b64token text.
060         * Padding is permitted only at the end. Bounds are checked before copying the credential.
061         * No raw credential appears on absent or malformed outcomes.
062         * @param values all materialized Authorization values, preserving duplicates
063         * @param maximumTokenLength credential limit from 8 KiB through 1 MiB
064         * @return the header parsing outcome
065         * @throws NullPointerException if a required argument is null
066         * @throws IllegalArgumentException if the configured limit is invalid
067         * @since 1.0.0
068         */
069        @CheckReturnValue
070        public static @NonNull BearerTokenResult fromAuthorizationHeaderValuesResult(
071                        @NonNull List<@NonNull String> values, @NonNull Integer maximumTokenLength) {
072                requireNonNull(values);
073                int maximum = Limits.BEARER_CREDENTIAL_SIZE.require(requireNonNull(maximumTokenLength));
074                if (values.isEmpty())
075                        return BearerTokenResult.fromAbsent();
076                if (values.size() != 1)
077                        return BearerTokenResult.fromMalformed();
078                String field = requireNonNull(values.get(0));
079                if (field.length() > maximum + PREFIX_ALLOWANCE || field.length() < 8)
080                        return BearerTokenResult.fromMalformed();
081                String scheme = "bearer";
082                for (int index = 0; index < scheme.length(); index++) {
083                        char c = field.charAt(index);
084                        if (c >= 'A' && c <= 'Z') c = (char) (c + ('a' - 'A'));
085                        if (c != scheme.charAt(index)) return BearerTokenResult.fromMalformed();
086                }
087                int start = scheme.length();
088                if (field.charAt(start) != ' ') return BearerTokenResult.fromMalformed();
089                while (start < field.length() && field.charAt(start) == ' ') {
090                        if (++start > PREFIX_ALLOWANCE) return BearerTokenResult.fromMalformed();
091                }
092                if (start == field.length() || field.length() - start > maximum) return BearerTokenResult.fromMalformed();
093                boolean padding = false;
094                for (int index = start; index < field.length(); index++) {
095                        char c = field.charAt(index);
096                        if (c == '=' && index > start) { padding = true; continue; }
097                        if (padding || !((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
098                                        || (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' || c == '~'
099                                        || c == '+' || c == '/')) return BearerTokenResult.fromMalformed();
100                }
101                return BearerTokenResult.fromToken(new BearerToken(field.substring(start)));
102        }
103
104        @NonNull String value() { return this.value; }
105
106        /**
107         * Returns a description containing no credential.
108         * @return the redacted description
109         * @since 1.0.0
110         */
111        @Override
112        public @NonNull String toString() { return "BearerToken{value=<redacted>}"; }
113}