Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
5f02b1f
Receive hosting provider execution and expanded canonical owner proof
codex Nov 8, 2026
0b79e56
Carry verified #3390 CLI19 fixes into #3414
codex Nov 8, 2026
9c6773d
Carry verified #3390 CLI21 fixes into #3414
codex Nov 8, 2026
34563e2
Carry verified #3390 CLI21 fixture correction fixes into #3414
codex Nov 8, 2026
7f4d7c4
Carry verified #3390 CLI22 attestation and scoped test fixes into #3414
codex Nov 8, 2026
024db71
docs: clarify hosting settlement and deletion gaps
codex Nov 8, 2026
0567827
Preserve composition failure evidence and clarify historical proof
codex Nov 8, 2026
1d15662
Align deletion capability status with retained numeric scope
codex Nov 8, 2026
c975a2b
Carry Account CI stall diagnostics into #3414
codex Nov 8, 2026
b6d81d0
docs: anchor hosting provisioning capability evidence
codex Nov 8, 2026
c0dbc80
Carry diagnostic lint and provisioning tracker corrections into #3414
codex Nov 8, 2026
e7392fa
Serialize numbered Account CI checks and expose bounded stall coverage
codex Nov 8, 2026
16e6814
Carry bounded Account CI reliability experiment into #3414
codex Nov 8, 2026
a03ca0d
Carry validated CI and JWKS repairs through #3414
codex Nov 8, 2026
fea79ed
Carry Account expiry fixture repair through #3414
codex Nov 8, 2026
91496fc
Merge database-time dispatch fences into provider receiving
codex Nov 8, 2026
1e90961
Carry complete smoke proof fingerprints into #3414
benhook1013 Nov 8, 2026
6df2590
Carry tenant-qualified browser discovery through #3414
benhook1013 Nov 8, 2026
0f5c56f
Carry committed JOIN replay correction through #3414
benhook1013 Nov 8, 2026
f2f5419
Carry Hosted12 qualified selector and proof corrections through #3414
benhook1013 Nov 9, 2026
b03b13b
Carry CLI27 JOIN attempt diagnostic correction through #3414
benhook1013 Nov 9, 2026
1aedb99
Carry smoke intake and optional capture fixes through #3414
benhook1013 Nov 9, 2026
d843146
Carry truthful JOIN replay and tenant diagnostics through #3414
benhook1013 Nov 9, 2026
e940366
Qualify canonical JOIN integration selectors with tenant scope
benhook1013 Nov 9, 2026
05e53d1
Use PostgreSQL time in subscription lifecycle integration tests
benhook1013 Nov 9, 2026
e67a1cd
Keep inactive membership fixture evidence in sync
benhook1013 Nov 9, 2026
cdea81a
Carry bounded PLAY transition CI and review fixes through #3414
benhook1013 Nov 9, 2026
95cb239
Carry session-correlation and verified Gradle recovery through #3414
benhook1013 Nov 9, 2026
23b790a
Carry hosted smoke contract and own wrapper transport retries
benhook1013 Nov 9, 2026
232062a
Carry capped root CI repair without widening provider scope
benhook1013 Nov 9, 2026
adbf76d
Keep wrapper transport tuning in the existing CI owner
benhook1013 Nov 9, 2026
05ebdca
Reconcile provider execution with merged develop
benhook1013 Nov 9, 2026
ff03545
Prove first-invoice dispatch recovery without premature activation
benhook1013 Nov 9, 2026
3eb48d5
Preserve committed provisioning on unavailable current readback
benhook1013 Nov 9, 2026
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
Expand Up @@ -166,6 +166,10 @@ Subscription creation, lifecycle, and entitlements are covered in more detail in
6. Stripe webhooks caused by initial provisioning or an explicit existing-subscription update resolve through the exact typed `subscription_provisioning` or `subscription_update` operation identity carried in provider metadata. Provider-lifecycle events such as subscription status or invoice events that do not originate from a current command use a separate `subscription_lifecycle` correlation: Account verifies the signature, deduplicates by Stripe `event.id` in `stripe_event_inbox`, resolves the provider subscription ID from the event payload to the unique canonical subscription and its immutable internal `subscriptionId`, and does not fabricate or reuse a command operation identity. If the provider ID is not yet linked or the local row cannot be resolved, the inbox correlation remains durably `pending` with retry state; reconciliation looks up current provider state, repairs the provider-ID/local-row linkage, and then applies a guarded transition. Replayed events are no-ops after durable deduplication, while out-of-order or ambiguous lifecycle events remain pending for reconciliation rather than regressing local state. Both command and lifecycle paths keep the internal `subscription` table in sync.
7. Changes to `subscription.status` are propagated to tenant-management and quota-enforcement components so that tenant availability and resource limits reflect the current billing state. For hard cutoff transitions such as `suspended` or `canceled`, Account transactionally advances the durable tenant authority generation with the committed billing state and emits `SubscriptionStatusChanged` plus `TenantBillingStateChanged`. Downstream services consume those events to invalidate projections and terminate affected gameplay sessions; they never advance Account authority themselves. See [Subscription Management](./subscription-management.md#tenant-availability-and-quota-enforcement) and [Session Behavior](../../system-architecture-session-behavior.md#session-and-identity-management).

#### Investigating an ambiguous first dispatch

For a `subscription_provisioning_operator_outbox` item with `STALLED_WITHOUT_COMMITTED_PROGRESS` or `ABSOLUTE_DEADLINE`, correlate the original request and subscription IDs with the immutable provider dispatch claim. A `FIRST_DISPATCH` claim records that one invocation obtained permission, which it can lose before sending the create. If the provider subscription ID is absent, a lost response and an unsent request remain indistinguishable from the claim alone. Check the original provisioning metadata and exact customer binding through the authorized read-only reconciliation path. Empty search or list results leave the outcome unresolved. Retain the reservation and operator item until the existing guarded reconciliation or terminal cleanup can establish its required evidence. The claim and outbox item confer no permission to issue another create.

## Multi-Tenancy and Security

Stripe integration must preserve tenant isolation while allowing platform-level reporting:
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
package net.firedevops.firemud.accountservice.client;

import com.stripe.exception.StripeException;
import com.stripe.model.StripeSearchResult;
import com.stripe.model.Subscription;
import com.stripe.net.RequestOptions;
import com.stripe.param.SubscriptionCreateParams;
import com.stripe.param.SubscriptionListParams;
import com.stripe.param.SubscriptionSearchParams;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.Objects;
import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
* Held initial hosting-subscription SDK adapter. Only a private, independently read durable owner
* dispatch supplies its explicit customer, instrument, quote and initial-call permission. Existing
* or pre-migration unknown dispatches reconcile only; no empty search authorizes recreation. No
* actor authorization, update/cancel command, runtime registration or entitlement is supplied.
*/
public final class StripeHostingSubscriptionProvisioner {
private static final long MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER = 100L;

private final com.stripe.StripeClient stripe;
private final Clock clock;
private final RequestOptions requestOptions;
private final StripeHostingSubscriptionObserver observer;
private final StripeBillingPrerequisiteObserver prerequisites;

@SuppressFBWarnings(
value = "EI_EXPOSE_REP2",
justification =
"Injected SDK/repository collaborators remain private; copying would break owner composition.")
public StripeHostingSubscriptionProvisioner(
com.stripe.StripeClient stripe,
Clock clock,
boolean expectedLivemode,
Duration connectTimeout,
Duration readTimeout) {
this.stripe = Objects.requireNonNull(stripe);
this.clock = Objects.requireNonNull(clock);
observer = new StripeHostingSubscriptionObserver(stripe, clock, connectTimeout, readTimeout);
// The observer validates positive whole-millisecond SDK limits before this conversion.
requestOptions =
RequestOptions.builder()
.setConnectTimeout(Math.toIntExact(connectTimeout.toMillis()))
.setReadTimeout(Math.toIntExact(readTimeout.toMillis()))
.setMaxNetworkRetries(0)
.build();
prerequisites = new StripeBillingPrerequisiteObserver(stripe, clock, expectedLivemode);
}

public Result provision(ProviderDispatch dispatch) {
Objects.requireNonNull(dispatch);
requireNoTransaction();
if (!dispatch.readyForProviderIo()) {
throw new IllegalStateException(
"Committed independent provider-dispatch readback is required");
}
if (!live(dispatch)) {
return new Pending("DISPATCH_LEASE_EXPIRED", null);
}
var creation = dispatch.claim().creation();
// Local reservations do not prove that the provider's instrument is still attached.
var prerequisite =
prerequisites.observe(
new StripeBillingPrerequisiteObserver.ExpectedBinding(
creation.owner().accountUuid(),
creation.customerProvisioningRequestId(),
dispatch.customerProviderIdempotencyId(),
creation.providerCustomerId(),
dispatch.providerPaymentMethodId()),
requestOptions);
if (!(prerequisite instanceof StripeBillingPrerequisiteObserver.ObservedBillingPrerequisites)) {
return new Pending("PROVIDER_PREREQUISITES_UNRESOLVED", null);
}
if (!live(dispatch)) {
return new Pending("DISPATCH_LEASE_EXPIRED", null);
}
Map<String, String> metadata =
Map.of(
"firemud_metadata_schema_version",
"1",
"firemud_operation_type",
"subscription_provisioning",
"firemud_operation_id",
creation.subscriptionProvisioningRequestId().toString(),
"firemud_subscription_id",
creation.subscriptionId().toString());
try {
String query =
"metadata['firemud_metadata_schema_version']:'1' AND "
+ "metadata['firemud_operation_type']:'subscription_provisioning' AND "
+ "metadata['firemud_operation_id']:'"
+ creation.subscriptionProvisioningRequestId()
+ "' AND metadata['firemud_subscription_id']:'"
+ creation.subscriptionId()
+ "'";
StripeSearchResult<Subscription> matches =
stripe
.subscriptions()
.search(
SubscriptionSearchParams.builder().setQuery(query).setLimit(2L).build(),
requestOptions);
if (matches == null
|| matches.getData() == null
|| !Boolean.FALSE.equals(matches.getHasMore())
|| matches.getData().size() > 1) {
return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_SEARCH", null);
}
Subscription candidate;
if (matches.getData().isEmpty()) {
if (!dispatch.initialCallAllowed()) {
if (!live(dispatch)) {
return new Pending("DISPATCH_LEASE_EXPIRED", null);
}
var listed =
stripe
.subscriptions()
.list(
SubscriptionListParams.builder()
.setCustomer(creation.providerCustomerId())
.setStatus(SubscriptionListParams.Status.ALL)
.setLimit(MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER)
.build(),
requestOptions);
if (listed == null
|| listed.getData() == null
|| !Boolean.FALSE.equals(listed.getHasMore())
|| listed.getData().size() > MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER) {
return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null);
}
candidate = null;
for (Subscription listedCandidate : listed.getData()) {
if (listedCandidate == null) {
return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null);
}
if (metadata.equals(listedCandidate.getMetadata())) {
if (!creation.providerCustomerId().equals(listedCandidate.getCustomer())) {
return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null);
}
if (candidate != null) {
return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null);
}
candidate = listedCandidate;
}
}
if (candidate == null) {
return new Pending("PROVIDER_LOOKUP_UNRESOLVED", null);
}
} else {
if (!live(dispatch)) {
return new Pending("DISPATCH_LEASE_EXPIRED", null);
}
candidate =
stripe
.subscriptions()
.create(
SubscriptionCreateParams.builder()
.setCustomer(creation.providerCustomerId())
.setDefaultPaymentMethod(dispatch.providerPaymentMethodId())
.setCollectionMethod(
SubscriptionCreateParams.CollectionMethod.CHARGE_AUTOMATICALLY)
.setPaymentBehavior(
SubscriptionCreateParams.PaymentBehavior.DEFAULT_INCOMPLETE)
.addItem(
SubscriptionCreateParams.Item.builder()
.setPrice(creation.planQuote().providerPriceId())
.setQuantity(creation.planQuote().providerQuantity())
.build())
.putAllMetadata(metadata)
.build(),
requestOptions
.toBuilderFullCopy()
.setIdempotencyKey(
creation.subscriptionProvisioningRequestId().toString())
.build());
}
} else {
candidate = matches.getData().getFirst();
}
// Candidate status is never authority. Exact identity and metadata only select readback.
if (candidate == null
|| !"subscription".equals(candidate.getObject())
|| candidate.getId() == null
|| !candidate.getId().matches("sub_[A-Za-z0-9]{1,251}")
|| !metadata.equals(candidate.getMetadata())) {
return new Pending("PROVIDER_CANDIDATE_BINDING_INVALID", null);
}
if (!live(dispatch)) {
return new Pending("DISPATCH_LEASE_EXPIRED", null);
}
var observed = observer.observe(dispatch.expectedBinding(candidate.getId()));
if (!(observed instanceof StripeHostingSubscriptionObserver.ObservedSubscription actual)) {
return new Pending("INDEPENDENT_PROVIDER_READBACK_UNRESOLVED", null);
}
return new Located(actual);
} catch (StripeException failure) {
return new Pending("PROVIDER_OUTCOME_UNKNOWN", failure);
}
}

private boolean live(ProviderDispatch dispatch) {
var now = clock.instant();
return !now.isBefore(dispatch.claim().claimedAt())
&& now.isBefore(dispatch.claim().expiresAt());
}

private static void requireNoTransaction() {
if (TransactionSynchronizationManager.isActualTransactionActive()
|| TransactionSynchronizationManager.isSynchronizationActive()) {
throw new IllegalStateException("Hosting provider IO refuses an ambient SQL transaction");
}
}

public sealed interface Result permits Pending, Located {}

@SuppressFBWarnings(
value = "EI_EXPOSE_REP",
justification =
"The SDK exception is an internal diagnostic cause, never provider authority or a public response.")
public record Pending(String reason, StripeException providerFailure) implements Result {}

/** Locator plus genuine private observer evidence; lifecycle commit independently reads again. */
public static final class Located implements Result {
private final StripeHostingSubscriptionObserver.ObservedSubscription observation;

private Located(StripeHostingSubscriptionObserver.ObservedSubscription observation) {
this.observation = observation;
}

public StripeHostingSubscriptionObserver.ObservedSubscription observation() {
return observation;
}

public String providerSubscriptionId() {
return observation.providerSubscriptionId();
}
}
}
Loading
Loading