src/java.net.http/share/classes/jdk/internal/net/http/AuthenticationFilter.java
changeset 49765 ee6f7a61f3a5
parent 48083 b1c1b4ef4be2
child 50681 4254bed3c09d
child 56451 9585061fdb04
equal deleted inserted replaced
49707:f7fd051519ac 49765:ee6f7a61f3a5
       
     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.internal.net.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 import java.net.http.HttpHeaders;
       
    41 import jdk.internal.net.http.common.Log;
       
    42 import jdk.internal.net.http.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         String host;
       
    86         int port;
       
    87         String protocol;
       
    88         InetSocketAddress proxyAddress;
       
    89         if (proxy && (proxyAddress = req.proxy()) != null) {
       
    90             // request sent to server through proxy
       
    91             proxyAddress = req.proxy();
       
    92             host = proxyAddress.getHostString();
       
    93             port = proxyAddress.getPort();
       
    94             protocol = "http"; // we don't support https connection to proxy
       
    95         } else {
       
    96             // direct connection to server or proxy
       
    97             host = uri.getHost();
       
    98             port = uri.getPort();
       
    99             protocol = uri.getScheme();
       
   100         }
       
   101 
       
   102         // needs to be instance method in Authenticator
       
   103         return auth.requestPasswordAuthenticationInstance(host,
       
   104                                                           null,
       
   105                                                           port,
       
   106                                                           protocol,
       
   107                                                           realm,
       
   108                                                           authscheme,
       
   109                                                           url,
       
   110                                                           rtype
       
   111         );
       
   112     }
       
   113 
       
   114     private URL toURL(URI uri, String method, boolean proxy)
       
   115             throws MalformedURLException
       
   116     {
       
   117         if (proxy && "CONNECT".equalsIgnoreCase(method)
       
   118                 && "socket".equalsIgnoreCase(uri.getScheme())) {
       
   119             return null; // proxy tunneling
       
   120         }
       
   121         return uri.toURL();
       
   122     }
       
   123 
       
   124     private URI getProxyURI(HttpRequestImpl r) {
       
   125         InetSocketAddress proxy = r.proxy();
       
   126         if (proxy == null) {
       
   127             return null;
       
   128         }
       
   129 
       
   130         // our own private scheme for proxy URLs
       
   131         // eg. proxy.http://host:port/
       
   132         String scheme = "proxy." + r.uri().getScheme();
       
   133         try {
       
   134             return new URI(scheme,
       
   135                            null,
       
   136                            proxy.getHostString(),
       
   137                            proxy.getPort(),
       
   138                            "/",
       
   139                            null,
       
   140                            null);
       
   141         } catch (URISyntaxException e) {
       
   142             throw new InternalError(e);
       
   143         }
       
   144     }
       
   145 
       
   146     @Override
       
   147     public void request(HttpRequestImpl r, MultiExchange<?> e) throws IOException {
       
   148         // use preemptive authentication if an entry exists.
       
   149         Cache cache = getCache(e);
       
   150         this.exchange = e;
       
   151 
       
   152         // Proxy
       
   153         if (exchange.proxyauth == null) {
       
   154             URI proxyURI = getProxyURI(r);
       
   155             if (proxyURI != null) {
       
   156                 CacheEntry ca = cache.get(proxyURI, true);
       
   157                 if (ca != null) {
       
   158                     exchange.proxyauth = new AuthInfo(true, ca.scheme, null, ca);
       
   159                     addBasicCredentials(r, true, ca.value);
       
   160                 }
       
   161             }
       
   162         }
       
   163 
       
   164         // Server
       
   165         if (exchange.serverauth == null) {
       
   166             CacheEntry ca = cache.get(r.uri(), false);
       
   167             if (ca != null) {
       
   168                 exchange.serverauth = new AuthInfo(true, ca.scheme, null, ca);
       
   169                 addBasicCredentials(r, false, ca.value);
       
   170             }
       
   171         }
       
   172     }
       
   173 
       
   174     // TODO: refactor into per auth scheme class
       
   175     private static void addBasicCredentials(HttpRequestImpl r,
       
   176                                             boolean proxy,
       
   177                                             PasswordAuthentication pw) {
       
   178         String hdrname = proxy ? "Proxy-Authorization" : "Authorization";
       
   179         StringBuilder sb = new StringBuilder(128);
       
   180         sb.append(pw.getUserName()).append(':').append(pw.getPassword());
       
   181         String s = encoder.encodeToString(sb.toString().getBytes(ISO_8859_1));
       
   182         String value = "Basic " + s;
       
   183         if (proxy) {
       
   184             if (r.isConnect()) {
       
   185                 if (!Utils.PROXY_TUNNEL_FILTER
       
   186                         .test(hdrname, List.of(value))) {
       
   187                     Log.logError("{0} disabled", hdrname);
       
   188                     return;
       
   189                 }
       
   190             } else if (r.proxy() != null) {
       
   191                 if (!Utils.PROXY_FILTER
       
   192                         .test(hdrname, List.of(value))) {
       
   193                     Log.logError("{0} disabled", hdrname);
       
   194                     return;
       
   195                 }
       
   196             }
       
   197         }
       
   198         r.setSystemHeader(hdrname, value);
       
   199     }
       
   200 
       
   201     // Information attached to a HttpRequestImpl relating to authentication
       
   202     static class AuthInfo {
       
   203         final boolean fromcache;
       
   204         final String scheme;
       
   205         int retries;
       
   206         PasswordAuthentication credentials; // used in request
       
   207         CacheEntry cacheEntry; // if used
       
   208 
       
   209         AuthInfo(boolean fromcache,
       
   210                  String scheme,
       
   211                  PasswordAuthentication credentials) {
       
   212             this.fromcache = fromcache;
       
   213             this.scheme = scheme;
       
   214             this.credentials = credentials;
       
   215             this.retries = 1;
       
   216         }
       
   217 
       
   218         AuthInfo(boolean fromcache,
       
   219                  String scheme,
       
   220                  PasswordAuthentication credentials,
       
   221                  CacheEntry ca) {
       
   222             this(fromcache, scheme, credentials);
       
   223             assert credentials == null || (ca != null && ca.value == null);
       
   224             cacheEntry = ca;
       
   225         }
       
   226 
       
   227         AuthInfo retryWithCredentials(PasswordAuthentication pw) {
       
   228             // If the info was already in the cache we need to create a new
       
   229             // instance with fromCache==false so that it's put back in the
       
   230             // cache if authentication succeeds
       
   231             AuthInfo res = fromcache ? new AuthInfo(false, scheme, pw) : this;
       
   232             res.credentials = Objects.requireNonNull(pw);
       
   233             res.retries = retries;
       
   234             return res;
       
   235         }
       
   236 
       
   237     }
       
   238 
       
   239     @Override
       
   240     public HttpRequestImpl response(Response r) throws IOException {
       
   241         Cache cache = getCache(exchange);
       
   242         int status = r.statusCode();
       
   243         HttpHeaders hdrs = r.headers();
       
   244         HttpRequestImpl req = r.request();
       
   245 
       
   246         if (status != UNAUTHORIZED && status != PROXY_UNAUTHORIZED) {
       
   247             // check if any authentication succeeded for first time
       
   248             if (exchange.serverauth != null && !exchange.serverauth.fromcache) {
       
   249                 AuthInfo au = exchange.serverauth;
       
   250                 cache.store(au.scheme, req.uri(), false, au.credentials);
       
   251             }
       
   252             if (exchange.proxyauth != null && !exchange.proxyauth.fromcache) {
       
   253                 AuthInfo au = exchange.proxyauth;
       
   254                 URI proxyURI = getProxyURI(req);
       
   255                 if (proxyURI != null) {
       
   256                     cache.store(au.scheme, proxyURI, true, au.credentials);
       
   257                 }
       
   258             }
       
   259             return null;
       
   260         }
       
   261 
       
   262         boolean proxy = status == PROXY_UNAUTHORIZED;
       
   263         String authname = proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
       
   264         String authval = hdrs.firstValue(authname).orElseThrow(() -> {
       
   265             return new IOException("Invalid auth header");
       
   266         });
       
   267         HeaderParser parser = new HeaderParser(authval);
       
   268         String scheme = parser.findKey(0);
       
   269 
       
   270         // TODO: Need to generalise from Basic only. Delegate to a provider class etc.
       
   271 
       
   272         if (!scheme.equalsIgnoreCase("Basic")) {
       
   273             return null;   // error gets returned to app
       
   274         }
       
   275 
       
   276         if (proxy) {
       
   277             if (r.isConnectResponse) {
       
   278                 if (!Utils.PROXY_TUNNEL_FILTER
       
   279                         .test("Proxy-Authorization", BASIC_DUMMY)) {
       
   280                     Log.logError("{0} disabled", "Proxy-Authorization");
       
   281                     return null;
       
   282                 }
       
   283             } else if (req.proxy() != null) {
       
   284                 if (!Utils.PROXY_FILTER
       
   285                         .test("Proxy-Authorization", BASIC_DUMMY)) {
       
   286                     Log.logError("{0} disabled", "Proxy-Authorization");
       
   287                     return null;
       
   288                 }
       
   289             }
       
   290         }
       
   291 
       
   292         AuthInfo au = proxy ? exchange.proxyauth : exchange.serverauth;
       
   293         if (au == null) {
       
   294             // if no authenticator, let the user deal with 407/401
       
   295             if (!exchange.client().authenticator().isPresent()) return null;
       
   296 
       
   297             PasswordAuthentication pw = getCredentials(authval, proxy, req);
       
   298             if (pw == null) {
       
   299                 throw new IOException("No credentials provided");
       
   300             }
       
   301             // No authentication in request. Get credentials from user
       
   302             au = new AuthInfo(false, "Basic", pw);
       
   303             if (proxy) {
       
   304                 exchange.proxyauth = au;
       
   305             } else {
       
   306                 exchange.serverauth = au;
       
   307             }
       
   308             req = HttpRequestImpl.newInstanceForAuthentication(req);
       
   309             addBasicCredentials(req, proxy, pw);
       
   310             return req;
       
   311         } else if (au.retries > retry_limit) {
       
   312             throw new IOException("too many authentication attempts. Limit: " +
       
   313                     Integer.toString(retry_limit));
       
   314         } else {
       
   315             // we sent credentials, but they were rejected
       
   316             if (au.fromcache) {
       
   317                 cache.remove(au.cacheEntry);
       
   318             }
       
   319 
       
   320             // if no authenticator, let the user deal with 407/401
       
   321             if (!exchange.client().authenticator().isPresent()) return null;
       
   322 
       
   323             // try again
       
   324             PasswordAuthentication pw = getCredentials(authval, proxy, req);
       
   325             if (pw == null) {
       
   326                 throw new IOException("No credentials provided");
       
   327             }
       
   328             au = au.retryWithCredentials(pw);
       
   329             if (proxy) {
       
   330                 exchange.proxyauth = au;
       
   331             } else {
       
   332                 exchange.serverauth = au;
       
   333             }
       
   334             req = HttpRequestImpl.newInstanceForAuthentication(req);
       
   335             addBasicCredentials(req, proxy, au.credentials);
       
   336             au.retries++;
       
   337             return req;
       
   338         }
       
   339     }
       
   340 
       
   341     // Use a WeakHashMap to make it possible for the HttpClient to
       
   342     // be garbage collected when no longer referenced.
       
   343     static final WeakHashMap<HttpClientImpl,Cache> caches = new WeakHashMap<>();
       
   344 
       
   345     static synchronized Cache getCache(MultiExchange<?> exchange) {
       
   346         HttpClientImpl client = exchange.client();
       
   347         Cache c = caches.get(client);
       
   348         if (c == null) {
       
   349             c = new Cache();
       
   350             caches.put(client, c);
       
   351         }
       
   352         return c;
       
   353     }
       
   354 
       
   355     // Note: Make sure that Cache and CacheEntry do not keep any strong
       
   356     //       reference to the HttpClient: it would prevent the client being
       
   357     //       GC'ed when no longer referenced.
       
   358     static final class Cache {
       
   359         final LinkedList<CacheEntry> entries = new LinkedList<>();
       
   360 
       
   361         Cache() {}
       
   362 
       
   363         synchronized CacheEntry get(URI uri, boolean proxy) {
       
   364             for (CacheEntry entry : entries) {
       
   365                 if (entry.equalsKey(uri, proxy)) {
       
   366                     return entry;
       
   367                 }
       
   368             }
       
   369             return null;
       
   370         }
       
   371 
       
   372         synchronized void remove(String authscheme, URI domain, boolean proxy) {
       
   373             for (CacheEntry entry : entries) {
       
   374                 if (entry.equalsKey(domain, proxy)) {
       
   375                     entries.remove(entry);
       
   376                 }
       
   377             }
       
   378         }
       
   379 
       
   380         synchronized void remove(CacheEntry entry) {
       
   381             entries.remove(entry);
       
   382         }
       
   383 
       
   384         synchronized void store(String authscheme,
       
   385                                 URI domain,
       
   386                                 boolean proxy,
       
   387                                 PasswordAuthentication value) {
       
   388             remove(authscheme, domain, proxy);
       
   389             entries.add(new CacheEntry(authscheme, domain, proxy, value));
       
   390         }
       
   391     }
       
   392 
       
   393     static URI normalize(URI uri, boolean isPrimaryKey) {
       
   394         String path = uri.getPath();
       
   395         if (path == null || path.isEmpty()) {
       
   396             // make sure the URI has a path, ignore query and fragment
       
   397             try {
       
   398                 return new URI(uri.getScheme(), uri.getAuthority(), "/", null, null);
       
   399             } catch (URISyntaxException e) {
       
   400                 throw new InternalError(e);
       
   401             }
       
   402         } else if (isPrimaryKey || !"/".equals(path)) {
       
   403             // remove extraneous components and normalize path
       
   404             return uri.resolve(".");
       
   405         } else {
       
   406             // path == "/" and the URI is not used to store
       
   407             // the primary key in the cache: nothing to do.
       
   408             return uri;
       
   409         }
       
   410     }
       
   411 
       
   412     static final class CacheEntry {
       
   413         final String root;
       
   414         final String scheme;
       
   415         final boolean proxy;
       
   416         final PasswordAuthentication value;
       
   417 
       
   418         CacheEntry(String authscheme,
       
   419                    URI uri,
       
   420                    boolean proxy,
       
   421                    PasswordAuthentication value) {
       
   422             this.scheme = authscheme;
       
   423             this.root = normalize(uri, true).toString(); // remove extraneous components
       
   424             this.proxy = proxy;
       
   425             this.value = value;
       
   426         }
       
   427 
       
   428         public PasswordAuthentication value() {
       
   429             return value;
       
   430         }
       
   431 
       
   432         public boolean equalsKey(URI uri, boolean proxy) {
       
   433             if (this.proxy != proxy) {
       
   434                 return false;
       
   435             }
       
   436             String other = String.valueOf(normalize(uri, false));
       
   437             return other.startsWith(root);
       
   438         }
       
   439     }
       
   440 }