File: MissingPermissionsTest.java

package info (click to toggle)
derby 10.14.2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 79,056 kB
  • sloc: java: 691,961; sql: 42,686; xml: 20,512; sh: 3,373; sed: 96; makefile: 60
file content (488 lines) | stat: -rw-r--r-- 19,676 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/*

   Derby - Class org.apache.derbyTesting.unitTests.junit.MissingPermissionsTest

   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

*/

package org.apache.derbyTesting.unitTests.junit;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;
import junit.framework.Test;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.SecurityManagerSetup;
import org.apache.derbyTesting.junit.SpawnedProcess;
import org.apache.derbyTesting.junit.SupportFilesSetup;
import org.apache.derbyTesting.junit.SystemPropertyTestSetup;
import org.apache.derbyTesting.junit.TestConfiguration;

/**
 * Test behavior when permissions are missing for:
 * <ul>
 *   <li>reading of system properties, see DERBY-6617</li>
 *   <li>read, write access to create derby.system.home, see DERBY-6617</li>
 * </ul>
 * Note: requires English locale because the test asserts on localized
 * strings.
 */
public class MissingPermissionsTest extends BaseJDBCTestCase {

    private final static String AUTH_MSG =
            "derby.connection.requireAuthentication";

    private final static String SYSTEM_HOME = "derby.system.home";

    private final static String resourcePrefix = "unitTests/junit/";
    private final static String testPrefix =
            "org/apache/derbyTesting/" + resourcePrefix;

    private final static String OK_POLICY =
            "MissingPermissionsTest.policy";
    private final static String OK_POLICY_T =
            testPrefix + OK_POLICY;
    private final static String OK_POLICY_R =
            resourcePrefix + OK_POLICY;

    private final static String POLICY_MINUS_PROPERTYPERMISSION =
            "MissingPermissionsTest1.policy";

    private final static String POLICY_MINUS_PROPERTYPERMISSION_T =
            testPrefix + POLICY_MINUS_PROPERTYPERMISSION;

    private final static String POLICY_MINUS_FILEPERMISSION =
            "MissingPermissionsTest2.policy";

    private final static String POLICY_MINUS_FILEPERMISSION_T =
            testPrefix + POLICY_MINUS_FILEPERMISSION;

    private final static String POLICY_MINUS_FILEPERMISSION_R =
            resourcePrefix + POLICY_MINUS_FILEPERMISSION;

    private final int KIND_EXPECT_ERROR_MSG_PRESENT = 0;
    private final int KIND_EXPECT_ERROR_MSG_ABSENT = 1;

    /**
     * Used for running #testModifyThreadGroup
     */
    private static boolean inSubProcess = false;

    public MissingPermissionsTest(String name) {
        super(name);
    }


    private static Test makeTest(String fixture, String policy) {
        Test t =  new MissingPermissionsTest(fixture);
        t = new SecurityManagerSetup(t, policy);
        final Properties props = new Properties();
        props.setProperty("derby.connection.requireAuthentication", "true");
        props.setProperty("derby.database.sqlAuthorization", "true");
        props.setProperty("derby.authentication.provider", "BUILTIN");
        props.setProperty("derby.user.APP", "APPPW");

        t = new SystemPropertyTestSetup(t, props, true);
        t = TestConfiguration.changeUserDecorator(t, "APP", "APPPW");
        t = TestConfiguration.singleUseDatabaseDecorator(t);
        return t;
    }

    public static Test suite() {
        inSubProcess = Boolean.getBoolean("inSubProcess");

        final BaseTestSuite suite =
                new BaseTestSuite("SystemPrivilegesPermissionTest");

        if (!inSubProcess && !TestConfiguration.loadingFromJars()) {
            // This test only works with jar files. Only check at top
            // level
            return suite;
        }

        if (!inSubProcess) {
            suite.addTest(
                    new SupportFilesSetup(
                            makeTest("testMissingFilePermission",
                                    POLICY_MINUS_FILEPERMISSION_T),
                            new String[] {
                                POLICY_MINUS_FILEPERMISSION_R}));

            suite.addTest(makeTest("testPresentPropertiesPermission",
                    OK_POLICY_T));

            suite.addTest(makeTest("testMissingPropertiesPermission",
                    POLICY_MINUS_PROPERTYPERMISSION_T));
        }

        // This test runs in both the top process and a subprocess since it has
        // two parts:
        suite.addTest(new SupportFilesSetup(makeTest("testModifyThreadGroup",
                OK_POLICY_T),
                new String[] {OK_POLICY_R}));
        return suite;
    }

