Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions api/src/org/labkey/api/audit/query/AbstractAuditDomainKind.java
Original file line number Diff line number Diff line change
Expand Up @@ -429,15 +429,19 @@ public void validate()
if (prefix.length() < 12)
throw new IllegalStateException("Namespace prefix must be unique and longer than this: " + prefix);

List<String> overlappers = PREFIXES.stream()
.filter(p -> p.startsWith(prefix) || prefix.startsWith(p))
.map(p -> "\"" + p + "\"")
.toList();

if (overlappers.isEmpty())
PREFIXES.add(prefix);
else
throw new IllegalStateException("Namespace prefix \"" + prefix + "\" overlaps with " + overlappers);
// Providers initialize concurrently
synchronized (PREFIXES)
{
List<String> overlappers = PREFIXES.stream()
.filter(p -> p.startsWith(prefix) || prefix.startsWith(p))
.map(p -> "\"" + p + "\"")
.toList();

if (overlappers.isEmpty())
PREFIXES.add(prefix);
else
throw new IllegalStateException("Namespace prefix \"" + prefix + "\" overlaps with " + overlappers);
}
}

public static class TestCase extends Assert
Expand Down
2 changes: 1 addition & 1 deletion api/src/org/labkey/api/data/BaseColumnInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -1717,7 +1717,7 @@ public static Collection<BaseColumnInfo> createFromDatabaseMetaData(String schem
}
}

JdbcMetaDataSelector keySelector = new JdbcMetaDataSelector(locator, (dbmd, locator1) -> dbmd.getImportedKeys(locator1.getCatalogName(), locator1.getSchemaName(), locator1.getTableName()));
JdbcMetaDataSelector keySelector = dialect.getImportedKeysSelector(locator);

// load keys in two phases
// 1) combine multi-column keys
Expand Down
59 changes: 55 additions & 4 deletions api/src/org/labkey/api/data/dialect/JdbcMetaDataTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,24 @@

