Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package com.idea2strategy.trading.worker;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
* A login that holds nothing but {@code idea2strategy_trading}, the way deployment wires the trading
* runtime.
*
* <p>The Testcontainers user owns every table, so a test that runs the worker as that user proves
* nothing about the generated grants. Running the worker's SQL through this login instead fails the
* test with {@code permission denied} the moment the trading role is granted less than it executes.
*/
public final class TradingRuntimeRole {
public static final String LOGIN = "trading_runtime_probe";
public static final String PASSWORD = "trading-runtime-probe";

private TradingRuntimeRole() {}

/** Installs the login through {@code admin} and returns a data source that connects as it. */
public static DriverManagerDataSource dataSource(String jdbcUrl, DataSource admin) {
install(admin);
DriverManagerDataSource runtime = new DriverManagerDataSource(jdbcUrl, LOGIN, PASSWORD);
try (Connection connection = runtime.getConnection();
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("""
select role.rolsuper or role.rolbypassrls,
(select array_agg(granted.rolname::text order by granted.rolname)
from pg_auth_members membership
join pg_roles granted on granted.oid = membership.roleid
where membership.member = role.oid)
from pg_roles role
where role.rolname = current_user
""")) {
result.next();
if (result.getBoolean(1)) {
throw new IllegalStateException(LOGIN + " must not bypass privilege checks");
}
String memberships = result.getString(2);
if (!"{idea2strategy_trading}".equals(memberships)) {
throw new IllegalStateException(
LOGIN + " must hold only idea2strategy_trading, but holds " + memberships);
}
} catch (SQLException failure) {
throw new IllegalStateException(failure);
}
return runtime;
}

/**
* Bridges a gap outside the scope of these tests: the BEFORE INSERT trigger on
* {@code trading.orders} calls {@code identity.require_active_account}, a SECURITY INVOKER
* function that locks {@code identity.accounts} FOR SHARE, and the trading role holds nothing in
* {@code identity}. Granted to the login directly, never to {@code idea2strategy_trading}, so
* the generated grants under test stay exactly as the central bundle ships them.
*/
public static void bridgeOrderCreationGuard(DataSource admin) {
install(admin);
try (Connection connection = admin.getConnection(); Statement statement = connection.createStatement()) {
statement.execute("GRANT USAGE ON SCHEMA identity TO " + LOGIN);
statement.execute("GRANT SELECT, UPDATE ON identity.accounts TO " + LOGIN);
} catch (SQLException failure) {
throw new IllegalStateException(failure);
}
}

/** Creates the login once per database and grants it the trading group role. */
public static void install(DataSource admin) {
try (Connection connection = admin.getConnection(); Statement statement = connection.createStatement()) {
statement.execute("""
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '%s') THEN
CREATE ROLE %s LOGIN INHERIT PASSWORD '%s';
END IF;
END $$
""".formatted(LOGIN, LOGIN, PASSWORD));
statement.execute("GRANT idea2strategy_trading TO " + LOGIN);
} catch (SQLException failure) {
throw new IllegalStateException(failure);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import com.idea2strategy.trading.strategy.runtime.warmup.FeatureObservation;
import com.idea2strategy.trading.strategy.runtime.warmup.PreparedWarmup;
import com.idea2strategy.trading.strategy.runtime.warmup.WarmupFeatureSeries;
import com.idea2strategy.trading.worker.TradingRuntimeRole;
import com.idea2strategy.trading.worker.runtime.EvaluatingBotRuntime;
import java.math.BigDecimal;
import java.nio.file.Files;
Expand Down Expand Up @@ -115,9 +116,14 @@ static void properties(DynamicPropertyRegistry registry) {
POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword());
CanonicalBaseline.migrateWithContributions(dataSource);
seed(dataSource);
TradingRuntimeRole.dataSource(POSTGRES.getJdbcUrl(), dataSource);
TradingRuntimeRole.bridgeOrderCreationGuard(dataSource);
registry.add("spring.datasource.url", POSTGRES::getJdbcUrl);
registry.add("spring.datasource.username", POSTGRES::getUsername);
registry.add("spring.datasource.password", POSTGRES::getPassword);
registry.add("spring.datasource.username", () -> TradingRuntimeRole.LOGIN);
registry.add("spring.datasource.password", () -> TradingRuntimeRole.PASSWORD);
// The test-only Flyway step migrates as the owner; the worker itself never migrates.
registry.add("spring.flyway.user", POSTGRES::getUsername);
registry.add("spring.flyway.password", POSTGRES::getPassword);
registry.add("trading.warmup.bundle-root", WARMUP_ROOT::toString);
registry.add(
"trading.warmup.materialization-receipt-path",
Expand Down Expand Up @@ -169,7 +175,11 @@ BotStartupGate preparedWarmupGate() {
private EvaluatingBotRuntime runtime;

@Autowired
private JdbcClient jdbc;
private JdbcClient runtimeJdbc;

/** Fixtures and assertions run as the container owner; the worker runs as the trading role. */
private final JdbcClient jdbc = JdbcClient.create(new DriverManagerDataSource(
POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()));

/** The clock the poller leases with, so a case can let a lease lapse without waiting for one. */
private final AdvanceableClock clock = new AdvanceableClock(POLL_AT);
Expand All @@ -188,7 +198,7 @@ void resetControlStateAndCanonicalRecord() {
runtime.stop(BOT, "TEST_RESET");
clock.set(POLL_AT);
poller = new StrategyBotOutboxPoller(
jdbc, consumer, clock, StrategyBotControlTransportConfiguration.HANDLER_ID,
runtimeJdbc, consumer, clock, StrategyBotControlTransportConfiguration.HANDLER_ID,
"b91-worker", 32, Duration.ofSeconds(30), Duration.ofSeconds(30), 5);
jdbc.sql("""
truncate trading.order_intent_batches, trading.order_intents, trading.orders,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.idea2strategy.trading.strategy.runtime.control.StrategyBotExecutionPlanAdapter;
import com.idea2strategy.trading.strategy.runtime.plan.ExecutionPlanCompatibility;
import com.idea2strategy.trading.strategy.runtime.plan.LoadedExecutionPlan;
import com.idea2strategy.trading.worker.TradingRuntimeRole;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
Expand Down Expand Up @@ -74,6 +75,9 @@ class StrategyBotOutboxPollerE2ETest {
static void databaseProperties(DynamicPropertyRegistry registry) {
CanonicalBaseline.migrateWithContributions(new DriverManagerDataSource(
POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()));
runtimeJdbc = JdbcClient.create(TradingRuntimeRole.dataSource(
POSTGRES.getJdbcUrl(), new DriverManagerDataSource(
POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())));
registry.add("spring.datasource.url", POSTGRES::getJdbcUrl);
registry.add("spring.datasource.username", POSTGRES::getUsername);
registry.add("spring.datasource.password", POSTGRES::getPassword);
Expand All @@ -82,6 +86,9 @@ static void databaseProperties(DynamicPropertyRegistry registry) {
@Autowired
private JdbcClient jdbc;

/** The poller and checkpoint store run as the trading role; fixtures run as the owner. */
private static JdbcClient runtimeJdbc;

private BotControlCheckpointStore checkpoints;
private final List<String> lifecycleEvents = new ArrayList<>();
private MutableClock clock;
Expand All @@ -92,7 +99,7 @@ void wire() {
jdbc.sql("delete from operations.outbox_consumer_receipts").update();
jdbc.sql("delete from operations.outbox_messages").update();
lifecycleEvents.clear();
checkpoints = new OutboxReceiptBotControlCheckpointStore(jdbc, HANDLER);
checkpoints = new OutboxReceiptBotControlCheckpointStore(runtimeJdbc, HANDLER);
clock = new MutableClock(T0);
StrategyBotControlConsumer consumer = new StrategyBotControlConsumer(
new StrategyBotContractCodec(),
Expand All @@ -108,7 +115,7 @@ void wire() {
StrategyBotExecutionPlanAdapter.RUNTIME_SCHEMA_VERSION,
Map.of()));
poller = new StrategyBotOutboxPoller(
jdbc, consumer, clock, HANDLER, "rt5-e2e-worker", 10,
runtimeJdbc, consumer, clock, HANDLER, "rt5-e2e-worker", 10,
Duration.ofSeconds(30), Duration.ofSeconds(60), 3);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import com.idea2strategy.trading.persistence.fill.PostgresFillRecordStore;
import com.idea2strategy.trading.persistence.order.PostgresOrderLifecycleStore;
import com.idea2strategy.trading.persistence.position.PostgresPositionLotStore;
import com.idea2strategy.trading.worker.TradingRuntimeRole;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Statement;
Expand Down Expand Up @@ -113,6 +114,8 @@ class ApprovedCorporateActionPollerE2ETest {
private static DriverManagerDataSource dataSource;
private static JdbcClient jdbc;
private static JdbcTransactionManager transactions;
private static JdbcClient runtimeJdbc;
private static JdbcTransactionManager runtimeTransactions;
private static ApprovedCorporateActionPoller poller;
private static BotContext firstBot;
private static BotContext secondBot;
Expand All @@ -124,10 +127,14 @@ static void migrateAndSeed() throws Exception {
CanonicalBaseline.migrateWithContributions(dataSource);
jdbc = JdbcClient.create(dataSource);
transactions = new JdbcTransactionManager(dataSource);
DriverManagerDataSource runtime = TradingRuntimeRole.dataSource(
POSTGRES.getJdbcUrl(), dataSource);
runtimeJdbc = JdbcClient.create(runtime);
runtimeTransactions = new JdbcTransactionManager(runtime);
poller = new ApprovedCorporateActionPoller(
jdbc, new PostgresBotEventStore(jdbc, transactions),
new CorporateActionService(new PostgresCorporateActionStore(jdbc, transactions)),
new ObjectMapper(), Clock.fixed(NOW, ZoneOffset.UTC), transactions);
runtimeJdbc, new PostgresBotEventStore(runtimeJdbc, runtimeTransactions),
new CorporateActionService(new PostgresCorporateActionStore(runtimeJdbc, runtimeTransactions)),
new ObjectMapper(), Clock.fixed(NOW, ZoneOffset.UTC), runtimeTransactions);

firstBot = new BotContext(1);
secondBot = new BotContext(2);
Expand Down Expand Up @@ -281,7 +288,7 @@ void retriesATransientFailureWithoutLeavingPartialBusinessState() throws Excepti
EFFECTIVE_AT.plusSeconds(1), 2, 1, null,
approvedReview(RETRIED_SPLIT, termsHash(RETRIED_SPLIT)));

CorporateActionStore canonical = new PostgresCorporateActionStore(jdbc, transactions);
CorporateActionStore canonical = new PostgresCorporateActionStore(runtimeJdbc, runtimeTransactions);
AtomicInteger attempts = new AtomicInteger();
CorporateActionStore failsOnce = application -> {
if (application.action().actionId().equals(RETRIED_SPLIT)
Expand Down Expand Up @@ -330,8 +337,8 @@ void processesDurableInputByEffectiveTimeThenStableIdentity() throws Exception {

private static ApprovedCorporateActionPoller poller(CorporateActionService service) {
return new ApprovedCorporateActionPoller(
jdbc, new PostgresBotEventStore(jdbc, transactions), service,
new ObjectMapper(), Clock.fixed(NOW, ZoneOffset.UTC), transactions);
runtimeJdbc, new PostgresBotEventStore(runtimeJdbc, runtimeTransactions), service,
new ObjectMapper(), Clock.fixed(NOW, ZoneOffset.UTC), runtimeTransactions);
}

private static void insertAction(UUID id, UUID instrumentId, UUID manifestId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.idea2strategy.trading.persistence.canonical.CanonicalBaseline;
import com.idea2strategy.trading.persistence.event.PostgresBotEventStore;
import com.idea2strategy.trading.persistence.ledger.PostgresLedgerStore;
import com.idea2strategy.trading.worker.TradingRuntimeRole;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.Statement;
Expand Down Expand Up @@ -55,13 +56,19 @@ class RoomEvaluationAccountOpenPollerE2ETest {
private static DriverManagerDataSource dataSource;
private static JdbcTransactionManager transactions;
private static JdbcClient jdbc;
private static JdbcTransactionManager runtimeTransactions;
private static JdbcClient runtimeJdbc;

@BeforeAll
static void database() throws Exception {
dataSource = new DriverManagerDataSource(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword());
CanonicalBaseline.migrateWithContributions(dataSource);
transactions = new JdbcTransactionManager(dataSource);
jdbc = JdbcClient.create(dataSource);
DriverManagerDataSource runtime = TradingRuntimeRole.dataSource(
POSTGRES.getJdbcUrl(), dataSource);
runtimeTransactions = new JdbcTransactionManager(runtime);
runtimeJdbc = JdbcClient.create(runtime);
// Backend's preceding root #181 envelope migration; remove this compatibility step when
// the next pinned canonical baseline includes V20260804145900.
jdbc.sql("alter table operations.outbox_messages alter column event_schema_version type varchar(80)").update();
Expand Down Expand Up @@ -93,7 +100,7 @@ void clear() {
@Test
void opensExactlyOneBalancedLedgerAndPublishesOneCompletionAcrossRedelivery() {
seedRequest(message(1), "room-open:" + PARTICIPATION, "100000.00000000");
RoomEvaluationAccountOpenPoller poller = poller(new PostgresLedgerStore(jdbc, transactions));
RoomEvaluationAccountOpenPoller poller = poller(new PostgresLedgerStore(runtimeJdbc, runtimeTransactions));

assertEquals(1, poller.pollOnce(10));
assertEquals(0, poller.pollOnce(10));
Expand All @@ -111,7 +118,7 @@ void opensExactlyOneBalancedLedgerAndPublishesOneCompletionAcrossRedelivery() {
void producerKeyReusedWithDifferentContentIsPermanentAndAuditedWithoutAnotherLedger() {
String producerKey = "room-open:" + PARTICIPATION;
seedRequest(message(1), producerKey, "100000.00000000");
RoomEvaluationAccountOpenPoller poller = poller(new PostgresLedgerStore(jdbc, transactions));
RoomEvaluationAccountOpenPoller poller = poller(new PostgresLedgerStore(runtimeJdbc, runtimeTransactions));
assertEquals(1, poller.pollOnce(10));

seedRequest(message(2), producerKey, "99999.00000000");
Expand Down Expand Up @@ -145,7 +152,7 @@ void expiredLeaseCannotBeStolenWhileTheEffectTransactionOwnsTheReceiptFence() th
MutableClock time = new MutableClock(NOW);
CountDownLatch effectEntered = new CountDownLatch(1);
CountDownLatch releaseEffect = new CountDownLatch(1);
BotEventStore delegate = new PostgresBotEventStore(jdbc, transactions);
BotEventStore delegate = new PostgresBotEventStore(runtimeJdbc, runtimeTransactions);
BotEventStore blocking = new BotEventStore() {
@Override public BotEvent appendOrLoad(BotEventAppend append) {
effectEntered.countDown();
Expand All @@ -161,8 +168,8 @@ void expiredLeaseCannotBeStolenWhileTheEffectTransactionOwnsTheReceiptFence() th
return delegate.find(botId, eventId);
}
};
var first = poller(blocking, new PostgresLedgerStore(jdbc, transactions), time, "worker-1", Duration.ofSeconds(1));
var second = poller(delegate, new PostgresLedgerStore(jdbc, transactions), time, "worker-2", Duration.ofSeconds(1));
var first = poller(blocking, new PostgresLedgerStore(runtimeJdbc, runtimeTransactions), time, "worker-1", Duration.ofSeconds(1));
var second = poller(delegate, new PostgresLedgerStore(runtimeJdbc, runtimeTransactions), time, "worker-2", Duration.ofSeconds(1));

try (var executor = Executors.newFixedThreadPool(2)) {
var firstResult = executor.submit(() -> first.pollOnce(1));
Expand All @@ -186,15 +193,15 @@ void expiredLeaseCannotBeStolenWhileTheEffectTransactionOwnsTheReceiptFence() th
}

private RoomEvaluationAccountOpenPoller poller(LedgerStore ledger) {
return poller(new PostgresBotEventStore(jdbc, transactions), ledger,
return poller(new PostgresBotEventStore(runtimeJdbc, runtimeTransactions), ledger,
Clock.fixed(NOW, ZoneOffset.UTC), "root-181-test", Duration.ofSeconds(30));
}

private RoomEvaluationAccountOpenPoller poller(
BotEventStore events, LedgerStore ledger, Clock clock, String worker, Duration lease) {
return new RoomEvaluationAccountOpenPoller(
jdbc, events, ledger, new ObjectMapper(), clock, worker, lease,
Duration.ofSeconds(30), 3, transactions);
runtimeJdbc, events, ledger, new ObjectMapper(), clock, worker, lease,
Duration.ofSeconds(30), 3, runtimeTransactions);
}

private void seedRequest(UUID messageId, String producerKey, String initialCash) {
Expand Down
Loading
Loading