    /**
     * This test is run with a policy that does not lack permission to read
     * properties for derby.jar. This should leave no related error messages on
     * derby.log.
     *
     * @throws SQLException
     * @throws IOException
     * @throws PrivilegedActionException
     */
    public void testPresentPropertiesPermission()
            throws SQLException, IOException, PrivilegedActionException {

        // With credentials we are OK
        openDefaultConnection("APP", "APPPW").close();

        Connection c = null;

        // With wrong credentials we are not OK
        try {
            c = openDefaultConnection("Donald", "Duck");
            fail();
        } catch(SQLException e) {
            assertSQLState("08004", e);
        } finally {
            if (c != null) {
                c.close();
            }
        }
        verifyMessagesInDerbyLog(KIND_EXPECT_ERROR_MSG_ABSENT);
    }

    /**
     * This test is run with a policy that lacks permission to read properties
     * for derby.jar. This should lead to error messages on derby.log.
     *
     * @throws SQLException
     * @throws IOException
     * @throws PrivilegedActionException
     */
    public void testMissingPropertiesPermission()
            throws SQLException, IOException, PrivilegedActionException {
        // With credentials we are OK
        openDefaultConnection("APP", "APPPW").close();

        // But also with wrong ones, all seems OK...
        openDefaultConnection("Donald", "Duck").close();

        // Check that we see the error messages expected in derby.log
        verifyMessagesInDerbyLog(KIND_EXPECT_ERROR_MSG_PRESENT);
    }

    /**
     * This test is run with a policy that lacks permission for derby.jar to
     * create a db directory for derby.  In this scenario we expect the boot to
     * fail, and an error message to be printed to the console, so we try to
     * get it by forking a sub-process. See {@code FileMonitor#PBinitialize}
     * when it gets a {@code SecurityException} following attempt to do "{@code
     * home.mkdir(s)}".
     * <p/>
     * Note that the policy used with this text fixture also doubles as the
     * one used by the subprocess to demonstrate the lack of permission.
     *
     * @throws SQLException
     * @throws IOException
     * @throws PrivilegedActionException
     * @throws ClassNotFoundException
     * @throws java.lang.InterruptedException
     */
    public void testMissingFilePermission() throws SQLException,
            IOException,
            PrivilegedActionException,
            ClassNotFoundException,
            InterruptedException {

        // Collect the set of needed arguments to the java command
        // The command runs ij with a security manager whose policy
        // lacks the permissions to create derby.system.home.
        final List<String> args = new ArrayList<String>();
        args.add("-Djava.security.manager");
        args.add("-Djava.security.policy=extin/MissingPermissionsTest2.policy");
        args.add("-DderbyTesting.codejar="
                    + getSystemProperty("derbyTesting.codejar"));
        args.add("-DderbyTesting.testjar="
                    + getSystemProperty("derbyTesting.testjar"));
        args.add("-DderbyTesting.junit="
                    + getSystemProperty("derbyTesting.junit"));
        String antjunit = getSystemProperty("derbyTesting.antjunit");
        if (antjunit != null) {
            // This property is only available when the test is started
            // by Ant's JUnit task.
            args.add("-DderbyTesting.antjunit=" + antjunit);
        }
        args.add("-Dderby.system.home=system/nested");
        args.add("-Dij.connection.test=jdbc:derby:wombat;create=true");
        args.add("org.apache.derby.tools.ij");
        final String[] argArray = args.toArray(new String[0]);

        final Process p = execJavaCmd(argArray);
        SpawnedProcess spawned = new SpawnedProcess(p, "MPT");
        spawned.suppressOutputOnComplete(); // we want to read it ourselves

        // The started process is an interactive ij session that will wait
        // for user input. Close stdin of the process so that it stops
        // waiting and exits.
        p.getOutputStream().close();

        final int exitCode = spawned.complete(120000L); // 2 minutes

        assertTrue(
            spawned.getFailMessage("subprocess run failed: "), exitCode == 0);

        // The actual message may vary. On Java 6, the names are not quoted,
        // whereas newer versions double-quote them. On Windows, the directory
        // separator is different. Also, different JVM vendors capitalize
        // the "access denied" message differently.
        //
        // Use a regular expression that matches all known variants.
        final String expectedMessageOnConsole =
            "(?s).*The file or directory system.nested could not be created " +
            "due to a security exception: " +
            "java\\.security\\.AccessControlException: [Aa]ccess denied " +
            "\\(\"?java\\.io\\.FilePermission\"? \"?system.nested\"? " +
            "\"?write\"?\\).*";

        final String output = spawned.getFullServerOutput(); // ignore
        final String err    = spawned.getFullServerError();

        assertTrue(err, err.matches(expectedMessageOnConsole));
    }

