You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AppServer.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /*
  2. * Copyright (C) 2010, 2017 Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.junit.http;
  44. import static org.junit.Assert.assertFalse;
  45. import static org.junit.Assert.assertTrue;
  46. import java.io.File;
  47. import java.io.IOException;
  48. import java.net.InetAddress;
  49. import java.net.URI;
  50. import java.net.URISyntaxException;
  51. import java.net.UnknownHostException;
  52. import java.nio.file.Files;
  53. import java.util.ArrayList;
  54. import java.util.List;
  55. import java.util.Locale;
  56. import java.util.concurrent.ConcurrentHashMap;
  57. import java.util.concurrent.ConcurrentMap;
  58. import org.eclipse.jetty.http.HttpVersion;
  59. import org.eclipse.jetty.security.AbstractLoginService;
  60. import org.eclipse.jetty.security.Authenticator;
  61. import org.eclipse.jetty.security.ConstraintMapping;
  62. import org.eclipse.jetty.security.ConstraintSecurityHandler;
  63. import org.eclipse.jetty.security.authentication.BasicAuthenticator;
  64. import org.eclipse.jetty.server.Connector;
  65. import org.eclipse.jetty.server.HttpConfiguration;
  66. import org.eclipse.jetty.server.HttpConnectionFactory;
  67. import org.eclipse.jetty.server.Server;
  68. import org.eclipse.jetty.server.ServerConnector;
  69. import org.eclipse.jetty.server.SslConnectionFactory;
  70. import org.eclipse.jetty.server.handler.ContextHandlerCollection;
  71. import org.eclipse.jetty.servlet.ServletContextHandler;
  72. import org.eclipse.jetty.util.security.Constraint;
  73. import org.eclipse.jetty.util.security.Password;
  74. import org.eclipse.jetty.util.ssl.SslContextFactory;
  75. import org.eclipse.jgit.transport.URIish;
  76. /**
  77. * Tiny web application server for unit testing.
  78. * <p>
  79. * Tests should start the server in their {@code setUp()} method and stop the
  80. * server in their {@code tearDown()} method. Only while started the server's
  81. * URL and/or port number can be obtained.
  82. */
  83. public class AppServer {
  84. /** Realm name for the secure access areas. */
  85. public static final String realm = "Secure Area";
  86. /** Username for secured access areas. */
  87. public static final String username = "agitter";
  88. /** Password for {@link #username} in secured access areas. */
  89. public static final String password = "letmein";
  90. /** SSL keystore password; must have at least 6 characters. */
  91. private static final String keyPassword = "mykeys";
  92. /** Role for authentication. */
  93. private static final String authRole = "can-access";
  94. static {
  95. // Install a logger that throws warning messages.
  96. //
  97. final String prop = "org.eclipse.jetty.util.log.class";
  98. System.setProperty(prop, RecordingLogger.class.getName());
  99. }
  100. private final Server server;
  101. private final HttpConfiguration config;
  102. private final ServerConnector connector;
  103. private final HttpConfiguration secureConfig;
  104. private final ServerConnector secureConnector;
  105. private final ContextHandlerCollection contexts;
  106. private final TestRequestLog log;
  107. private List<File> filesToDelete = new ArrayList<>();
  108. /**
  109. * Constructor for <code>AppServer</code>.
  110. */
  111. public AppServer() {
  112. this(0, -1);
  113. }
  114. /**
  115. * Constructor for <code>AppServer</code>.
  116. *
  117. * @param port
  118. * the http port number; may be zero to allocate a port
  119. * dynamically
  120. * @since 4.2
  121. */
  122. public AppServer(int port) {
  123. this(port, -1);
  124. }
  125. /**
  126. * Constructor for <code>AppServer</code>.
  127. *
  128. * @param port
  129. * for http, may be zero to allocate a port dynamically
  130. * @param sslPort
  131. * for https,may be zero to allocate a port dynamically. If
  132. * negative, the server will be set up without https support.
  133. * @since 4.9
  134. */
  135. public AppServer(int port, int sslPort) {
  136. server = new Server();
  137. config = new HttpConfiguration();
  138. config.setSecureScheme("https");
  139. config.setSecurePort(0);
  140. config.setOutputBufferSize(32768);
  141. connector = new ServerConnector(server,
  142. new HttpConnectionFactory(config));
  143. connector.setPort(port);
  144. String ip;
  145. String hostName;
  146. try {
  147. final InetAddress me = InetAddress.getByName("localhost");
  148. ip = me.getHostAddress();
  149. connector.setHost(ip);
  150. hostName = InetAddress.getLocalHost().getCanonicalHostName();
  151. } catch (UnknownHostException e) {
  152. throw new RuntimeException("Cannot find localhost", e);
  153. }
  154. if (sslPort >= 0) {
  155. SslContextFactory sslContextFactory = createTestSslContextFactory(
  156. hostName);
  157. secureConfig = new HttpConfiguration(config);
  158. secureConnector = new ServerConnector(server,
  159. new SslConnectionFactory(sslContextFactory,
  160. HttpVersion.HTTP_1_1.asString()),
  161. new HttpConnectionFactory(secureConfig));
  162. secureConnector.setPort(sslPort);
  163. secureConnector.setHost(ip);
  164. } else {
  165. secureConfig = null;
  166. secureConnector = null;
  167. }
  168. contexts = new ContextHandlerCollection();
  169. log = new TestRequestLog();
  170. log.setHandler(contexts);
  171. if (secureConnector == null) {
  172. server.setConnectors(new Connector[] { connector });
  173. } else {
  174. server.setConnectors(
  175. new Connector[] { connector, secureConnector });
  176. }
  177. server.setHandler(log);
  178. }
  179. private SslContextFactory createTestSslContextFactory(String hostName) {
  180. SslContextFactory.Client factory = new SslContextFactory.Client(true);
  181. String dName = "CN=,OU=,O=,ST=,L=,C=";
  182. try {
  183. File tmpDir = Files.createTempDirectory("jks").toFile();
  184. tmpDir.deleteOnExit();
  185. makePrivate(tmpDir);
  186. File keyStore = new File(tmpDir, "keystore.jks");
  187. Runtime.getRuntime().exec(
  188. new String[] {
  189. "keytool", //
  190. "-keystore", keyStore.getAbsolutePath(), //
  191. "-storepass", keyPassword,
  192. "-alias", hostName, //
  193. "-genkeypair", //
  194. "-keyalg", "RSA", //
  195. "-keypass", keyPassword, //
  196. "-dname", dName, //
  197. "-validity", "2" //
  198. }).waitFor();
  199. keyStore.deleteOnExit();
  200. makePrivate(keyStore);
  201. filesToDelete.add(keyStore);
  202. filesToDelete.add(tmpDir);
  203. factory.setKeyStorePath(keyStore.getAbsolutePath());
  204. factory.setKeyStorePassword(keyPassword);
  205. factory.setKeyManagerPassword(keyPassword);
  206. factory.setTrustStorePath(keyStore.getAbsolutePath());
  207. factory.setTrustStorePassword(keyPassword);
  208. } catch (InterruptedException | IOException e) {
  209. throw new RuntimeException("Cannot create ssl key/certificate", e);
  210. }
  211. return factory;
  212. }
  213. private void makePrivate(File file) {
  214. file.setReadable(false);
  215. file.setWritable(false);
  216. file.setExecutable(false);
  217. file.setReadable(true, true);
  218. file.setWritable(true, true);
  219. if (file.isDirectory()) {
  220. file.setExecutable(true, true);
  221. }
  222. }
  223. /**
  224. * Create a new servlet context within the server.
  225. * <p>
  226. * This method should be invoked before the server is started, once for each
  227. * context the caller wants to register.
  228. *
  229. * @param path
  230. * path of the context; use "/" for the root context if binding
  231. * to the root is desired.
  232. * @return the context to add servlets into.
  233. */
  234. public ServletContextHandler addContext(String path) {
  235. assertNotYetSetUp();
  236. if ("".equals(path))
  237. path = "/";
  238. ServletContextHandler ctx = new ServletContextHandler();
  239. ctx.setContextPath(path);
  240. contexts.addHandler(ctx);
  241. return ctx;
  242. }
  243. /**
  244. * Configure basic authentication.
  245. *
  246. * @param ctx
  247. * @param methods
  248. * @return servlet context handler
  249. */
  250. public ServletContextHandler authBasic(ServletContextHandler ctx,
  251. String... methods) {
  252. assertNotYetSetUp();
  253. auth(ctx, new BasicAuthenticator(), methods);
  254. return ctx;
  255. }
  256. static class TestMappedLoginService extends AbstractLoginService {
  257. private String role;
  258. protected final ConcurrentMap<String, UserPrincipal> users = new ConcurrentHashMap<>();
  259. TestMappedLoginService(String role) {
  260. this.role = role;
  261. }
  262. @Override
  263. protected void doStart() throws Exception {
  264. UserPrincipal p = new UserPrincipal(username,
  265. new Password(password));
  266. users.put(username, p);
  267. super.doStart();
  268. }
  269. @Override
  270. protected String[] loadRoleInfo(UserPrincipal user) {
  271. if (users.get(user.getName()) == null) {
  272. return null;
  273. }
  274. return new String[] { role };
  275. }
  276. @Override
  277. protected UserPrincipal loadUserInfo(String user) {
  278. return users.get(user);
  279. }
  280. }
  281. private ConstraintMapping createConstraintMapping() {
  282. ConstraintMapping cm = new ConstraintMapping();
  283. cm.setConstraint(new Constraint());
  284. cm.getConstraint().setAuthenticate(true);
  285. cm.getConstraint().setDataConstraint(Constraint.DC_NONE);
  286. cm.getConstraint().setRoles(new String[] { authRole });
  287. cm.setPathSpec("/*");
  288. return cm;
  289. }
  290. private void auth(ServletContextHandler ctx, Authenticator authType,
  291. String... methods) {
  292. AbstractLoginService users = new TestMappedLoginService(authRole);
  293. List<ConstraintMapping> mappings = new ArrayList<>();
  294. if (methods == null || methods.length == 0) {
  295. mappings.add(createConstraintMapping());
  296. } else {
  297. for (String method : methods) {
  298. ConstraintMapping cm = createConstraintMapping();
  299. cm.setMethod(method.toUpperCase(Locale.ROOT));
  300. mappings.add(cm);
  301. }
  302. }
  303. ConstraintSecurityHandler sec = new ConstraintSecurityHandler();
  304. sec.setRealmName(realm);
  305. sec.setAuthenticator(authType);
  306. sec.setLoginService(users);
  307. sec.setConstraintMappings(
  308. mappings.toArray(new ConstraintMapping[0]));
  309. sec.setHandler(ctx);
  310. contexts.removeHandler(ctx);
  311. contexts.addHandler(sec);
  312. }
  313. /**
  314. * Start the server on a random local port.
  315. *
  316. * @throws Exception
  317. * the server cannot be started, testing is not possible.
  318. */
  319. public void setUp() throws Exception {
  320. RecordingLogger.clear();
  321. log.clear();
  322. server.start();
  323. config.setSecurePort(getSecurePort());
  324. if (secureConfig != null) {
  325. secureConfig.setSecurePort(getSecurePort());
  326. }
  327. }
  328. /**
  329. * Shutdown the server.
  330. *
  331. * @throws Exception
  332. * the server refuses to halt, or wasn't running.
  333. */
  334. public void tearDown() throws Exception {
  335. RecordingLogger.clear();
  336. log.clear();
  337. server.stop();
  338. for (File f : filesToDelete) {
  339. f.delete();
  340. }
  341. filesToDelete.clear();
  342. }
  343. /**
  344. * Get the URI to reference this server.
  345. * <p>
  346. * The returned URI includes the proper host name and port number, but does
  347. * not contain a path.
  348. *
  349. * @return URI to reference this server's root context.
  350. */
  351. public URI getURI() {
  352. assertAlreadySetUp();
  353. String host = connector.getHost();
  354. if (host.contains(":") && !host.startsWith("["))
  355. host = "[" + host + "]";
  356. final String uri = "http://" + host + ":" + getPort();
  357. try {
  358. return new URI(uri);
  359. } catch (URISyntaxException e) {
  360. throw new RuntimeException("Unexpected URI error on " + uri, e);
  361. }
  362. }
  363. /**
  364. * Get port.
  365. *
  366. * @return the local port number the server is listening on.
  367. */
  368. public int getPort() {
  369. assertAlreadySetUp();
  370. return connector.getLocalPort();
  371. }
  372. /**
  373. * Get secure port.
  374. *
  375. * @return the HTTPS port or -1 if not configured.
  376. */
  377. public int getSecurePort() {
  378. assertAlreadySetUp();
  379. return secureConnector != null ? secureConnector.getLocalPort() : -1;
  380. }
  381. /**
  382. * Get requests.
  383. *
  384. * @return all requests since the server was started.
  385. */
  386. public List<AccessEvent> getRequests() {
  387. return new ArrayList<>(log.getEvents());
  388. }
  389. /**
  390. * Get requests.
  391. *
  392. * @param base
  393. * base URI used to access the server.
  394. * @param path
  395. * the path to locate requests for, relative to {@code base}.
  396. * @return all requests which match the given path.
  397. */
  398. public List<AccessEvent> getRequests(URIish base, String path) {
  399. return getRequests(HttpTestCase.join(base, path));
  400. }
  401. /**
  402. * Get requests.
  403. *
  404. * @param path
  405. * the path to locate requests for.
  406. * @return all requests which match the given path.
  407. */
  408. public List<AccessEvent> getRequests(String path) {
  409. ArrayList<AccessEvent> r = new ArrayList<>();
  410. for (AccessEvent event : log.getEvents()) {
  411. if (event.getPath().equals(path)) {
  412. r.add(event);
  413. }
  414. }
  415. return r;
  416. }
  417. private void assertNotYetSetUp() {
  418. assertFalse("server is not running", server.isRunning());
  419. }
  420. private void assertAlreadySetUp() {
  421. assertTrue("server is running", server.isRunning());
  422. }
  423. }