1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.commons.logging.security;
21
22 import java.io.PrintWriter;
23 import java.io.StringWriter;
24 import java.lang.reflect.Field;
25 import java.lang.reflect.Method;
26 import java.util.Hashtable;
27
28 import junit.framework.Test;
29 import junit.framework.TestCase;
30
31 import org.apache.commons.logging.Log;
32 import org.apache.commons.logging.LogFactory;
33 import org.apache.commons.logging.PathableClassLoader;
34 import org.apache.commons.logging.PathableTestSuite;
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 public class SecurityForbiddenTestCase extends TestCase
50 {
51 private SecurityManager oldSecMgr;
52
53
54
55 public static class CustomHashtable extends Hashtable {
56 }
57
58
59
60
61 public static Test suite() throws Exception {
62 PathableClassLoader parent = new PathableClassLoader(null);
63 parent.useExplicitLoader("junit.", Test.class.getClassLoader());
64 parent.addLogicalLib("commons-logging");
65 parent.addLogicalLib("testclasses");
66
67 Class testClass = parent.loadClass(
68 "org.apache.commons.logging.security.SecurityForbiddenTestCase");
69 return new PathableTestSuite(testClass, parent);
70 }
71
72 public void setUp() {
73
74 oldSecMgr = System.getSecurityManager();
75 }
76
77 public void tearDown() {
78
79
80 System.setSecurityManager(oldSecMgr);
81 }
82
83
84
85
86
87
88 public void testAllForbidden() {
89 System.setProperty(
90 LogFactory.HASHTABLE_IMPLEMENTATION_PROPERTY,
91 CustomHashtable.class.getName());
92 MockSecurityManager mySecurityManager = new MockSecurityManager();
93 System.setSecurityManager(mySecurityManager);
94
95 try {
96
97
98 Class c = this.getClass().getClassLoader().loadClass(
99 "org.apache.commons.logging.LogFactory");
100 Method m = c.getMethod("getLog", new Class[] {Class.class});
101 Log log = (Log) m.invoke(null, new Object[] {this.getClass()});
102 log.info("testing");
103
104
105
106
107
108
109 System.setSecurityManager(oldSecMgr);
110 Field factoryField = c.getDeclaredField("factories");
111 factoryField.setAccessible(true);
112 Object factoryTable = factoryField.get(null);
113 assertNotNull(factoryTable);
114 String ftClassName = factoryTable.getClass().getName();
115 assertTrue("Custom hashtable unexpectedly used",
116 !CustomHashtable.class.getName().equals(ftClassName));
117
118 assertEquals(0, mySecurityManager.getUntrustedCodeCount());
119 } catch(Throwable t) {
120
121
122
123 System.setSecurityManager(oldSecMgr);
124 StringWriter sw = new StringWriter();
125 PrintWriter pw = new PrintWriter(sw);
126 t.printStackTrace(pw);
127 fail("Unexpected exception:" + t.getMessage() + ":" + sw.toString());
128 }
129 }
130 }