Path: blob/master/test/jdk/java/net/httpclient/FilePublisher/FilePublisherPermsTest.java
41153 views
/*1* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @bug 823545926* @summary Confirm that HttpRequest.BodyPublishers#ofFile(Path)27* works with changing permissions28* policy 1: no custom permission29* policy 2: custom permission for test classes30* policy 3: custom permission for test classes and httpclient31* @modules java.base/sun.net.www.http32* java.net.http/jdk.internal.net.http.common33* java.net.http/jdk.internal.net.http.frame34* java.net.http/jdk.internal.net.http.hpack35* jdk.httpserver36* @library /test/lib ../http2/server37* @compile ../HttpServerAdapters.java38* @build jdk.test.lib.net.SimpleSSLContext SecureZipFSProvider39* @run testng/othervm/java.security.policy=FilePublisherPermsTest1.policy FilePublisherPermsTest40* @run testng/othervm/java.security.policy=FilePublisherPermsTest2.policy FilePublisherPermsTest41* @run testng/othervm/java.security.policy=FilePublisherPermsTest3.policy FilePublisherPermsTest42*/4344import com.sun.net.httpserver.HttpServer;45import com.sun.net.httpserver.HttpsConfigurator;46import com.sun.net.httpserver.HttpsServer;47import jdk.test.lib.net.SimpleSSLContext;48import org.testng.annotations.AfterTest;49import org.testng.annotations.BeforeTest;50import org.testng.annotations.DataProvider;51import org.testng.annotations.Test;5253import javax.net.ssl.SSLContext;54import java.io.FileNotFoundException;55import java.io.FilePermission;56import java.io.IOException;57import java.io.InputStream;58import java.io.OutputStream;59import java.net.InetAddress;60import java.net.InetSocketAddress;61import java.net.URI;62import java.net.http.HttpClient;63import java.net.http.HttpRequest;64import java.net.http.HttpRequest.BodyPublisher;65import java.net.http.HttpRequest.BodyPublishers;66import java.net.http.HttpResponse;67import java.nio.file.FileSystem;68import java.nio.file.FileSystems;69import java.nio.file.Files;70import java.nio.file.Path;71import java.security.*;72import java.util.Map;7374import static java.lang.System.out;75import static java.net.http.HttpClient.Builder.NO_PROXY;76import static org.testng.Assert.assertEquals;77import static org.testng.Assert.fail;7879public class FilePublisherPermsTest implements HttpServerAdapters {8081SSLContext sslContext;82HttpServerAdapters.HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]83HttpServerAdapters.HttpTestServer httpsTestServer; // HTTPS/1.184HttpServerAdapters.HttpTestServer http2TestServer; // HTTP/2 ( h2c )85HttpServerAdapters.HttpTestServer https2TestServer; // HTTP/2 ( h2 )86String httpURI;87String httpsURI;88String http2URI;89String https2URI;9091FileSystem zipFs;92static Path zipFsPath;93static Path defaultFsPath;9495String policyFile;9697// Default file system set up98static final String DEFAULT_FS_MSG = "default fs";99100private Path defaultFsFile() throws Exception {101var file = Path.of("defaultFile.txt");102if (Files.notExists(file)) {103Files.createFile(file);104Files.writeString(file, DEFAULT_FS_MSG);105}106assertEquals(Files.readString(file), DEFAULT_FS_MSG);107return file;108}109110@DataProvider(name = "defaultFsData")111public Object[][] defaultFsData() {112return new Object[][]{113{ httpURI, defaultFsPath },114{ httpsURI, defaultFsPath },115{ http2URI, defaultFsPath },116{ https2URI, defaultFsPath },117{ httpURI, defaultFsPath },118{ httpsURI, defaultFsPath },119{ http2URI, defaultFsPath },120{ https2URI, defaultFsPath },121};122}123124@Test(dataProvider = "defaultFsData")125public void testDefaultFs(String uriString, Path path)126throws Exception {127out.printf("\n\n--- testDefaultFs(%s, %s): starting\n",128uriString, path);129130if (System.getSecurityManager() != null) {131changePerms(path.toString(), "read,write,delete");132// Should not throw133BodyPublisher bodyPublisher = BodyPublishers.ofFile(path);134// Restrict permissions135changePerms(path.toString(), "delete");136try {137BodyPublishers.ofFile(path);138fail();139} catch (SecurityException e) {140out.println("Caught expected: " + e);141}142try {143send(uriString, bodyPublisher);144fail();145} catch (SecurityException e) {146out.println("Caught expected: " + e);147}148}149}150151// Zip File system set up152static final String ZIP_FS_MSG = "zip fs";153154static FileSystem newZipFs(Path zipFile) throws Exception {155return FileSystems.newFileSystem(zipFile, Map.of("create", "true"));156}157158static FileSystem newSecureZipFs(Path zipFile) throws Exception {159FileSystem fs = newZipFs(zipFile);160return new SecureZipFSProvider(fs.provider()).newFileSystem(fs);161}162163static Path zipFsFile(FileSystem fs) throws Exception {164var file = fs.getPath("fileInZip.txt");165if (Files.notExists(file)) {166Files.createFile(file);167Files.writeString(file, ZIP_FS_MSG);168}169assertEquals(Files.readString(file), ZIP_FS_MSG);170return file;171}172173@DataProvider(name = "zipFsData")174public Object[][] zipFsData() {175return new Object[][]{176{ httpURI, zipFsPath },177{ httpsURI, zipFsPath },178{ http2URI, zipFsPath },179{ https2URI, zipFsPath },180{ httpURI, zipFsPath },181{ httpsURI, zipFsPath },182{ http2URI, zipFsPath },183{ https2URI, zipFsPath },184};185}186187@Test(dataProvider = "zipFsData")188public void testZipFs(String uriString, Path path) throws Exception {189out.printf("\n\n--- testZipFsCustomPerm(%s, %s): starting\n", uriString, path);190if (System.getSecurityManager() != null) {191changePerms(path.toString(), "read,write,delete");192193// Custom permission not sufficiently granted, expected to fail194if (!policyFile.contains("FilePublisherPermsTest3")) {195try {196BodyPublishers.ofFile(path);197fail();198} catch (SecurityException e) {199out.println("Caught expected: " + e);200return;201}202} else {203BodyPublisher bodyPublisher = BodyPublishers.ofFile(path);204send(uriString, bodyPublisher);205// Restrict permissions206changePerms(path.toString(), "delete");207try {208BodyPublishers.ofFile(path);209fail();210} catch (SecurityException e) {211out.println("Caught expected: " + e);212}213try {214send(uriString, bodyPublisher);215fail();216} catch (SecurityException e) {217out.println("Caught expected: " + e);218}219}220}221}222223@Test224public void testFileNotFound() throws Exception {225out.printf("\n\n--- testFileNotFound(): starting\n");226var zipPath = Path.of("fileNotFound.zip");227changePerms(zipPath.toString(), "read,write,delete");228try (FileSystem fs = newZipFs(zipPath)) {229Path fileInZip = zipFsFile(fs);230Files.deleteIfExists(fileInZip);231BodyPublishers.ofFile(fileInZip);232fail();233} catch (FileNotFoundException e) {234out.println("Caught expected: " + e);235}236var path = Path.of("fileNotFound.txt");237changePerms(path.toString(), "read,write,delete");238try {239Files.deleteIfExists(path);240BodyPublishers.ofFile(path);241fail();242} catch (FileNotFoundException e) {243out.println("Caught expected: " + e);244}245}246247private void send(String uriString, BodyPublisher bodyPublisher)248throws Exception {249HttpClient client = HttpClient.newBuilder()250.proxy(NO_PROXY)251.sslContext(sslContext)252.build();253var req = HttpRequest.newBuilder(URI.create(uriString))254.POST(bodyPublisher)255.build();256client.send(req, HttpResponse.BodyHandlers.discarding());257}258259private void changePerms(String path, String actions) {260Policy.setPolicy(new CustomPolicy(261new FilePermission(path, actions)262));263}264265static class CustomPolicy extends Policy {266static final Policy DEFAULT_POLICY = Policy.getPolicy();267final PermissionCollection perms = new Permissions();268269CustomPolicy(Permission... permissions) {270java.util.Arrays.stream(permissions).forEach(perms::add);271}272273public PermissionCollection getPermissions(ProtectionDomain domain) {274return perms;275}276277public PermissionCollection getPermissions(CodeSource codesource) {278return perms;279}280281public boolean implies(ProtectionDomain domain, Permission perm) {282// Ignore any existing permissions for test files283return perm.getName().equals(defaultFsPath.toString())284|| perm.getName().equals(zipFsPath.toString())285? perms.implies(perm)286: perms.implies(perm) || DEFAULT_POLICY.implies(domain, perm);287}288}289290static class HttpEchoHandler implements HttpServerAdapters.HttpTestHandler {291@Override292public void handle(HttpServerAdapters.HttpTestExchange t) throws IOException {293try (InputStream is = t.getRequestBody();294OutputStream os = t.getResponseBody()) {295byte[] bytes = is.readAllBytes();296t.sendResponseHeaders(200, bytes.length);297os.write(bytes);298}299}300}301302@BeforeTest303public void setup() throws Exception {304policyFile = System.getProperty("java.security.policy");305out.println(policyFile);306307sslContext = new SimpleSSLContext().get();308if (sslContext == null)309throw new AssertionError("Unexpected null sslContext");310311zipFs = newSecureZipFs(Path.of("file.zip"));312zipFsPath = zipFsFile(zipFs);313defaultFsPath = defaultFsFile();314315InetSocketAddress sa =316new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);317318httpTestServer = HttpServerAdapters.HttpTestServer.of(HttpServer.create(sa, 0));319httpTestServer.addHandler(320new FilePublisherPermsTest.HttpEchoHandler(), "/http1/echo");321httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/echo";322323HttpsServer httpsServer = HttpsServer.create(sa, 0);324httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));325httpsTestServer = HttpServerAdapters.HttpTestServer.of(httpsServer);326httpsTestServer.addHandler(327new FilePublisherPermsTest.HttpEchoHandler(), "/https1/echo");328httpsURI = "https://" + httpsTestServer.serverAuthority() + "/https1/echo";329330http2TestServer = HttpServerAdapters.HttpTestServer.of(331new Http2TestServer("localhost", false, 0));332http2TestServer.addHandler(333new FilePublisherPermsTest.HttpEchoHandler(), "/http2/echo");334http2URI = "http://" + http2TestServer.serverAuthority() + "/http2/echo";335336https2TestServer = HttpServerAdapters.HttpTestServer.of(337new Http2TestServer("localhost", true, sslContext));338https2TestServer.addHandler(339new FilePublisherPermsTest.HttpEchoHandler(), "/https2/echo");340https2URI = "https://" + https2TestServer.serverAuthority() + "/https2/echo";341342httpTestServer.start();343httpsTestServer.start();344http2TestServer.start();345https2TestServer.start();346}347348@AfterTest349public void teardown() throws Exception {350httpTestServer.stop();351httpsTestServer.stop();352http2TestServer.stop();353https2TestServer.stop();354zipFs.close();355}356}357358359