import org.junit.Assert;
import org.junit.Test;
import org.labkey.api.audit.AbstractAuditTypeProvider;
import org.labkey.api.data.CoreSchema;
import org.labkey.api.data.DatabaseTableType;
import org.labkey.api.data.DbSchema;
import org.labkey.api.data.DbSchemaType;
import org.labkey.api.data.DbScope;
import org.labkey.api.data.JdbcMetaDataSelector;
import org.labkey.api.data.SQLFragment;
import org.labkey.api.data.SqlExecutor;
import org.labkey.api.data.TableInfo;
import org.labkey.api.data.TableSelector;
import org.labkey.api.data.TestSchema;
import org.labkey.api.exp.api.ExperimentService;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JdbcMetaDataTest extends Assert
{
Expand All @@ -45,12 +54,54 @@ public void testTablesWithSpecialCharacters()
@Test
public void testMaterializedView()
{
// SQL Server doesn't support materialized views
if (_testSchema.getSqlDialect().isPostgreSQL())
new SqlExecutor(_testSchema).execute(SQLFragment.unsafe("REFRESH MATERIALIZED VIEW test.MaterializedView"));
test("MaterializedView", CoreSchema.getInstance().getTableInfoContainers(), DatabaseTableType.MATERIALIZED_VIEW);
}

@Test
public void testImportedKeysMatchJdbc() throws SQLException
{
DbScope scope = _testSchema.getScope();

for (String schemaName : List.of(CoreSchema.getInstance().getSchemaName(), ExperimentService.get().getSchema().getName(), AbstractAuditTypeProvider.SCHEMA_NAME))
{
for (String tableName : DbSchema.createFromMetaData(scope, schemaName, DbSchemaType.Bare).getTableNames())
assertImportedKeysMatch(scope, schemaName, tableName);
}

// Mixed case, LIKE wild cards, a multi-column FK, and a cross-schema FK, on tables visible only to this uncommitted transaction
try (DbScope.Transaction ignored = scope.ensureTransaction())
{
new SqlExecutor(scope).execute(SQLFragment.unsafe(
"CREATE TABLE test.\"FkParent_%X\" (\"Container\" VARCHAR(36) NOT NULL, \"RowId\" INT NOT NULL, PRIMARY KEY (\"Container\", \"RowId\"));\n" +
"CREATE TABLE test.\"FkChild$Y\" (\"Container\" VARCHAR(36) NOT NULL, \"ParentRowId\" INT, \"ContainerRowId\" INT, " +
"CONSTRAINT \"FK_Child_Parent\" FOREIGN KEY (\"Container\", \"ParentRowId\") REFERENCES test.\"FkParent_%X\" (\"Container\", \"RowId\"), " +
"CONSTRAINT \"FK_Child_Containers\" FOREIGN KEY (\"ContainerRowId\") REFERENCES ").append(CoreSchema.getInstance().getTableInfoContainers()).append(SQLFragment.unsafe(" (RowId))")));
assertEquals(3, assertImportedKeysMatch(scope, _testSchema.getName(), "FkChild$Y"));
}
}

/** Asserts the dialect's FK selector returns the rows JDBC getImportedKeys() does, in the same order; returns the row count */
private static int assertImportedKeysMatch(DbScope scope, String schemaName, String tableName) throws SQLException
{
try (JdbcMetaDataLocator locator = scope.getSqlDialect().getTableResolver().getSingleTableLocator(scope, schemaName, tableName))
{
List<List<Object>> expected = readImportedKeys(new JdbcMetaDataSelector(locator, (dbmd, l) -> dbmd.getImportedKeys(l.getCatalogName(), l.getSchemaName(), l.getTableName())));
List<List<Object>> actual = readImportedKeys(scope.getSqlDialect().getImportedKeysSelector(locator));
assertEquals(schemaName + "." + tableName, expected, actual);
return actual.size();
}
}

private static List<List<Object>> readImportedKeys(JdbcMetaDataSelector selector) throws SQLException
{
List<List<Object>> rows = new ArrayList<>();
try (ResultSet rs = selector.getResultSet())
{
new SqlExecutor(_testSchema).execute(SQLFragment.unsafe("REFRESH MATERIALIZED VIEW test.MaterializedView"));
test("MaterializedView", CoreSchema.getInstance().getTableInfoContainers(), DatabaseTableType.MATERIALIZED_VIEW);
while (rs.next())
rows.add(List.of(rs.getString("PKTABLE_SCHEM"), rs.getString("PKTABLE_NAME"), rs.getString("PKCOLUMN_NAME"), rs.getString("FKCOLUMN_NAME"), rs.getInt("KEY_SEQ"), rs.getString("FK_NAME")));
}
return rows;
}

private void test(String viewName, TableInfo expectedTable, DatabaseTableType expectedTableType)
Expand Down
7 changes: 7 additions & 0 deletions api/src/org/labkey/api/data/dialect/SqlDialect.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import org.labkey.api.data.DbScope;
import org.labkey.api.data.DbScope.LabKeyDataSource;
import org.labkey.api.data.InClauseGenerator;
import org.labkey.api.data.JdbcMetaDataSelector;
import org.labkey.api.data.JdbcMetaDataSelector.JdbcMetaDataResultSetFactory;
import org.labkey.api.data.JdbcType;
import org.labkey.api.data.LookupColumn;
Expand Down Expand Up @@ -1592,6 +1593,12 @@ public final ForeignKeyResolver getForeignKeyResolver(DbScope scope, @Nullable S
return getTableResolver().getForeignKeyResolver(scope, schemaName, tableName);
}

/** Selects the locator's table's foreign keys as a {@link DatabaseMetaData#getImportedKeys} result set, ordered by PK table, FK_NAME, KEY_SEQ */
public JdbcMetaDataSelector getImportedKeysSelector(JdbcMetaDataLocator locator)
{
return new JdbcMetaDataSelector(locator, (dbmd, l) -> dbmd.getImportedKeys(l.getCatalogName(), l.getSchemaName(), l.getTableName()));
}

// Pass-through by default. Dialects can override if they need special handling.
public JdbcMetaDataResultSetFactory getJdbcMetaDataResultSetFactory(JdbcMetaDataResultSetFactory jdbcMetaDataResultSetFactory)
{
Expand Down
54 changes: 54 additions & 0 deletions api/src/org/labkey/api/module/ModuleArchiveTestCase.java
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,60 @@ public void testHeldUnchangedJarIsKept() throws IOException
assertFalse(v2.isModified());
}

@Test
public void testReextractionRewritesOnlyWhatDiffers() throws IOException
{
long now = System.currentTimeMillis();
ModuleArchive v1 = writeArchive(now - 60_000, Map.of("same.jar", "1", "app.jar", "1", "edited.jar", "1", "sub/old.jar", "1"));
File exploded = v1.extractAll();
File same = libJar(exploded, "same.jar");
File edited = libJar(exploded, "edited.jar");
File old = libJar(exploded, "sub/old.jar");
File stray = libJar(exploded, "stray.txt");
long sameLastModified = same.lastModified();
Files.write(edited.toPath(), innerJar("9"));
Files.writeString(stray.toPath(), "not from the archive");

ModuleArchive v2 = writeArchive(now, Map.of("same.jar", "1", "app.jar", "2", "edited.jar", "1"));
v2.extractAll();

assertEquals("Unchanged entry was rewritten", sameLastModified, same.lastModified());
assertEquals("2", readVersion(libJar(exploded, "app.jar")));
assertEquals("1", readVersion(edited));
assertFalse(old.exists());
assertFalse(old.getParentFile().exists());
assertFalse(stray.exists());
assertFalse(v2.isModified());
}

@Test
public void testCaseOnlyRenameKeepsFile() throws IOException
{
long now = System.currentTimeMillis();
File exploded = writeArchive(now - 60_000, Map.of("dep.jar", "1", "app.jar", "1")).extractAll();

ModuleArchive v2 = writeArchive(now, Map.of("Dep.jar", "1", "App.jar", "2"));
v2.extractAll();

assertEquals("1", readVersion(libJar(exploded, "Dep.jar")));
assertEquals("2", readVersion(libJar(exploded, "App.jar")));
assertFalse(v2.isModified());
}

@Test
public void testFileAndDirectorySwapPlaces() throws IOException
{
long now = System.currentTimeMillis();
File exploded = writeArchive(now - 60_000, Map.of("a.jar", "1", "b/c.jar", "1")).extractAll();

ModuleArchive v2 = writeArchive(now, Map.of("a.jar/d.jar", "2", "b", "2"));
v2.extractAll();

assertEquals("2", readVersion(libJar(exploded, "a.jar/d.jar")));
assertEquals("2", readVersion(libJar(exploded, "b")));
assertFalse(v2.isModified());
}

private static File libJar(File exploded, String name)
{
return FileUtil.appendPath(exploded, org.labkey.api.util.Path.parse("lib/" + name));
Expand Down
14 changes: 14 additions & 0 deletions api/src/org/labkey/api/security/Encryption.java
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,20 @@ static void registerHandler(EncryptionMigrationHandler handler)
void deleteEncryptedContent();
}

/** A brand-new database holds no legacy-cipher content, so record the current cipher to skip that migration. */
public static void recordCurrentCipherForNewInstall()
{
if (!isEncryptionPassPhraseSpecified() || !ModuleLoader.getInstance().shouldInsertData())
return;

WritablePropertyMap cipherProps = PropertyManager.getNormalStore().getWritableProperties(ENCRYPTION_CIPHER_CATEGORY, true);
if (cipherProps.get(CIPHER_PROPERTY) == null)
{
cipherProps.put(CIPHER_PROPERTY, AESConfig.current.getCipherName());
cipherProps.save();
}
}

/**
* Examines the database to determine whether algorithm or key migration is pending, and if so installs a
* fallback algorithm. This allows HTTP requests to transparently decrypt not-yet-migrated values during the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,8 @@ public void setStackTrace(String stackTrace) {
*/
public static abstract class SecurityEscalationAuditDomainKind extends AbstractAuditDomainKind
{
private static Set<PropertyDescriptor> _fields = null;
// Per instance: each subclass's property URIs must come from its own domain URI
private Set<PropertyDescriptor> _fields = null;

protected static final String NAMESPACE_PREFIX = "Audit-";

Expand Down
37 changes: 32 additions & 5 deletions audit/src/org/labkey/audit/AuditLogImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
import org.labkey.api.util.Pair;
import org.labkey.api.util.StartupListener;
import org.labkey.api.util.TestContext;
import org.labkey.api.util.UnexpectedException;
import org.labkey.api.util.logging.LogHelper;
import org.labkey.api.view.ActionURL;
import org.labkey.api.view.HttpView;
Expand All @@ -77,6 +78,10 @@
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;

Expand All @@ -89,6 +94,7 @@ public class AuditLogImpl implements AuditLogService, StartupListener
private final Queue<Pair<User, AuditTypeEvent>> _eventTypeQueue = new LinkedList<>();
private final AtomicBoolean _logToDatabase = new AtomicBoolean(false);
private static final Object STARTUP_LOCK = new Object();
private static final int PROVIDER_INIT_THREADS = 8;

// Cache the audit events associated with transaction ids. We currently use these for interacting with objects
// that were created immediately after they were created, so the cache size does not need to be very large and the defaultTimeToLive can be small.
Expand Down Expand Up @@ -120,11 +126,7 @@ public String getName()
@Override
public void moduleStartupComplete(ServletContext servletContext)
{
// perform audit provider initialization
for (AuditTypeProvider provider : AuditLogService.get().getAuditProviders())
{
provider.initializeProvider(User.getAdminServiceUser());
}
initializeProviders(AuditLogService.get().getAuditProviders(), User.getAdminServiceUser());

// Synchronize so that we can guarantee that all events have already been added to the queue before we
// start processing them
Expand All @@ -140,6 +142,31 @@ public void moduleStartupComplete(ServletContext servletContext)
}
}

// Each provider touches only its own domain and storage table, in its own transaction, and mostly waits on the database
private static void initializeProviders(List<AuditTypeProvider> providers, User user)
{
int threads = Math.clamp(providers.size(), 1, PROVIDER_INIT_THREADS);

try (ExecutorService pool = Executors.newFixedThreadPool(threads, Thread.ofPlatform().name("Audit Provider Init ", 1).factory()))
{
List<Future<?>> futures = providers.stream()
.<Future<?>>map(provider -> pool.submit(() -> provider.initializeProvider(user)))
.toList();

for (Future<?> future : futures)
future.get();
}
catch (ExecutionException e)
{
UnexpectedException.rethrow(e.getCause());
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
throw UnexpectedException.wrap(e);
}
}

@Override
public boolean isViewable()
{
Expand Down
Loading