SecurityException from I/O code in a parallel stream

前端 未结 2 1609
清酒与你
清酒与你 2020-12-31 11:17

I have no way to explain this one, but I found this phenomenon in somebody else\'s code:

import java.io.IOException;
import java.io.UncheckedIOException;
imp         


        
2条回答
  •  时光取名叫无心
    2020-12-31 11:50

    Your worrying about AccessController.doPrivileged is unnecessary. It does not reduce the security if done right. The versions taking a single action argument will execute the action in your context, ignoring your callers but there are overloaded methods, having an additional argument, a previously recorded context:

    private void doTest(boolean parallel)
    {
        Consumer createFile=name -> {
            try {
                Files.createTempFile(name, ".dat");
            }
            catch (IOException e) {
                throw new UncheckedIOException("Failed to create temp file", e);
            }
        }, actualAction;
        Stream stream = Stream.of("1", "2", "3");
    
        if(parallel)
        {
            stream = stream.parallel();
            AccessControlContext ctx=AccessController.getContext();
            actualAction=name -> AccessController.doPrivileged(
              (PrivilegedAction)()->{ createFile.accept(name); return null; }, ctx);
        }
        else actualAction = createFile;
    
        stream.forEach(actualAction);
    }
    

    The first important line is the AccessControlContext ctx=AccessController.getContext(); statement it records your current security context which includes your code and the current callers. (Remember that the effective permissions are the intersection of the sets of all callers). By providing the resulting context object ctx to the doPrivileged method within the Consumer you are reestablishing the context, in other words, the PrivilegedAction will have the same permissions as in your single-threaded scenario.

提交回复
热议问题