001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.auth.oauth.flow;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.io.*;
022import java.time.*;
023import java.util.*;
024import java.util.function.*;
025
026import com.nimbusds.oauth2.sdk.*;
027import com.nimbusds.oauth2.sdk.http.*;
028
029/**
030 * Helpers shared across all flow types.
031 *
032 * <p>
033 * Centralizes the Nimbus {@code TokenRequest}-to-{@code OAuthToken} round-trip plus the standard error mapping.
034 *
035 * @since 10.0.0
036 */
037public final class Flows {
038
039   /** Default connect/read timeout applied to every token-endpoint request when the caller sets none. */
040   static final Duration DEFAULT_HTTP_TIMEOUT = Duration.ofSeconds(10);
041
042   /** Lifetime assumed for an access token when the token endpoint returns no usable {@code expires_in}. */
043   static final Duration DEFAULT_TOKEN_LIFETIME = Duration.ofMinutes(5);
044
045   private Flows() {}
046
047   /**
048    * Sends the supplied {@link TokenRequest} via Nimbus's HTTP client and maps the response to
049    * {@link OAuthToken}.
050    *
051    * <p>
052    * A finite connect/read timeout is applied BEFORE the caller's {@code httpConfigurator} runs, so an unresponsive
053    * IdP can never wedge the call indefinitely while still letting callers override the value.
054    *
055    * @param req The Nimbus {@code TokenRequest}.  Never {@code null}.
056    * @param timeout The connect/read timeout.  {@code null} selects {@link #DEFAULT_HTTP_TIMEOUT}.
057    * @param httpConfigurator Optional pre-send hook on the {@link HTTPRequest}.
058    * @return The acquired token.
059    * @throws OAuthFlowException If the IdP returns an error or the HTTP round-trip fails.
060    */
061   public static OAuthToken send(TokenRequest req, Duration timeout, Consumer<HTTPRequest> httpConfigurator) {
062      var http = req.toHTTPRequest();
063      applyTimeout(http, timeout);
064      if (httpConfigurator != null)
065         httpConfigurator.accept(http);
066      HTTPResponse httpResp;
067      try {
068         httpResp = http.send();
069      } catch (IOException e) {
070         throw new OAuthFlowException("OAuth token endpoint HTTP call failed", e);
071      }
072      TokenResponse resp;
073      try {
074         resp = TokenResponse.parse(httpResp);
075      } catch (ParseException e) {
076         throw new OAuthFlowException("OAuth token-endpoint response could not be parsed", e);
077      }
078      if (!resp.indicatesSuccess()) {
079         var err = resp.toErrorResponse().getErrorObject();
080         var code = (err == null || err.getCode() == null) ? "unknown_error" : err.getCode();
081         throw new OAuthFlowException("OAuth token endpoint error: " + code, code);
082      }
083      return toOAuthToken(resp.toSuccessResponse());
084   }
085
086   /**
087    * Applies a finite connect/read timeout to a Nimbus {@link HTTPRequest} (Nimbus defaults to infinite).
088    *
089    * @param http The request.  Never {@code null}.
090    * @param timeout The timeout.  {@code null} selects {@link #DEFAULT_HTTP_TIMEOUT}.
091    */
092   static void applyTimeout(HTTPRequest http, Duration timeout) {
093      var t = timeout == null ? DEFAULT_HTTP_TIMEOUT : timeout;
094      var ms = (int) Math.min(t.toMillis(), Integer.MAX_VALUE);
095      http.setConnectTimeout(ms);
096      http.setReadTimeout(ms);
097      http.setFollowRedirects(false); // token requests carry credentials; a redirect must not be followed
098   }
099
100   private static OAuthToken toOAuthToken(AccessTokenResponse success) {
101      var tokens = success.getTokens();
102      var access = tokens.getAccessToken();
103      String tokenType = access.getType() != null ? access.getType().getValue() : "Bearer"; // HTT: null branch unreachable; Nimbus AccessToken always has a non-null AccessTokenType
104      Instant expiresAt = computeExpiry(access);
105      Optional<String> refreshToken = tokens.getRefreshToken() != null
106         ? o(tokens.getRefreshToken().getValue())
107         : oe();
108      Optional<Set<String>> scope = access.getScope() != null
109         ? o(new LinkedHashSet<>(access.getScope().toStringList()))
110         : oe();
111      Optional<String> idToken = oe();
112      var custom = success.getCustomParameters();
113      var v = custom.get("id_token");
114      if (v instanceof String v2)
115         idToken = o(v2);
116      return new OAuthToken(access.getValue(), tokenType, expiresAt, refreshToken, scope, idToken);
117   }
118
119   private static Instant computeExpiry(com.nimbusds.oauth2.sdk.token.AccessToken access) {
120      var lifetime = access.getLifetime();
121      if (lifetime <= 0L)
122         return Instant.now().plus(DEFAULT_TOKEN_LIFETIME);
123      return Instant.now().plusSeconds(lifetime);
124   }
125}