src/java/de/uapcore/lightpit/DatabaseFacade.java

Sun, 31 Dec 2017 17:43:39 +0100

author
Mike Becker <universe@uap-core.de>
date
Sun, 31 Dec 2017 17:43:39 +0100
changeset 18
a94b172c3a93
parent 16
4e0998805276
child 19
1a0ac419f714
permissions
-rw-r--r--

user friendly error pages for codes 404, 403 and 500

universe@16 1 /*
universe@16 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
universe@16 3 *
universe@16 4 * Copyright 2017 Mike Becker. All rights reserved.
universe@16 5 *
universe@16 6 * Redistribution and use in source and binary forms, with or without
universe@16 7 * modification, are permitted provided that the following conditions are met:
universe@16 8 *
universe@16 9 * 1. Redistributions of source code must retain the above copyright
universe@16 10 * notice, this list of conditions and the following disclaimer.
universe@16 11 *
universe@16 12 * 2. Redistributions in binary form must reproduce the above copyright
universe@16 13 * notice, this list of conditions and the following disclaimer in the
universe@16 14 * documentation and/or other materials provided with the distribution.
universe@16 15 *
universe@16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
universe@16 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
universe@16 18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
universe@16 19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
universe@16 20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
universe@16 21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
universe@16 22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
universe@16 23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
universe@16 24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
universe@16 25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
universe@16 26 * POSSIBILITY OF SUCH DAMAGE.
universe@16 27 *
universe@16 28 */
universe@16 29 package de.uapcore.lightpit;
universe@16 30
universe@16 31 import java.sql.Connection;
universe@16 32 import java.sql.DatabaseMetaData;
universe@16 33 import java.sql.SQLException;
universe@16 34 import java.util.Optional;
universe@16 35 import javax.naming.Context;
universe@16 36 import javax.naming.InitialContext;
universe@16 37 import javax.naming.NamingException;
universe@16 38 import javax.servlet.ServletContext;
universe@16 39 import javax.servlet.ServletContextEvent;
universe@16 40 import javax.servlet.ServletContextListener;
universe@16 41 import javax.servlet.annotation.WebListener;
universe@16 42 import javax.sql.DataSource;
universe@16 43 import org.slf4j.Logger;
universe@16 44 import org.slf4j.LoggerFactory;
universe@16 45
universe@16 46 /**
universe@16 47 * Provides access to different privilege layers within the database.
universe@16 48 */
universe@16 49 @WebListener
universe@16 50 public final class DatabaseFacade implements ServletContextListener {
universe@16 51
universe@16 52 private static final Logger LOG = LoggerFactory.getLogger(DatabaseFacade.class);
universe@16 53
universe@16 54 /**
universe@16 55 * Timeout in seconds for the validation test.
universe@16 56 */
universe@16 57 private static final int DB_TEST_TIMEOUT = 10;
universe@16 58
universe@16 59 /**
universe@16 60 * The default schema to test against when validating the connection.
universe@16 61 *
universe@16 62 * May be overridden by context parameter.
universe@16 63 */
universe@16 64 private static final String DB_DEFAULT_SCHEMA = "lightpit";
universe@16 65
universe@16 66 /**
universe@16 67 * The attribute name in the servlet context under which an instance of this class can be found.
universe@16 68 */
universe@16 69 public static final String SC_ATTR_NAME = DatabaseFacade.class.getName();
universe@16 70 private ServletContext sc;
universe@16 71
universe@16 72 private static final String PRIVILEGED_DS_JNDI_NAME = "jdbc/lightpit/dbo";
universe@16 73 private Optional<DataSource> privilegedDataSource;
universe@16 74
universe@16 75 private static final String UNPRIVILEGED_DS_JNDI_NAME = "jdbc/lightpit/app";
universe@16 76 private Optional<DataSource> unprivilegedDataSource;
universe@16 77
universe@16 78
universe@16 79 /**
universe@16 80 * Returns an optional privileged data source.
universe@16 81 *
universe@16 82 * Privileged data sources should be able to execute any kind of DDL
universe@16 83 * statements to perform installation or configuration steps.
universe@16 84 *
universe@16 85 * This optional should always be empty in live operation. Modules which
universe@16 86 * provide installation or configuration steps MUST check the presence of
universe@16 87 * a privileged data source and SHOULD display an informative message if
universe@16 88 * it is currently disabled.
universe@16 89 *
universe@16 90 * @return an optional privileged data source
universe@16 91 */
universe@16 92 public Optional<DataSource> getPrivilegedDataSource() {
universe@16 93 return privilegedDataSource;
universe@16 94 }
universe@16 95
universe@16 96 /**
universe@16 97 * Returns an optional unprivileged data source.
universe@16 98 *
universe@16 99 * The Optional returned should never be empty. However, if something goes
universe@16 100 * wrong during initialization, the data source might be absent.
universe@16 101 * Hence, users of this data source are forced to check the existence.
universe@16 102 *
universe@16 103 * @return an optional unprivileged data source
universe@16 104 */
universe@16 105 public Optional<DataSource> getUnprivilegedDataSource() {
universe@16 106 return unprivilegedDataSource;
universe@16 107 }
universe@16 108
universe@16 109 /**
universe@16 110 * Returns the JNDI resource name of the privileged data source.
universe@16 111 *
universe@16 112 * Modules may use this information to provide useful information to the user.
universe@16 113 *
universe@16 114 * @return the JNDI resource name of the privileged data source
universe@16 115 */
universe@16 116 public String getPrivilegedDataSourceJNDIName() {
universe@16 117 return PRIVILEGED_DS_JNDI_NAME;
universe@16 118 }
universe@16 119
universe@16 120 /**
universe@16 121 * Returns the JNDI resource name of the unprivileged data source.
universe@16 122 *
universe@16 123 * Modules may use this information to provide useful information to the user.
universe@16 124 *
universe@16 125 * @return the JNDI resource name of the unprivileged data source
universe@16 126 */
universe@16 127 public String getUnprivilegedDataSourceJNDIName() {
universe@16 128 return UNPRIVILEGED_DS_JNDI_NAME;
universe@16 129 }
universe@16 130
universe@16 131 private static void checkConnection(DataSource ds, String testSchema, String errMsg) {
universe@16 132 try (Connection conn = ds.getConnection()) {
universe@16 133 if (!conn.isValid(DB_TEST_TIMEOUT)) {
universe@16 134 throw new SQLException("Validation check failed.");
universe@16 135 }
universe@16 136 if (conn.isReadOnly()) {
universe@16 137 throw new SQLException("Connection is read-only and thus unusable.");
universe@16 138 }
universe@16 139 if (!conn.getSchema().equals(testSchema)) {
universe@16 140 throw new SQLException(String.format("Connection is not configured to use the schema %s.", testSchema));
universe@16 141 }
universe@16 142 DatabaseMetaData metaData = conn.getMetaData();
universe@16 143 LOG.info("Connections as {} to {}/{} ready to go.", metaData.getUserName(), metaData.getURL(), conn.getSchema());
universe@16 144 } catch (SQLException ex) {
universe@16 145 LOG.error(errMsg, ex);
universe@16 146 }
universe@16 147 }
universe@16 148
universe@16 149 private static Optional<DataSource> retrievePrivilegedDataSource(Context ctx) {
universe@16 150 DataSource ret = null;
universe@16 151 try {
universe@16 152 ret = (DataSource)ctx.lookup(PRIVILEGED_DS_JNDI_NAME);
universe@16 153 LOG.info("Privileged data source {} retrieved from context.", PRIVILEGED_DS_JNDI_NAME);
universe@16 154 LOG.warn("Your application may be vulnerable due to privileged database access. Make sure that privileged data sources are only available during installation or configuration.");
universe@16 155 } catch (NamingException ex) {
universe@16 156 LOG.info("Privileged data source not available. This is perfectly OK. Activate only, if you need to do installation or configuration.");
universe@16 157 /* in case the absence of the DataSource is not intended, log something more useful on debug level */
universe@16 158 LOG.debug("Reason for the missing data source: ", ex);
universe@16 159 }
universe@16 160 return Optional.ofNullable(ret);
universe@16 161 }
universe@16 162
universe@16 163 private static Optional<DataSource> retrieveUnprivilegedDataSource(Context ctx) {
universe@16 164 DataSource ret = null;
universe@16 165 try {
universe@16 166 ret = (DataSource)ctx.lookup(UNPRIVILEGED_DS_JNDI_NAME);
universe@16 167 LOG.info("Unprivileged data source retrieved.");
universe@16 168 } catch (NamingException ex) {
universe@16 169 LOG.error("Unprivileged data source {} not available.", UNPRIVILEGED_DS_JNDI_NAME);
universe@16 170 /* for the unprivileged DataSource log the exception on error level (ordinary admins could find this useful) */
universe@16 171 LOG.error("Reason for the missing data source: ", ex);
universe@16 172 }
universe@16 173 return Optional.ofNullable(ret);
universe@16 174 }
universe@16 175
universe@16 176 @Override
universe@16 177 public void contextInitialized(ServletContextEvent sce) {
universe@16 178 sc = sce.getServletContext();
universe@16 179
universe@16 180 privilegedDataSource = unprivilegedDataSource = null;
universe@16 181
universe@16 182 final String contextName = Optional
universe@16 183 .ofNullable(sc.getInitParameter(Constants.CTX_ATTR_JNDI_CONTEXT))
universe@16 184 .orElse("java:comp/env");
universe@16 185 final String dbSchema = Optional
universe@16 186 .ofNullable(sc.getInitParameter(Constants.CTX_ATTR_DB_SCHEMA))
universe@16 187 .orElse(DB_DEFAULT_SCHEMA);
universe@16 188
universe@16 189 try {
universe@16 190 LOG.debug("Trying to access JNDI context {}...", contextName);
universe@16 191 Context initialCtx = new InitialContext();
universe@16 192 Context ctx = (Context) initialCtx.lookup(contextName);
universe@16 193
universe@16 194 privilegedDataSource = retrievePrivilegedDataSource(ctx);
universe@16 195 unprivilegedDataSource = retrieveUnprivilegedDataSource(ctx);
universe@16 196
universe@16 197 privilegedDataSource.ifPresent((ds) -> checkConnection(ds, dbSchema, "Checking privileged connection failed"));
universe@16 198 unprivilegedDataSource.ifPresent((ds) -> checkConnection(ds, dbSchema, "Checking unprivileged connection failed"));
universe@16 199 } catch (NamingException | ClassCastException ex) {
universe@16 200 LOG.error("Cannot access JNDI resources.", ex);
universe@16 201 }
universe@16 202
universe@16 203 sc.setAttribute(SC_ATTR_NAME, this);
universe@16 204 LOG.info("Database facade injected into ServletContext.");
universe@16 205 }
universe@16 206
universe@16 207 @Override
universe@16 208 public void contextDestroyed(ServletContextEvent sce) {
universe@16 209 privilegedDataSource = unprivilegedDataSource = null;
universe@16 210 }
universe@16 211 }

mercurial