    /**
     * Make a regex that matches a warning for missing property permission.
     * @param property the property for which read permission is missing
     * @return a pattern that matches the expected warning
     */
    private String makeMessage(String property) {
        // A variable part in the message is whether or not the names are
        // double-quoted. In Java 6 they are not. In newer versions they are.
        // Another variable part is that the captitalization of "access denied"
        // varies depending on the JVM vendor.
        final StringBuilder sb = new StringBuilder();
        sb.append("(?s).*WARNING: the property ");
        sb.append(Pattern.quote(property));
        sb.append(" could not be read due to a security exception: ");
        sb.append("java\\.security\\.AccessControlException: [Aa]ccess denied \\(");
        sb.append("\"?java\\.util\\.PropertyPermission\"? \"?");
        sb.append(Pattern.quote(property));
        sb.append("\"? \"?read\"?.*");
        return sb.toString();
    }


    private void verifyMessagesInDerbyLog(int kind) throws
            FileNotFoundException,
            IOException,
            PrivilegedActionException {

        String derbyLog = null;

        if (kind == KIND_EXPECT_ERROR_MSG_PRESENT) {
            // In this case we didn't have permission to read derby.system.home
            // so expect derby.log to be at CWD.
            derbyLog = "derby.log";
        } else if (kind == KIND_EXPECT_ERROR_MSG_ABSENT) {
            derbyLog = "system/derby.log";
        }

        final BufferedReader dl = getReader(derbyLog);
        final StringBuilder log = new StringBuilder();

        try {
            for (String line = dl.readLine(); line != null; line = dl.readLine()) {
                log.append(line);
                log.append('\n');
            }

            String logString = log.toString();
            if (kind == KIND_EXPECT_ERROR_MSG_PRESENT) {
                // We should see SecurityException when reading security
                // related properties in FileMonitor#PBgetJVMProperty
                assertTrue(logString, logString.matches(makeMessage(AUTH_MSG)));

                // We should see SecurityException when reading
                // derby.system.home in FileMonitor#PBinitialize
                assertTrue(logString,
                           logString.matches(makeMessage(SYSTEM_HOME)));
            } else if (kind == KIND_EXPECT_ERROR_MSG_ABSENT) {
                assertFalse(logString,
                            logString.matches(makeMessage(AUTH_MSG)));
                assertFalse(logString,
                            logString.matches(makeMessage(SYSTEM_HOME)));
            }
        } finally {
            dl.close();
        }
    }

    private static BufferedReader getReader(final String file)
            throws PrivilegedActionException {

        return AccessController.doPrivileged(
                new PrivilegedExceptionAction<BufferedReader>() {
            @Override
            public BufferedReader run() throws FileNotFoundException {
                return new BufferedReader(new FileReader(file));
            }});
    }


