]> source.dussan.org Git - jgit.git/commitdiff
[errorprone] Remove deprecated security manager 02/1203402/2
authorIvan Frade <ifrade@google.com>
Thu, 31 Oct 2024 19:17:09 +0000 (12:17 -0700)
committerIvan Frade <ifrade@google.com>
Fri, 1 Nov 2024 22:42:01 +0000 (15:42 -0700)
Errorprone warns about this deprecated classes. The recommendation is
stop using SecurityManager all together.

The Security Manager is deprecated and subject to removal in a future
release. There is no replacement for the Security Manager. See JEP 411
[1] for discussion and alternatives.

[1] https://openjdk.org/jeps/411

Change-Id: I3c67136e97d13cf24b85e41d94408631c26e8be8

org.eclipse.jgit.test/tst/org/eclipse/jgit/api/SecurityManagerMissingPermissionsTest.java [deleted file]
org.eclipse.jgit.test/tst/org/eclipse/jgit/api/SecurityManagerTest.java [deleted file]
org.eclipse.jgit/resources/org/eclipse/jgit/internal/JGitText.properties
org.eclipse.jgit/src/org/eclipse/jgit/internal/JGitText.java
org.eclipse.jgit/src/org/eclipse/jgit/transport/SshSessionFactory.java
org.eclipse.jgit/src/org/eclipse/jgit/util/FS.java
org.eclipse.jgit/src/org/eclipse/jgit/util/FS_Win32_Cygwin.java
org.eclipse.jgit/src/org/eclipse/jgit/util/SystemReader.java
org.eclipse.jgit/src/org/eclipse/jgit/util/io/ThrowingPrintWriter.java

diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/SecurityManagerMissingPermissionsTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/SecurityManagerMissingPermissionsTest.java
deleted file mode 100644 (file)
index d0fbdbd..0000000
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (c) 2019 Alex Jitianu <alex_jitianu@sync.ro> and others
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Distribution License v. 1.0 which is available at
- * https://www.eclipse.org/org/documents/edl-v10.php.
- *
- * SPDX-License-Identifier: BSD-3-Clause
- */
-package org.eclipse.jgit.api;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.security.Policy;
-import java.util.Collections;
-
-import org.eclipse.jgit.junit.RepositoryTestCase;
-import org.eclipse.jgit.util.FileUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Tests that using a SecurityManager does not result in errors logged.
- */
-public class SecurityManagerMissingPermissionsTest extends RepositoryTestCase {
-
-       /**
-        * Collects all logging sent to the logging system.
-        */
-       private final ByteArrayOutputStream errorOutput = new ByteArrayOutputStream();
-
-       private SecurityManager originalSecurityManager;
-
-       private PrintStream defaultErrorOutput;
-
-       @Override
-       @Before
-       public void setUp() throws Exception {
-               originalSecurityManager = System.getSecurityManager();
-
-               // slf4j-simple logs to System.err, redirect it to enable asserting
-               // logged errors
-               defaultErrorOutput = System.err;
-               System.setErr(new PrintStream(errorOutput));
-
-               refreshPolicyAllPermission(Policy.getPolicy());
-               System.setSecurityManager(new SecurityManager());
-               super.setUp();
-       }
-
-       /**
-        * If a SecurityManager is active a lot of {@link java.io.FilePermission}
-        * errors are thrown and logged while initializing a repository.
-        *
-        * @throws Exception
-        */
-       @Test
-       public void testCreateNewRepos_MissingPermissions() throws Exception {
-               File wcTree = new File(getTemporaryDirectory(),
-                               "CreateNewRepositoryTest_testCreateNewRepos");
-
-               File marker = new File(getTemporaryDirectory(), "marker");
-               Files.write(marker.toPath(), Collections.singletonList("Can write"));
-               assertTrue("Can write in test directory", marker.isFile());
-               FileUtils.delete(marker);
-               assertFalse("Can delete in test direcory", marker.exists());
-
-               Git git = Git.init().setBare(false)
-                               .setDirectory(new File(wcTree.getAbsolutePath())).call();
-
-               addRepoToClose(git.getRepository());
-
-               assertEquals("", errorOutput.toString());
-       }
-
-       @Override
-       @After
-       public void tearDown() throws Exception {
-               System.setSecurityManager(originalSecurityManager);
-               System.setErr(defaultErrorOutput);
-               super.tearDown();
-       }
-
-       /**
-        * Refresh the Java Security Policy.
-        *
-        * @param policy
-        *            the policy object
-        *
-        * @throws IOException
-        *             if the temporary file that contains the policy could not be
-        *             created
-        */
-       private static void refreshPolicyAllPermission(Policy policy)
-                       throws IOException {
-               // Starting with an all permissions policy.
-               String policyString = "grant { permission java.security.AllPermission; };";
-
-               // Do not use TemporaryFilesFactory, it will create a dependency cycle
-               Path policyFile = Files.createTempFile("testpolicy", ".txt");
-
-               try {
-                       Files.write(policyFile, Collections.singletonList(policyString));
-                       System.setProperty("java.security.policy",
-                                       policyFile.toUri().toURL().toString());
-                       policy.refresh();
-               } finally {
-                       try {
-                               Files.delete(policyFile);
-                       } catch (IOException e) {
-                               // Do not log; the test tests for no logging having occurred
-                               e.printStackTrace();
-                       }
-               }
-       }
-
-}
diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/SecurityManagerTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/SecurityManagerTest.java
deleted file mode 100644 (file)
index 2b930a1..0000000
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright (C) 2019 Nail Samatov <sanail@yandex.ru> and others
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Distribution License v. 1.0 which is available at
- * https://www.eclipse.org/org/documents/edl-v10.php.
- *
- * SPDX-License-Identifier: BSD-3-Clause
- */
-package org.eclipse.jgit.api;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FilePermission;
-import java.io.IOException;
-import java.lang.reflect.ReflectPermission;
-import java.nio.file.Files;
-import java.security.Permission;
-import java.security.SecurityPermission;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.PropertyPermission;
-import java.util.logging.LoggingPermission;
-
-import javax.security.auth.AuthPermission;
-
-import org.eclipse.jgit.api.errors.GitAPIException;
-import org.eclipse.jgit.junit.JGitTestUtil;
-import org.eclipse.jgit.junit.MockSystemReader;
-import org.eclipse.jgit.junit.SeparateClassloaderTestRunner;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.treewalk.TreeWalk;
-import org.eclipse.jgit.util.FileUtils;
-import org.eclipse.jgit.util.SystemReader;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-/**
- * <p>
- * Tests if jgit works if SecurityManager is enabled.
- * </p>
- *
- * <p>
- * Note: JGit's classes shouldn't be used before SecurityManager is configured.
- * If you use some JGit's class before SecurityManager is replaced then part of
- * the code can be invoked outside of our custom SecurityManager and this test
- * becomes useless.
- * </p>
- *
- * <p>
- * For example the class {@link org.eclipse.jgit.util.FS} is used widely in jgit
- * sources. It contains DETECTED static field. At the first usage of the class
- * FS the field DETECTED is initialized and during initialization many system
- * operations that SecurityManager can forbid are invoked.
- * </p>
- *
- * <p>
- * For this reason this test doesn't extend LocalDiskRepositoryTestCase (it uses
- * JGit's classes in setUp() method) and other JGit's utility classes. It's done
- * to affect SecurityManager as less as possible.
- * </p>
- *
- * <p>
- * We use SeparateClassloaderTestRunner to isolate FS.DETECTED field
- * initialization between different tests run.
- * </p>
- */
-@RunWith(SeparateClassloaderTestRunner.class)
-public class SecurityManagerTest {
-       private File root;
-
-       private SecurityManager originalSecurityManager;
-
-       private List<Permission> permissions = new ArrayList<>();
-
-       @Before
-       public void setUp() throws Exception {
-               // Create working directory
-               SystemReader.setInstance(new MockSystemReader());
-               root = Files.createTempDirectory("jgit-security").toFile();
-
-               // Add system permissions
-               permissions.add(new RuntimePermission("*"));
-               permissions.add(new SecurityPermission("*"));
-               permissions.add(new AuthPermission("*"));
-               permissions.add(new ReflectPermission("*"));
-               permissions.add(new PropertyPermission("*", "read,write"));
-               permissions.add(new LoggingPermission("control", null));
-
-               permissions.add(new FilePermission(
-                               System.getProperty("java.home") + "/-", "read"));
-
-               String tempDir = System.getProperty("java.io.tmpdir");
-               permissions.add(new FilePermission(tempDir, "read,write,delete"));
-               permissions
-                               .add(new FilePermission(tempDir + "/-", "read,write,delete"));
-
-               // Add permissions to dependent jar files.
-               String classPath = System.getProperty("java.class.path");
-               if (classPath != null) {
-                       for (String path : classPath.split(File.pathSeparator)) {
-                               permissions.add(new FilePermission(path, "read"));
-                       }
-               }
-               // Add permissions to jgit class files.
-               String jgitSourcesRoot = new File(System.getProperty("user.dir"))
-                               .getParent();
-               permissions.add(new FilePermission(jgitSourcesRoot + "/-", "read"));
-
-               // Add permissions to working dir for jgit. Our git repositories will be
-               // initialized and cloned here.
-               permissions.add(new FilePermission(root.getPath() + "/-",
-                               "read,write,delete,execute"));
-
-               // Replace Security Manager
-               originalSecurityManager = System.getSecurityManager();
-               System.setSecurityManager(new SecurityManager() {
-
-                       @Override
-                       public void checkPermission(Permission requested) {
-                               for (Permission permission : permissions) {
-                                       if (permission.implies(requested)) {
-                                               return;
-                                       }
-                               }
-
-                               super.checkPermission(requested);
-                       }
-               });
-       }
-
-       @After
-       public void tearDown() throws Exception {
-               System.setSecurityManager(originalSecurityManager);
-
-               // Note: don't use this method before security manager is replaced in
-               // setUp() method. The method uses FS.DETECTED internally and can affect
-               // the test.
-               FileUtils.delete(root, FileUtils.RECURSIVE | FileUtils.RETRY);
-       }
-
-       @Test
-       public void testInitAndClone() throws IOException, GitAPIException {
-               File remote = new File(root, "remote");
-               File local = new File(root, "local");
-
-               try (Git git = Git.init().setDirectory(remote).call()) {
-                       JGitTestUtil.write(new File(remote, "hello.txt"), "Hello world!");
-                       git.add().addFilepattern(".").call();
-                       git.commit().setMessage("Initial commit").call();
-               }
-
-               try (Git git = Git.cloneRepository().setURI(remote.toURI().toString())
-                               .setDirectory(local).call()) {
-                       assertTrue(new File(local, ".git").exists());
-
-                       JGitTestUtil.write(new File(local, "hi.txt"), "Hi!");
-                       git.add().addFilepattern(".").call();
-                       RevCommit commit1 = git.commit().setMessage("Commit on local repo")
-                                       .call();
-                       assertEquals("Commit on local repo", commit1.getFullMessage());
-                       assertNotNull(TreeWalk.forPath(git.getRepository(), "hello.txt",
-                                       commit1.getTree()));
-               }
-
-       }
-
-}
index b1450ef05766d4710c3a92f0e78e4703a2183b51..024ca77f21a34253f1c2dabdff3a0faa06b6a784 100644 (file)
@@ -640,8 +640,6 @@ readFileStoreAttributesFailed=Reading FileStore attributes from user config fail
 readerIsRequired=Reader is required
 readingObjectsFromLocalRepositoryFailed=reading objects from local repository failed: {0}
 readLastModifiedFailed=Reading lastModified of {0} failed
