Runway 1.1.0
This commit is contained in:
1 parent
ce217fc952
commit
07d5bd7e9a
223 files changed
+21147
-255
No files matched your search
@@ -0,0 +1,98 @@
|
||||
package mx.quest.database.mariadb;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import javax.sql.DataSource;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
import mx.quest.database.spi.DatabaseProvider;
|
||||
import org.mariadb.jdbc.MariaDbDataSource;
|
||||
|
||||
/**
|
||||
* MariaDB through MariaDB Connector/J. Builds an unpooled {@link MariaDbDataSource} whose URL is
|
||||
* {@code jdbc:mariadb://host:port/database} plus properties this class pins; the account goes in through the setters,
|
||||
* never the URL. The database plugin pools it and runs every statement.
|
||||
*
|
||||
* <p>Pinned so that no setting and no server can reach outside the connection:
|
||||
* {@code allowLocalInfile=false} (the server cannot ask for a client file), {@code allowMultiQueries=false},
|
||||
* {@code permitRedirect=false} (the server cannot send the client to another host),
|
||||
* {@code allowPublicKeyRetrieval=false}. The connection time zone is UTC, matching the session time zone the
|
||||
* database plugin pins; {@code preserveInstants} stays off, so a {@code LocalDateTime} is read and written as it is
|
||||
* (instants as UTC wall-clock values), whatever the JVM's zone. TLS: {@code DISABLE} {@code sslMode=disable}; {@code REQUIRE} {@code sslMode=trust}
|
||||
* (encrypted, the server not checked); {@code VERIFY_FULL} {@code sslMode=verify-full} against the configured CA file
|
||||
* ({@code serverSslCert}) or the JVM's trust store.
|
||||
*/
|
||||
public final class MariaDbProvider implements DatabaseProvider {
|
||||
|
||||
static final int DEFAULT_PORT = 3306;
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return "mariadb";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String driverVersion() {
|
||||
String version = MariaDbDataSource.class.getPackage().getImplementationVersion();
|
||||
return "MariaDB Connector/J " + (version == null ? "" : version).strip();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataSource dataSource(ConnectionSettings settings) {
|
||||
Objects.requireNonNull(settings, "settings");
|
||||
try {
|
||||
MariaDbDataSource ds = new MariaDbDataSource(url(settings));
|
||||
ds.setUser(settings.username());
|
||||
ds.setPassword(settings.password());
|
||||
return ds;
|
||||
} catch (SQLException e) {
|
||||
throw new IllegalArgumentException("the MariaDB connection settings are not usable", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** The URL: the checked host, port and database, then only the properties this class pins. */
|
||||
static String url(ConnectionSettings settings) {
|
||||
String host = settings.host().indexOf(':') >= 0 ? "[" + settings.host() + "]" : settings.host();
|
||||
Map<String, String> p = new LinkedHashMap<>();
|
||||
p.put("allowLocalInfile", "false");
|
||||
p.put("allowMultiQueries", "false");
|
||||
p.put("permitRedirect", "false");
|
||||
p.put("allowPublicKeyRetrieval", "false");
|
||||
p.put("connectionTimeZone", "UTC");
|
||||
// No preserveInstants: with it Connector/J also turns every DATETIME/TIMESTAMP it reads as a LocalDateTime into
|
||||
// the JVM's zone, and the database plugin reads and writes instants as UTC LocalDateTime values (the session
|
||||
// is UTC). Without it a LocalDateTime goes both ways as written, whatever the JVM's zone.
|
||||
p.put("tcpKeepAlive", "true");
|
||||
p.put("connectTimeout", Long.toString(Math.max(1, settings.connectTimeout().toMillis())));
|
||||
p.put("socketTimeout", Long.toString(Math.max(1, settings.socketTimeout().toMillis())));
|
||||
switch (settings.tls()) {
|
||||
case DISABLE -> p.put("sslMode", "disable");
|
||||
case REQUIRE -> p.put("sslMode", "trust");
|
||||
case VERIFY_FULL -> {
|
||||
p.put("sslMode", "verify-full");
|
||||
if (settings.caCertificate() != null) {
|
||||
p.put("serverSslCert", settings.caCertificate().toAbsolutePath().toString());
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalArgumentException("unknown TLS policy " + settings.tls());
|
||||
}
|
||||
// Connector/J takes the URL literally (it decodes nothing), so values go in as they are: an encoded CA path
|
||||
// would name a file that does not exist. The characters its parser splits on are refused instead.
|
||||
StringBuilder url = new StringBuilder("jdbc:mariadb://").append(host).append(':')
|
||||
.append(settings.portOr(DEFAULT_PORT)).append('/').append(literal(settings.database()));
|
||||
char sep = '?';
|
||||
for (Map.Entry<String, String> e : p.entrySet()) {
|
||||
url.append(sep).append(e.getKey()).append('=').append(literal(e.getValue()));
|
||||
sep = '&';
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
private static String literal(String value) {
|
||||
if (value.indexOf('&') >= 0 || value.indexOf('?') >= 0 || value.indexOf('=') >= 0) {
|
||||
throw new IllegalArgumentException("a connection value cannot contain '&', '?' or '=': " + value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package mx.quest.database.mariadb;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/** Registers the MariaDB provider; the database plugin collects it by type. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class MariaDbProviderConfig {
|
||||
|
||||
@Bean
|
||||
public MariaDbProvider databaseMariadbProvider() {
|
||||
return new MariaDbProvider();
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package mx.quest.database.mariadb;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
import mx.quest.database.spi.ConnectionSettings.Tls;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
|
||||
class MariaDbProviderTest {
|
||||
|
||||
static ConnectionSettings settings(String host, int port, String database, String password, Tls tls, Path ca) {
|
||||
return new ConnectionSettings(host, port, database, "runway", password, tls, ca, Duration.ofSeconds(5),
|
||||
Duration.ofSeconds(40));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theUrlCarriesOnlyThePinnedPropertiesAndNeverTheAccount() {
|
||||
String url = MariaDbProvider.url(settings("db", 0, "runway", "s3cret", Tls.DISABLE, null));
|
||||
assertThat(url).startsWith("jdbc:mariadb://db:3306/runway?")
|
||||
.contains("allowLocalInfile=false", "allowMultiQueries=false", "permitRedirect=false",
|
||||
"allowPublicKeyRetrieval=false", "connectionTimeZone=UTC",
|
||||
"sslMode=disable",
|
||||
"connectTimeout=5000", "socketTimeout=40000")
|
||||
.doesNotContain("preserveInstants").doesNotContain("s3cret").doesNotContain("user=").doesNotContain("password");
|
||||
assertThat(MariaDbProvider.url(settings("db", 1, "runway", "", Tls.REQUIRE, null))).contains("sslMode=trust");
|
||||
assertThat(MariaDbProvider.url(settings("db", 1, "runway", "", Tls.VERIFY_FULL, null)))
|
||||
.contains("sslMode=verify-full").doesNotContain("serverSslCert");
|
||||
assertThat(MariaDbProvider.url(settings("db", 1, "runway", "", Tls.VERIFY_FULL, Path.of("/a b/ca.pem"))))
|
||||
.contains("serverSslCert=/a b/ca.pem");
|
||||
assertThat(MariaDbProvider.url(settings("::1", 1, "run$way", "", Tls.DISABLE, null)))
|
||||
.startsWith("jdbc:mariadb://[::1]:1/run$way?");
|
||||
assertThatThrownBy(() -> MariaDbProvider.url(settings("db", 1, "runway", "", Tls.VERIFY_FULL,
|
||||
Path.of("/x&sslMode=disable/ca.pem")))).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectorJReadsTheValuesAsWritten() throws Exception {
|
||||
// The driver decodes nothing: what the URL says is the file it opens and the database it names.
|
||||
var conf = org.mariadb.jdbc.Configuration.parse(MariaDbProvider.url(settings("db", 1, "run$way", "",
|
||||
Tls.VERIFY_FULL, Path.of("/opt/run way/ca-abc.pem"))));
|
||||
assertThat(conf.database()).isEqualTo("run$way");
|
||||
assertThat(conf.serverSslCert()).isEqualTo("/opt/run way/ca-abc.pem");
|
||||
assertThat(conf.connectionTimeZone()).isEqualTo("UTC");
|
||||
assertThat(conf.preserveInstants()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void itConnectsToARealServerAndInstantsGoBothWaysAsUtcWhateverTheJvmZone() throws Exception {
|
||||
String hostPort = System.getProperty("db.it.mariadb");
|
||||
String file = System.getProperty("db.it.password-file");
|
||||
assumeTrue(hostPort != null && file != null, "no MariaDB server configured");
|
||||
String[] hp = hostPort.split(":");
|
||||
TimeZone jvm = TimeZone.getDefault();
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("America/Mexico_City")); // a JVM that is not on UTC
|
||||
Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
|
||||
try (Connection c = new MariaDbProvider().dataSource(settings(hp[0], Integer.parseInt(hp[1]), "runway",
|
||||
Files.readString(Path.of(file)).strip(), Tls.DISABLE, null)).getConnection()) {
|
||||
try (Statement s = c.createStatement(); ResultSet rs = s.executeQuery("SELECT VERSION()")) {
|
||||
rs.next();
|
||||
assertThat(rs.getString(1)).contains("MariaDB");
|
||||
}
|
||||
try (Statement s = c.createStatement()) {
|
||||
s.execute("SET time_zone = '+00:00'"); // what the database plugin pins on every connection
|
||||
s.execute("CREATE TEMPORARY TABLE rw_times (at DATETIME(6) NOT NULL)");
|
||||
}
|
||||
// The way the database plugin's backups and registry write and read (Portable, MariaDbEngine.instant).
|
||||
Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); // DATETIME(6)
|
||||
try (PreparedStatement ps = c.prepareStatement("INSERT INTO rw_times (at) VALUES (?)")) {
|
||||
ps.setObject(1, LocalDateTime.ofInstant(now, ZoneOffset.UTC));
|
||||
ps.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement ps = c.prepareStatement("SELECT at, UTC_TIMESTAMP(6), "
|
||||
+ "TIMESTAMPDIFF(SECOND, ?, UTC_TIMESTAMP(6)) FROM rw_times")) {
|
||||
ps.setTimestamp(1, Timestamp.from(Instant.now()), utc);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
rs.next();
|
||||
assertThat(rs.getObject(1, LocalDateTime.class).toInstant(ZoneOffset.UTC))
|
||||
.as("a UTC LocalDateTime read back as written").isEqualTo(now);
|
||||
assertThat(rs.getObject(2, LocalDateTime.class).toInstant(ZoneOffset.UTC))
|
||||
.as("the server's UTC clock read as a LocalDateTime")
|
||||
.isBetween(now.minusSeconds(5), Instant.now().plusSeconds(5));
|
||||
assertThat(rs.getTimestamp(1, utc).toInstant()).as("read as a Timestamp with a UTC Calendar")
|
||||
.isEqualTo(now);
|
||||
assertThat(Math.abs(rs.getLong(3))).as("a Timestamp bound with a UTC Calendar")
|
||||
.isLessThanOrEqualTo(5);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
TimeZone.setDefault(jvm);
|
||||
}
|
||||
assertThat(new MariaDbProvider().driverVersion()).startsWith("MariaDB Connector/J");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConfigurationRegistersOneProviderNamedForThePlugin() {
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
|
||||
MariaDbProviderConfig.class)) {
|
||||
assertThat(ctx.getBeanNamesForType(mx.quest.database.spi.DatabaseProvider.class))
|
||||
.containsExactly("databaseMariadbProvider");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCompiledClassesLinkNoHostInternals() throws Exception {
|
||||
Path classes = Path.of("target", "classes");
|
||||
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
|
||||
List<String> problems = new ArrayList<>();
|
||||
try (Stream<Path> files = Files.walk(classes)) {
|
||||
for (Path f : files.filter(x -> x.toString().endsWith(".class")).toList()) {
|
||||
Matcher m = host.matcher(new String(Files.readAllBytes(f), StandardCharsets.ISO_8859_1));
|
||||
while (m.find()) {
|
||||
problems.add(f + " → " + m.group());
|
||||
}
|
||||
}
|
||||
}
|
||||
assertThat(problems).isEmpty();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user