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.oidc;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import com.revetsec.internal.http.Deadline;
021import com.revetsec.internal.oauth.OidcTransactionAccess;
022import com.revetsec.jose.JwtClaims;
023import com.revetsec.oauth.OAuthException;
024import org.jspecify.annotations.NonNull;
025import org.jspecify.annotations.Nullable;
026import javax.annotation.concurrent.ThreadSafe;
027import java.time.Clock;
028import java.time.Duration;
029import java.time.Instant;
030import java.util.function.Predicate;
031import static java.util.Objects.requireNonNull;
032
033/**
034 * Exact issuer validation or the fixed Microsoft Entra common/organizations v2.0 trust policy.
035 * The application predicate sees only signature-authenticated lowercase tenant GUIDs. It must be fast,
036 * thread-safe and cooperative: it runs synchronously on the caller's thread and cannot be preempted.
037 * Sharing keys across Entra clients requires the same policy instance; distinct predicates are not equivalent.
038 * Consumer tenants use the same rule; deny them unless consumer accounts are intended. Hosted behavior is unproven.
039 * @author <a href="https://www.revetkn.com">Mark Allen</a>
040 * @since 1.0.0
041 */
042@ThreadSafe
043@CheckReturnValue
044public final class OidcIssuerPolicy {
045        static final String PREFIX = "https://login.microsoftonline.com/";
046        static final String SUFFIX = "/v2.0";
047        static final String TEMPLATE = PREFIX + "{tenantid}" + SUFFIX;
048        private static final OidcIssuerPolicy EXACT = new OidcIssuerPolicy(null);
049        private final @Nullable Predicate<@NonNull String> allowedTenant;
050        private OidcIssuerPolicy(@Nullable Predicate<@NonNull String> allowedTenant) { this.allowedTenant = allowedTenant; }
051        /**
052         * Returns the default exact issuer policy, with no tenant callback.
053         * @return exact issuer policy
054         * @since 1.0.0
055         */
056        public static @NonNull OidcIssuerPolicy exactInstance() { return EXACT; }
057        /**
058         * Selects only the fixed public-cloud common/organizations v2.0 issuer template.
059         * The callback is never called by build, metadata parsing or restored session references.
060         * False rejects the tenant; a throwing callback produces a fixed configuration failure without its cause.
061         * @param allowedTenant trusted application decision for a verified lowercase tenant GUID
062         * @return selected policy; share this same instance when sharing common keys
063         * @throws NullPointerException if the predicate is null
064         * @since 1.0.0
065         */
066        public static @NonNull OidcIssuerPolicy fromMicrosoftEntraMultiTenant(@NonNull Predicate<@NonNull String> allowedTenant) {
067                return new OidcIssuerPolicy(requireNonNull(allowedTenant));
068        }
069        boolean isMicrosoftEntra() { return this.allowedTenant != null; }
070        void checkConfiguredIssuer(@NonNull String issuer) {
071                if (isMicrosoftEntra() && !issuer.equals(PREFIX + "common" + SUFFIX) && !issuer.equals(PREFIX + "organizations" + SUFFIX))
072                        throw new IllegalArgumentException("The Entra policy requires a fixed common or organizations v2.0 issuer.");
073        }
074        void checkMetadata(@NonNull OidcProviderMetadata metadata) {
075                checkConfiguredIssuer(metadata.getIssuer());
076                if (!metadata.getIssuer().equals(metadata.getAdvertisedIssuer()) && (!isMicrosoftEntra() || !TEMPLATE.equals(metadata.getAdvertisedIssuer())))
077                        throw new IllegalArgumentException("The provider metadata requires the selected Entra issuer policy.");
078        }
079        static @Nullable String tenantFromIssuer(@NonNull String issuer) {
080                if (issuer.length() != PREFIX.length() + 36 + SUFFIX.length() || !issuer.startsWith(PREFIX) || !issuer.endsWith(SUFFIX)) return null;
081                String value = issuer.substring(PREFIX.length(), issuer.length() - SUFFIX.length());
082                if (value.length() != 36) return null;
083                for (int index = 0; index < value.length(); index++) {
084                        char character = value.charAt(index);
085                        boolean dash = index == 8 || index == 13 || index == 18 || index == 23;
086                        if (dash ? character != '-' : !((character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'))) return null;
087                }
088                return value;
089        }
090        void checkTenant(@NonNull String tenant, @Nullable Deadline deadline) {
091                checkDeadline(deadline);
092                if (Thread.currentThread().isInterrupted()) throw OidcTransactionAccess.get().endpointFailure(OAuthException.Reason.INTERRUPTED);
093                boolean allowed;
094                try { allowed = requireNonNull(this.allowedTenant).test(tenant); }
095                catch (VirtualMachineError fatal) { throw fatal; }
096                catch (RuntimeException | Error unavailable) { throw OidcTransactionAccess.get().endpointFailure(OAuthException.Reason.ISSUER_POLICY_UNAVAILABLE); }
097                checkDeadline(deadline);
098                if (Thread.currentThread().isInterrupted()) throw OidcTransactionAccess.get().endpointFailure(OAuthException.Reason.INTERRUPTED);
099                if (!allowed) throw OidcValidationException.fromReason(OidcValidationException.Reason.TENANT_NOT_ALLOWED);
100        }
101        static void checkDeadline(@Nullable Deadline deadline) {
102                if (deadline != null && deadline.remainingNanos() <= 0)
103                        throw OidcTransactionAccess.get().endpointFailure(OAuthException.Reason.NETWORK_FAILURE);
104        }
105        static @NonNull Instant readClock(@NonNull Clock clock) {
106                try { return requireNonNull(clock.instant()); }
107                catch (VirtualMachineError fatal) { throw fatal; }
108                catch (RuntimeException | Error invalid) { throw OidcTransactionAccess.get().endpointFailure(OAuthException.Reason.ISSUER_POLICY_UNAVAILABLE); }
109        }
110        static void checkTime(@NonNull JwtClaims claims, @NonNull Instant now, @NonNull Instant verifiedAt, @NonNull Duration skew) {
111                if (now.isBefore(verifiedAt)) throw OidcTransactionAccess.get().endpointFailure(OAuthException.Reason.ISSUER_POLICY_UNAVAILABLE);
112                if (!now.isBefore(claims.getExpiresAt().orElseThrow().plus(skew)))
113                        throw OidcValidationException.fromReason(OidcValidationException.Reason.EXPIRED);
114        }
115        /**
116         * Redacts the application predicate and tenant policy contents.
117         * @return redacted policy description
118         * @since 1.0.0
119         */
120        @Override public @NonNull String toString() { return "OidcIssuerPolicy{configuration=<redacted>}"; }
121}