|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.kyuubi.service.authentication |
| 19 | + |
| 20 | +import java.sql.{Connection, PreparedStatement, Statement} |
| 21 | +import java.util.Properties |
| 22 | +import javax.security.sasl.AuthenticationException |
| 23 | + |
| 24 | +import com.zaxxer.hikari.{HikariConfig, HikariDataSource} |
| 25 | +import org.apache.commons.lang3.StringUtils |
| 26 | + |
| 27 | +import org.apache.kyuubi.Logging |
| 28 | +import org.apache.kyuubi.config.KyuubiConf |
| 29 | +import org.apache.kyuubi.config.KyuubiConf._ |
| 30 | + |
| 31 | +class JdbcAuthenticationProviderImpl(conf: KyuubiConf) extends PasswdAuthenticationProvider |
| 32 | + with Logging { |
| 33 | + |
| 34 | + private val driverClass = conf.get(AUTHENTICATION_JDBC_DRIVER) |
| 35 | + private val jdbcUrl = conf.get(AUTHENTICATION_JDBC_URL) |
| 36 | + private val jdbcUsername = conf.get(AUTHENTICATION_JDBC_USERNAME) |
| 37 | + private val jdbcUserPassword = conf.get(AUTHENTICATION_JDBC_PASSWORD) |
| 38 | + private val authQuerySql = conf.get(AUTHENTICATION_JDBC_QUERY) |
| 39 | + |
| 40 | + private val SQL_PLACEHOLDER_REGEX = """\$\{.+?}""".r |
| 41 | + private val USERNAME_SQL_PLACEHOLDER = "${username}" |
| 42 | + private val PASSWORD_SQL_PLACEHOLDER = "${password}" |
| 43 | + |
| 44 | + checkJdbcConfigs() |
| 45 | + |
| 46 | + private[kyuubi] val hikariDataSource = getHikariDataSource |
| 47 | + |
| 48 | + /** |
| 49 | + * The authenticate method is called by the Kyuubi Server authentication layer |
| 50 | + * to authenticate users for their requests. |
| 51 | + * If a user is to be granted, return nothing/throw nothing. |
| 52 | + * When a user is to be disallowed, throw an appropriate [[AuthenticationException]]. |
| 53 | + * |
| 54 | + * @param user The username received over the connection request |
| 55 | + * @param password The password received over the connection request |
| 56 | + * @throws AuthenticationException When a user is found to be invalid by the implementation |
| 57 | + */ |
| 58 | + @throws[AuthenticationException] |
| 59 | + override def authenticate(user: String, password: String): Unit = { |
| 60 | + if (StringUtils.isBlank(user)) { |
| 61 | + throw new AuthenticationException(s"Error validating, user is null" + |
| 62 | + s" or contains blank space") |
| 63 | + } |
| 64 | + |
| 65 | + if (StringUtils.isBlank(password)) { |
| 66 | + throw new AuthenticationException(s"Error validating, password is null" + |
| 67 | + s" or contains blank space") |
| 68 | + } |
| 69 | + |
| 70 | + var connection: Connection = null |
| 71 | + var queryStatement: PreparedStatement = null |
| 72 | + |
| 73 | + try { |
| 74 | + connection = hikariDataSource.getConnection |
| 75 | + |
| 76 | + queryStatement = getAndPrepareQueryStatement(connection, user, password) |
| 77 | + |
| 78 | + val resultSet = queryStatement.executeQuery() |
| 79 | + |
| 80 | + if (resultSet == null || !resultSet.next()) { |
| 81 | + // auth failed |
| 82 | + throw new AuthenticationException(s"Password does not match or no such user. user:" + |
| 83 | + s" $user , password length: ${password.length}") |
| 84 | + } |
| 85 | + |
| 86 | + // auth passed |
| 87 | + |
| 88 | + } catch { |
| 89 | + case e: AuthenticationException => |
| 90 | + throw e |
| 91 | + case e: Exception => |
| 92 | + error("Cannot get user info", e); |
| 93 | + throw e |
| 94 | + } finally { |
| 95 | + closeDbConnection(connection, queryStatement) |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + private def checkJdbcConfigs(): Unit = { |
| 100 | + def configLog(config: String, value: String): String = s"JDBCAuthConfig: $config = '$value'" |
| 101 | + |
| 102 | + debug(configLog("Driver Class", driverClass.orNull)) |
| 103 | + debug(configLog("JDBC URL", jdbcUrl.orNull)) |
| 104 | + debug(configLog("Database username", jdbcUsername.orNull)) |
| 105 | + debug(configLog("Database password length", jdbcUserPassword.getOrElse("").length.toString)) |
| 106 | + debug(configLog("Query SQL", authQuerySql.orNull)) |
| 107 | + |
| 108 | + // Check if JDBC parameters valid |
| 109 | + if (driverClass.isEmpty) { |
| 110 | + throw new IllegalArgumentException("JDBC driver class is not configured.") |
| 111 | + } |
| 112 | + |
| 113 | + if (jdbcUrl.isEmpty) { |
| 114 | + throw new IllegalArgumentException("JDBC url is not configured") |
| 115 | + } |
| 116 | + |
| 117 | + if (jdbcUsername.isEmpty || jdbcUserPassword.isEmpty) { |
| 118 | + throw new IllegalArgumentException("JDBC username or password is not configured") |
| 119 | + } |
| 120 | + |
| 121 | + // Check Query SQL |
| 122 | + if (authQuerySql.isEmpty) { |
| 123 | + throw new IllegalArgumentException("Query SQL is not configured") |
| 124 | + } |
| 125 | + val querySqlInLowerCase = authQuerySql.get.trim.toLowerCase |
| 126 | + if (!querySqlInLowerCase.startsWith("select")) { // allow select query sql only |
| 127 | + throw new IllegalArgumentException("Query SQL must start with \"SELECT\""); |
| 128 | + } |
| 129 | + if (!querySqlInLowerCase.contains("where")) { |
| 130 | + warn("Query SQL does not contains \"WHERE\" keyword"); |
| 131 | + } |
| 132 | + if (!querySqlInLowerCase.contains("${username}")) { |
| 133 | + warn("Query SQL does not contains \"${username}\" placeholder"); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + private def getPlaceholderList(sql: String): List[String] = { |
| 138 | + SQL_PLACEHOLDER_REGEX.findAllMatchIn(sql) |
| 139 | + .map(m => m.matched) |
| 140 | + .toList |
| 141 | + } |
| 142 | + |
| 143 | + private def getAndPrepareQueryStatement( |
| 144 | + connection: Connection, |
| 145 | + user: String, |
| 146 | + password: String): PreparedStatement = { |
| 147 | + |
| 148 | + val preparedSql: String = { |
| 149 | + SQL_PLACEHOLDER_REGEX.replaceAllIn(authQuerySql.get, "?") |
| 150 | + } |
| 151 | + debug(s"prepared auth query sql: $preparedSql") |
| 152 | + |
| 153 | + val stmt = connection.prepareStatement(preparedSql) |
| 154 | + stmt.setMaxRows(1) // minimum result size required for authentication |
| 155 | + |
| 156 | + // Extract placeholder list and fill parameters to placeholders |
| 157 | + val placeholderList: List[String] = getPlaceholderList(authQuerySql.get) |
| 158 | + for (i <- placeholderList.indices) { |
| 159 | + val param = placeholderList(i) match { |
| 160 | + case USERNAME_SQL_PLACEHOLDER => user |
| 161 | + case PASSWORD_SQL_PLACEHOLDER => password |
| 162 | + case otherPlaceholder => |
| 163 | + throw new IllegalArgumentException( |
| 164 | + s"Unrecognized Placeholder In Query SQL: $otherPlaceholder") |
| 165 | + } |
| 166 | + |
| 167 | + stmt.setString(i + 1, param) |
| 168 | + } |
| 169 | + |
| 170 | + stmt |
| 171 | + } |
| 172 | + |
| 173 | + private def closeDbConnection(connection: Connection, statement: Statement): Unit = { |
| 174 | + if (statement != null && !statement.isClosed) { |
| 175 | + try { |
| 176 | + statement.close() |
| 177 | + } catch { |
| 178 | + case e: Exception => |
| 179 | + error("Cannot close PreparedStatement to auth database ", e) |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + if (connection != null && !connection.isClosed) { |
| 184 | + try { |
| 185 | + connection.close() |
| 186 | + } catch { |
| 187 | + case e: Exception => |
| 188 | + error("Cannot close connection to auth database ", e) |
| 189 | + } |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + private def getHikariDataSource: HikariDataSource = { |
| 194 | + val datasourceProperties = new Properties() |
| 195 | + val hikariConfig = new HikariConfig(datasourceProperties) |
| 196 | + hikariConfig.setDriverClassName(driverClass.orNull) |
| 197 | + hikariConfig.setJdbcUrl(jdbcUrl.orNull) |
| 198 | + hikariConfig.setUsername(jdbcUsername.orNull) |
| 199 | + hikariConfig.setPassword(jdbcUserPassword.orNull) |
| 200 | + hikariConfig.setPoolName("jdbc-auth-pool") |
| 201 | + |
| 202 | + new HikariDataSource(hikariConfig) |
| 203 | + } |
| 204 | +} |
0 commit comments