-readPipeIsNotAllowed=FS.readPipe() isn't allowed for command ''{0}''. Working directory: ''{1}''.
-readPipeIsNotAllowedRequiredPermission=FS.readPipe() isn't allowed for command ''{0}''. Working directory: ''{1}''. Required permission: {2}.
 readTimedOut=Read timed out after {0} ms
 receivePackObjectTooLarge1=Object too large, rejecting the pack. Max object size limit is {0} bytes.
 receivePackObjectTooLarge2=Object too large ({0} bytes), rejecting the pack. Max object size limit is {1} bytes.
index 310962b9678cd0be2bdf1877e9477e11e5680c13..0980219e25cbf65b05a24f7f708ab7c4830b03f7 100644 (file)
@@ -670,8 +670,6 @@ public class JGitText extends TranslationBundle {
        /***/ public String readerIsRequired;
        /***/ public String readingObjectsFromLocalRepositoryFailed;
        /***/ public String readLastModifiedFailed;
-       /***/ public String readPipeIsNotAllowed;
-       /***/ public String readPipeIsNotAllowedRequiredPermission;
        /***/ public String readTimedOut;
        /***/ public String receivePackObjectTooLarge1;
        /***/ public String receivePackObjectTooLarge2;
index a0194ea8b1fa498ce3080106c81c0333547c73f0..8120df0698076c5a42f988a117fe76a968453320 100644 (file)
@@ -11,8 +11,6 @@
 
 package org.eclipse.jgit.transport;
 
-import java.security.AccessController;
-import java.security.PrivilegedAction;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -99,9 +97,8 @@ public abstract class SshSessionFactory {
         * @since 5.2
         */
        public static String getLocalUserName() {
-               return AccessController
-                               .doPrivileged((PrivilegedAction<String>) () -> SystemReader
-                                               .getInstance().getProperty(Constants.OS_USER_NAME_KEY));
+               return SystemReader.getInstance()
+                               .getProperty(Constants.OS_USER_NAME_KEY);
        }
 
        /**
index 860c1c92fd8454642cd76aa42ebfc30844235540..59bbacfa769e79a0d9578f163f0fddb133309e07 100644 (file)
@@ -30,7 +30,6 @@ import java.nio.file.InvalidPathException;
 import java.nio.file.Path;
 import java.nio.file.attribute.BasicFileAttributes;
 import java.nio.file.attribute.FileTime;
-import java.security.AccessControlException;
 import java.text.MessageFormat;
 import java.time.Duration;
 import java.time.Instant;
@@ -261,31 +260,6 @@ public abstract class FS {
 
                private static final AtomicInteger threadNumber = new AtomicInteger(1);
 
-               /**
-                * Don't use the default thread factory of the ForkJoinPool for the
-                * CompletableFuture; it runs without any privileges, which causes
-                * trouble if a SecurityManager is present.
-                * <p>
-                * Instead use normal daemon threads. They'll belong to the
-                * SecurityManager's thread group, or use the one of the calling thread,
-                * as appropriate.
-                * </p>
-                *
-                * @see java.util.concurrent.Executors#newCachedThreadPool()
-                */
-               private static final ExecutorService FUTURE_RUNNER = new ThreadPoolExecutor(
-                               5, 5, 30L, TimeUnit.SECONDS,
-                               new LinkedBlockingQueue<>(),
-                               runnable -> {
-                                       Thread t = new Thread(runnable,
-                                                       "JGit-FileStoreAttributeReader-" //$NON-NLS-1$
-                                                       + threadNumber.getAndIncrement());
-                                       // Make sure these threads don't prevent application/JVM
-                                       // shutdown.
-                                       t.setDaemon(true);
-                                       return t;
-                               });
-
                /**
                 * Use a separate executor with at most one thread to synchronize
                 * writing to the config. We write asynchronously since the config
@@ -463,7 +437,7 @@ public abstract class FS {
                                                                locks.remove(s);
                                                        }
                                                        return attributes;
-                                               }, FUTURE_RUNNER);
+                                               });
                                f = f.exceptionally(e -> {
                                        LOG.error(e.getLocalizedMessage(), e);
                                        return Optional.empty();
@@ -1391,13 +1365,6 @@ public abstract class FS {
                        }
                } catch (IOException e) {
                        LOG.error("Caught exception in FS.readPipe()", e); //$NON-NLS-1$
-               } catch (AccessControlException e) {
-                       LOG.warn(MessageFormat.format(
-                                       JGitText.get().readPipeIsNotAllowedRequiredPermission,
-                                       command, dir, e.getPermission()));
-               } catch (SecurityException e) {
-                       LOG.warn(MessageFormat.format(JGitText.get().readPipeIsNotAllowed,
-                                       command, dir));
                }
                if (debug) {
                        LOG.debug("readpipe returns null"); //$NON-NLS-1$
index 635351ac844bc74096d0c4ba2bf84bd717e47fac..237879110a753bc281525d3da8b900dedb4baf6f 100644 (file)
@@ -14,8 +14,6 @@ import static java.nio.charset.StandardCharsets.UTF_8;
 
 import java.io.File;
 import java.io.OutputStream;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
@@ -43,10 +41,7 @@ public class FS_Win32_Cygwin extends FS_Win32 {
         * @return true if cygwin is found
         */
        public static boolean isCygwin() {
-               final String path = AccessController
-                               .doPrivileged((PrivilegedAction<String>) () -> System
-                                               .getProperty("java.library.path") //$NON-NLS-1$
-                               );
+               final String path = System.getProperty("java.library.path"); //$NON-NLS-1$
                if (path == null)
                        return false;
                File found = FS.searchPath(path, "cygpath.exe"); //$NON-NLS-1$
@@ -99,9 +94,7 @@ public class FS_Win32_Cygwin extends FS_Win32 {
 
        @Override
        protected File userHomeImpl() {
-               final String home = AccessController.doPrivileged(
-                               (PrivilegedAction<String>) () -> System.getenv("HOME") //$NON-NLS-1$
-               );
+               final String home = System.getenv("HOME"); //$NON-NLS-1$
                if (home == null || home.length() == 0)
                        return super.userHomeImpl();
                return resolve(new File("."), home); //$NON-NLS-1$
index ed62c7137180d8d4d04ccd682d09ebbd2f08c48d..03ed925617e614dec930a4974aec0f43845c73a6 100644 (file)
@@ -23,8 +23,6 @@ import java.nio.charset.UnsupportedCharsetException;
 import java.nio.file.InvalidPathException;
 import java.nio.file.Path;
 import java.nio.file.Paths;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.Locale;
@@ -670,9 +668,7 @@ public abstract class SystemReader {
        }
 
        private String getOsName() {
-               return AccessController.doPrivileged(
-                               (PrivilegedAction<String>) () -> getProperty("os.name") //$NON-NLS-1$
-               );
+               return getProperty("os.name"); //$NON-NLS-1$
        }
 
        /**
index 4764676c88c6b9d4f85107c93a68d45a0bf7d9f5..13982b133cac702c1c9116248094a0a5cec11cbf 100644 (file)
@@ -11,8 +11,6 @@ package org.eclipse.jgit.util.io;
 
 import java.io.IOException;
 import java.io.Writer;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
 
 import org.eclipse.jgit.util.SystemReader;
 
@@ -35,10 +33,7 @@ public class ThrowingPrintWriter extends Writer {
         */
        public ThrowingPrintWriter(Writer out) {
                this.out = out;
-               LF = AccessController
-                               .doPrivileged((PrivilegedAction<String>) () -> SystemReader
-                                               .getInstance().getProperty("line.separator") //$NON-NLS-1$
-                               );
+               LF = SystemReader.getInstance().getProperty("line.separator"); //$NON-NLS-1$
        }
 
        @Override