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.security.AllPermission;
27 import java.util.Hashtable;
28
29 import junit.framework.Test;
30 import junit.framework.TestCase;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.apache.commons.logging.PathableClassLoader;
35 import org.apache.commons.logging.PathableTestSuite;
36
37
38
39
40
41
42
43
44
45
46 public class SecurityAllowedTestCase extends TestCase
47 {
48 private SecurityManager oldSecMgr;
49
50
51
52 public static class CustomHashtable extends Hashtable {
53 }
54
55
56
57
58 public static Test suite() throws Exception {
59 PathableClassLoader parent = new PathableClassLoader(null);
60 parent.useExplicitLoader("junit.", Test.class.getClassLoader());
61 parent.addLogicalLib("commons-logging");
62 parent.addLogicalLib("testclasses");
63
64 Class testClass = parent.loadClass(
65 "org.apache.commons.logging.security.SecurityAllowedTestCase");
66 return new PathableTestSuite(testClass, parent);
67 }
68
69 public void setUp() {
70
71 oldSecMgr = System.getSecurityManager();
72 }
73
74 public void tearDown() {
75
76
77 System.setSecurityManager(oldSecMgr);
78 }
79
80
81
82
83
84 public void testAllAllowed() {
85 System.setProperty(
86 LogFactory.HASHTABLE_IMPLEMENTATION_PROPERTY,
87 CustomHashtable.class.getName());
88 MockSecurityManager mySecurityManager = new MockSecurityManager();
89 mySecurityManager.addPermission(new AllPermission());
90 System.setSecurityManager(mySecurityManager);
91
92 try {
93
94
95 Class c = this.getClass().getClassLoader().loadClass(
96 "org.apache.commons.logging.LogFactory");
97 Method m = c.getMethod("getLog", new Class[] {Class.class});
98 Log log = (Log) m.invoke(null, new Object[] {this.getClass()});
99
100
101
102
103
104
105
106
107
108
109
110
111 int untrustedCodeCount = mySecurityManager.getUntrustedCodeCount();
112 log.info("testing");
113
114
115
116 System.setSecurityManager(null);
117 Field factoryField = c.getDeclaredField("factories");
118 factoryField.setAccessible(true);
119 Object factoryTable = factoryField.get(null);
120 assertNotNull(factoryTable);
121 assertEquals(CustomHashtable.class.getName(), factoryTable.getClass().getName());
122
123 assertEquals(0, untrustedCodeCount);
124 } catch(Throwable t) {
125
126
127
128 System.setSecurityManager(oldSecMgr);
129 StringWriter sw = new StringWriter();
130 PrintWriter pw = new PrintWriter(sw);
131 t.printStackTrace(pw);
132 fail("Unexpected exception:" + t.getMessage() + ":" + sw.toString());
133 }
134 }
135 }