    public void testModifyThreadGroup() throws Throwable {
        if (!inSubProcess) {
            // Set up run of this test in a sub process, so we can catch its
            // standard err/standard out.
            final List<String> args = new ArrayList<String>();
            args.add("-DinSubProcess=true");
            args.add("-Djava.security.manager");
            args.add(
                "-Djava.security.policy=extin/MissingPermissionsTest.policy");
            args.add("-DderbyTesting.codejar="
                    + getSystemProperty("derbyTesting.codejar"));
            args.add("-DderbyTesting.testjar="
                    + getSystemProperty("derbyTesting.testjar"));
            args.add("-DderbyTesting.junit="
                    + getSystemProperty("derbyTesting.junit"));
            String antjunit = getSystemProperty("derbyTesting.antjunit");
            if (antjunit != null) {
                // This property is only available when the test is started
                // by Ant's JUnit task.
                args.add("-DderbyTesting.antjunit=" + antjunit);
            }
            args.add("-Dderby.system.home=system/nested_tMTG");
            args.add("-Dderby.system.durability=" +
                     getSystemProperty("derby.system.durability"));
            args.add("-Dderby.tests.trace=" +
                     getSystemProperty("derby.tests.trace"));
            args.add("-Dderby.system.debug=" +
                     getSystemProperty("derby.tests.debug"));
            args.add("junit.textui.TestRunner");
            args.add(this.getClass().getName());

            final String[] argArray = args.toArray(new String[0]);
            final Process p = execJavaCmd(argArray);
            SpawnedProcess spawned = new SpawnedProcess(p, "MPT");
            spawned.suppressOutputOnComplete(); // we want to read it ourselves

            // The started process is an interactive ij session that will wait
            // for user input. Close stdin of the process so that it stops
            // waiting and exits.
            p.getOutputStream().close();

            final int exitCode = spawned.complete(120000L); // 2 minutes

            assertTrue(spawned.getFailMessage("subprocess run failed: "),
                    exitCode == 1);

            final String expectedMessageOnConsole =
                    "WARNING: could not do ThreadGroup#setDaemon on Derby " +
                    "daemons due to a security exception";

            final String output = spawned.getFullServerOutput(); // ignore
            final String err    = spawned.getFullServerError();

            assertTrue(err, err.contains(expectedMessageOnConsole));

            // Print sub process' output if this test specifies any such
            if (Boolean.parseBoolean(
                        getSystemProperty("derby.tests.trace")) ||
                Boolean.parseBoolean(
                    getSystemProperty("derby.tests.debug"))) {

                System.out.println("\n[ (subprocess) " +
                        output.replace("\n", "\n  (subprocess) ") + "]\n");
            }

        } else {
            final SystemThreadRun mst = new SystemThreadRun(this);

            Thread t = AccessController.doPrivileged(
                new PrivilegedAction<Thread>() {
                    @Override
                    public Thread run() {
                        return new Thread(
                            Thread.currentThread().getThreadGroup().getParent(),
                            mst);
                    }});


            t.start();
            t.join();

            // The boot will fail since operation that require
            // modifyThreadGroup lead to boot failure. So the fact that the
            // same permission is missing in FileMonitor#createDaemonGroup
            // isn't an issue: it will not go undetected. It fails at this line
            // in BaseMonitor#runWithState:
            //
            //  timerFactory = (TimerFactory)Monitor.startSystemModule(
            //         "org.apache.derby.iapi.services.timer.TimerFactory");
            //
            // and the AccessControlException isn't caught and percolates all
            // the way out.
            assertTrue(mst.f instanceof AccessControlException);

            // This patch also fixes the fact that previously, the monitor in such
            // an event, thought it was already initialized so subsequent boot
            // attempt (from a non-system thread) would also fail. We now clean up,
            // so a boot here should work.
            openDefaultConnection("APP", "APPPW").close();
        }
    }

    private class SystemThreadRun implements Runnable {
        public Throwable f;
        private final BaseJDBCTestCase test;

        public SystemThreadRun(BaseJDBCTestCase test) {
            super();
            this.test = test;
        }

        @SuppressWarnings({"BroadCatchBlock", "TooBroadCatch"})
        @Override
        public void run() {
            try {
                assertEquals(
                    Thread.currentThread().getThreadGroup().getName(),
                    "system");
                // Expect this to fail with AccessControlException
                test.openDefaultConnection("APP", "APPPW").close();
                fail();
            } catch (Throwable e) {
                this.f = e;
            }
        }
    }
}