src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/AuthenticationFilter.java
branchhttp-client-branch
changeset 56079 d23b02f37fce
parent 56078 6c11b48a0695
child 56080 64846522c0d5
equal deleted inserted replaced
56078:6c11b48a0695 56079:d23b02f37fce
     1 /*
       
     2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 package jdk.incubator.http;
       
    27 
       
    28 import java.io.IOException;
       
    29 import java.net.MalformedURLException;
       
    30 import java.net.PasswordAuthentication;
       
    31 import java.net.URI;
       
    32 import java.net.InetSocketAddress;
       
    33 import java.net.URISyntaxException;
       
    34 import java.net.URL;
       
    35 import java.util.Base64;
       
    36 import java.util.LinkedList;
       
    37 import java.util.List;
       
    38 import java.util.Objects;
       
    39 import java.util.WeakHashMap;
       
    40 
       
    41 import jdk.incubator.http.internal.common.Log;
       
    42 import jdk.incubator.http.internal.common.Utils;
       
    43 import static java.net.Authenticator.RequestorType.PROXY;
       
    44 import static java.net.Authenticator.RequestorType.SERVER;
       
    45 import static java.nio.charset.StandardCharsets.ISO_8859_1;
       
    46 
       
    47 /**
       
    48  * Implementation of Http Basic authentication.
       
    49  */
       
    50 class AuthenticationFilter implements HeaderFilter {
       
    51     volatile MultiExchange<?> exchange;
       
    52     private static final Base64.Encoder encoder = Base64.getEncoder();
       
    53 
       
    54     static final int DEFAULT_RETRY_LIMIT = 3;
       
    55 
       
    56     static final int retry_limit = Utils.getIntegerNetProperty(
       
    57             "jdk.httpclient.auth.retrylimit", DEFAULT_RETRY_LIMIT);
       
    58 
       
    59     static final int UNAUTHORIZED = 401;
       
    60     static final int PROXY_UNAUTHORIZED = 407;
       
    61 
       
    62     private static final List<String> BASIC_DUMMY =
       
    63             List.of("Basic " + Base64.getEncoder()
       
    64                     .encodeToString("o:o".getBytes(ISO_8859_1)));
       
    65 
       
    66     // A public no-arg constructor is required by FilterFactory
       
    67     public AuthenticationFilter() {}
       
    68 
       
    69     private PasswordAuthentication getCredentials(String header,
       
    70                                                   boolean proxy,
       
    71                                                   HttpRequestImpl req)
       
    72         throws IOException
       
    73     {
       
    74         HttpClientImpl client = exchange.client();
       
    75         java.net.Authenticator auth =
       
    76                 client.authenticator()
       
    77                       .orElseThrow(() -> new IOException("No authenticator set"));
       
    78         URI uri = req.uri();
       
    79         HeaderParser parser = new HeaderParser(header);
       
    80         String authscheme = parser.findKey(0);
       
    81 
       
    82         String realm = parser.findValue("realm");
       
    83         java.net.Authenticator.RequestorType rtype = proxy ? PROXY : SERVER;
       
    84         URL url = toURL(uri, req.method(), proxy);
       
    85 
       
    86         // needs to be instance method in Authenticator
       
    87         return auth.requestPasswordAuthenticationInstance(uri.getHost(),
       
    88                                                           null,
       
    89                                                           uri.getPort(),
       
    90                                                           uri.getScheme(),
       
    91                                                           realm,
       
    92                                                           authscheme,
       
    93                                                           url,
       
    94                                                           rtype
       
    95         );
       
    96     }
       
    97 
       
    98     private URL toURL(URI uri, String method, boolean proxy)
       
    99             throws MalformedURLException
       
   100     {
       
   101         if (proxy && "CONNECT".equalsIgnoreCase(method)
       
   102                 && "socket".equalsIgnoreCase(uri.getScheme())) {
       
   103             return null; // proxy tunneling
       
   104         }
       
   105         return uri.toURL();
       
   106     }
       
   107 
       
   108     private URI getProxyURI(HttpRequestImpl r) {
       
   109         InetSocketAddress proxy = r.proxy();
       
   110         if (proxy == null) {
       
   111             return null;
       
   112         }
       
   113 
       
   114         // our own private scheme for proxy URLs
       
   115         // eg. proxy.http://host:port/
       
   116         String scheme = "proxy." + r.uri().getScheme();
       
   117         try {
       
   118             return new URI(scheme,
       
   119                            null,
       
   120                            proxy.getHostString(),
       
   121                            proxy.getPort(),
       
   122                            null,
       
   123                            null,
       
   124                            null);
       
   125         } catch (URISyntaxException e) {
       
   126             throw new InternalError(e);
       
   127         }
       
   128     }
       
   129 
       
   130     @Override
       
   131     public void request(HttpRequestImpl r, MultiExchange<?> e) throws IOException {
       
   132         // use preemptive authentication if an entry exists.
       
   133         Cache cache = getCache(e);
       
   134         this.exchange = e;
       
   135 
       
   136         // Proxy
       
   137         if (exchange.proxyauth == null) {
       
   138             URI proxyURI = getProxyURI(r);
       
   139             if (proxyURI != null) {
       
   140                 CacheEntry ca = cache.get(proxyURI, true);
       
   141                 if (ca != null) {
       
   142                     exchange.proxyauth = new AuthInfo(true, ca.scheme, null, ca);
       
   143                     addBasicCredentials(r, true, ca.value);
       
   144                 }
       
   145             }
       
   146         }
       
   147 
       
   148         // Server
       
   149         if (exchange.serverauth == null) {
       
   150             CacheEntry ca = cache.get(r.uri(), false);
       
   151             if (ca != null) {
       
   152                 exchange.serverauth = new AuthInfo(true, ca.scheme, null, ca);
       
   153                 addBasicCredentials(r, false, ca.value);
       
   154             }
       
   155         }
       
   156     }
       
   157 
       
   158     // TODO: refactor into per auth scheme class
       
   159     private static void addBasicCredentials(HttpRequestImpl r,
       
   160                                             boolean proxy,
       
   161                                             PasswordAuthentication pw) {
       
   162         String hdrname = proxy ? "Proxy-Authorization" : "Authorization";
       
   163         StringBuilder sb = new StringBuilder(128);
       
   164         sb.append(pw.getUserName()).append(':').append(pw.getPassword());
       
   165         String s = encoder.encodeToString(sb.toString().getBytes(ISO_8859_1));
       
   166         String value = "Basic " + s;
       
   167         if (proxy) {
       
   168             if (r.isConnect()) {
       
   169                 if (!Utils.PROXY_TUNNEL_FILTER
       
   170                         .test(hdrname, List.of(value))) {
       
   171                     Log.logError("{0} disabled", hdrname);
       
   172                     return;
       
   173                 }
       
   174             } else if (r.proxy() != null) {
       
   175                 if (!Utils.PROXY_FILTER
       
   176                         .test(hdrname, List.of(value))) {
       
   177                     Log.logError("{0} disabled", hdrname);
       
   178                     return;
       
   179                 }
       
   180             }
       
   181         }
       
   182         r.setSystemHeader(hdrname, value);
       
   183     }
       
   184 
       
   185     // Information attached to a HttpRequestImpl relating to authentication
       
   186     static class AuthInfo {
       
   187         final boolean fromcache;
       
   188         final String scheme;
       
   189         int retries;
       
   190         PasswordAuthentication credentials; // used in request
       
   191         CacheEntry cacheEntry; // if used
       
   192 
       
   193         AuthInfo(boolean fromcache,
       
   194                  String scheme,
       
   195                  PasswordAuthentication credentials) {
       
   196             this.fromcache = fromcache;
       
   197             this.scheme = scheme;
       
   198             this.credentials = credentials;
       
   199             this.retries = 1;
       
   200         }
       
   201 
       
   202         AuthInfo(boolean fromcache,
       
   203                  String scheme,
       
   204                  PasswordAuthentication credentials,
       
   205                  CacheEntry ca) {
       
   206             this(fromcache, scheme, credentials);
       
   207             assert credentials == null || (ca != null && ca.value == null);
       
   208             cacheEntry = ca;
       
   209         }
       
   210 
       
   211         AuthInfo retryWithCredentials(PasswordAuthentication pw) {
       
   212             // If the info was already in the cache we need to create a new
       
   213             // instance with fromCache==false so that it's put back in the
       
   214             // cache if authentication succeeds
       
   215             AuthInfo res = fromcache ? new AuthInfo(false, scheme, pw) : this;
       
   216             res.credentials = Objects.requireNonNull(pw);
       
   217             res.retries = retries;
       
   218             return res;
       
   219         }
       
   220 
       
   221     }
       
   222 
       
   223     @Override
       
   224     public HttpRequestImpl response(Response r) throws IOException {
       
   225         Cache cache = getCache(exchange);
       
   226         int status = r.statusCode();
       
   227         HttpHeaders hdrs = r.headers();
       
   228         HttpRequestImpl req = r.request();
       
   229 
       
   230         if (status != UNAUTHORIZED && status != PROXY_UNAUTHORIZED) {
       
   231             // check if any authentication succeeded for first time
       
   232             if (exchange.serverauth != null && !exchange.serverauth.fromcache) {
       
   233                 AuthInfo au = exchange.serverauth;
       
   234                 cache.store(au.scheme, req.uri(), false, au.credentials);
       
   235             }
       
   236             if (exchange.proxyauth != null && !exchange.proxyauth.fromcache) {
       
   237                 AuthInfo au = exchange.proxyauth;
       
   238                 cache.store(au.scheme, req.uri(), false, au.credentials);
       
   239             }
       
   240             return null;
       
   241         }
       
   242 
       
   243         boolean proxy = status == PROXY_UNAUTHORIZED;
       
   244         String authname = proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
       
   245         String authval = hdrs.firstValue(authname).orElseThrow(() -> {
       
   246             return new IOException("Invalid auth header");
       
   247         });
       
   248         HeaderParser parser = new HeaderParser(authval);
       
   249         String scheme = parser.findKey(0);
       
   250 
       
   251         // TODO: Need to generalise from Basic only. Delegate to a provider class etc.
       
   252 
       
   253         if (!scheme.equalsIgnoreCase("Basic")) {
       
   254             return null;   // error gets returned to app
       
   255         }
       
   256 
       
   257         if (proxy) {
       
   258             if (r.isConnectResponse) {
       
   259                 if (!Utils.PROXY_TUNNEL_FILTER
       
   260                         .test("Proxy-Authorization", BASIC_DUMMY)) {
       
   261                     Log.logError("{0} disabled", "Proxy-Authorization");
       
   262                     return null;
       
   263                 }
       
   264             } else if (req.proxy() != null) {
       
   265                 if (!Utils.PROXY_FILTER
       
   266                         .test("Proxy-Authorization", BASIC_DUMMY)) {
       
   267                     Log.logError("{0} disabled", "Proxy-Authorization");
       
   268                     return null;
       
   269                 }
       
   270             }
       
   271         }
       
   272 
       
   273         AuthInfo au = proxy ? exchange.proxyauth : exchange.serverauth;
       
   274         if (au == null) {
       
   275             // if no authenticator, let the user deal with 407/401
       
   276             if (!exchange.client().authenticator().isPresent()) return null;
       
   277 
       
   278             PasswordAuthentication pw = getCredentials(authval, proxy, req);
       
   279             if (pw == null) {
       
   280                 throw new IOException("No credentials provided");
       
   281             }
       
   282             // No authentication in request. Get credentials from user
       
   283             au = new AuthInfo(false, "Basic", pw);
       
   284             if (proxy) {
       
   285                 exchange.proxyauth = au;
       
   286             } else {
       
   287                 exchange.serverauth = au;
       
   288             }
       
   289             addBasicCredentials(req, proxy, pw);
       
   290             return req;
       
   291         } else if (au.retries > retry_limit) {
       
   292             throw new IOException("too many authentication attempts. Limit: " +
       
   293                     Integer.toString(retry_limit));
       
   294         } else {
       
   295             // we sent credentials, but they were rejected
       
   296             if (au.fromcache) {
       
   297                 cache.remove(au.cacheEntry);
       
   298             }
       
   299 
       
   300             // if no authenticator, let the user deal with 407/401
       
   301             if (!exchange.client().authenticator().isPresent()) return null;
       
   302 
       
   303             // try again
       
   304             PasswordAuthentication pw = getCredentials(authval, proxy, req);
       
   305             if (pw == null) {
       
   306                 throw new IOException("No credentials provided");
       
   307             }
       
   308             au = au.retryWithCredentials(pw);
       
   309             if (proxy) {
       
   310                 exchange.proxyauth = au;
       
   311             } else {
       
   312                 exchange.serverauth = au;
       
   313             }
       
   314             addBasicCredentials(req, proxy, au.credentials);
       
   315             au.retries++;
       
   316             return req;
       
   317         }
       
   318     }
       
   319 
       
   320     // Use a WeakHashMap to make it possible for the HttpClient to
       
   321     // be garbaged collected when no longer referenced.
       
   322     static final WeakHashMap<HttpClientImpl,Cache> caches = new WeakHashMap<>();
       
   323 
       
   324     static synchronized Cache getCache(MultiExchange<?> exchange) {
       
   325         HttpClientImpl client = exchange.client();
       
   326         Cache c = caches.get(client);
       
   327         if (c == null) {
       
   328             c = new Cache();
       
   329             caches.put(client, c);
       
   330         }
       
   331         return c;
       
   332     }
       
   333 
       
   334     // Note: Make sure that Cache and CacheEntry do not keep any strong
       
   335     //       reference to the HttpClient: it would prevent the client being
       
   336     //       GC'ed when no longer referenced.
       
   337     static class Cache {
       
   338         final LinkedList<CacheEntry> entries = new LinkedList<>();
       
   339 
       
   340         synchronized CacheEntry get(URI uri, boolean proxy) {
       
   341             for (CacheEntry entry : entries) {
       
   342                 if (entry.equalsKey(uri, proxy)) {
       
   343                     return entry;
       
   344                 }
       
   345             }
       
   346             return null;
       
   347         }
       
   348 
       
   349         synchronized void remove(String authscheme, URI domain, boolean proxy) {
       
   350             for (CacheEntry entry : entries) {
       
   351                 if (entry.equalsKey(domain, proxy)) {
       
   352                     entries.remove(entry);
       
   353                 }
       
   354             }
       
   355         }
       
   356 
       
   357         synchronized void remove(CacheEntry entry) {
       
   358             entries.remove(entry);
       
   359         }
       
   360 
       
   361         synchronized void store(String authscheme,
       
   362                                 URI domain,
       
   363                                 boolean proxy,
       
   364                                 PasswordAuthentication value) {
       
   365             remove(authscheme, domain, proxy);
       
   366             entries.add(new CacheEntry(authscheme, domain, proxy, value));
       
   367         }
       
   368     }
       
   369 
       
   370     static class CacheEntry {
       
   371         final String root;
       
   372         final String scheme;
       
   373         final boolean proxy;
       
   374         final PasswordAuthentication value;
       
   375 
       
   376         CacheEntry(String authscheme,
       
   377                    URI uri,
       
   378                    boolean proxy,
       
   379                    PasswordAuthentication value) {
       
   380             this.scheme = authscheme;
       
   381             this.root = uri.resolve(".").toString(); // remove extraneous components
       
   382             this.proxy = proxy;
       
   383             this.value = value;
       
   384         }
       
   385 
       
   386         public PasswordAuthentication value() {
       
   387             return value;
       
   388         }
       
   389 
       
   390         public boolean equalsKey(URI uri, boolean proxy) {
       
   391             if (this.proxy != proxy) {
       
   392                 return false;
       
   393             }
       
   394             String other = uri.toString();
       
   395             return other.startsWith(root);
       
   396         }
       
   397     }
       
   398 }