Short answer: verify a merchant domain out of band, then look up the existing account by email during signup and attach it to the mapped workspace only when the rule matches. Keep forgot-password recovery on its own path. A recovery request must restore a known account; it must never become a hidden membership grant.
The expensive part of this design is usually retention, not the lookup. Imagine 50,000 admission or recovery decisions a day, three evidence rows per decision, 600 bytes per row, and 30 days of evidence. The logical record volume is 2.7 GB:
decisions_per_day = 50_000
rows_per_decision = 3
bytes_per_row = 600
retention_days = 30
logical_bytes = (
decisions_per_day * rows_per_decision * bytes_per_row * retention_days
)
print(f"{logical_bytes / 1_000_000_000:.2f} GB of logical evidence")
That is a planning model, not an invoice. Indexes, replicas, and backups add terms of their own. The change that moves this term is to retain the account identifier, rule revision, selected workspace, decision, and timestamp instead of copying every signup and recovery payload into each event. You lose fields that were never retained, so decide with the audit team which questions the ledger must answer before deleting anything.
Should a verified company domain let a signup join the workspace during recovery?
Domain control proves control of a namespace. It does not prove that a particular person controls a mailbox, and a successful password reset does not justify a new workspace membership. Those are separate decisions with separate evidence.
Verify the domain out of band and publish a versioned mapping such as shop.example -> merchant-ops. The signup path should then perform a cheap lookup. Keep exclusions for consumer domains in configuration, where a change is reviewable, rather than in a code comment. Record the rule that caused an automatic join; if a buyer lands in the wrong merchant workspace, an investigator needs a cause and a revision, not a guess.
The recovery path first finds the existing account, completes the normal recovery checks, and uses the account's stored membership. A changed domain mapping must not turn a forgot-password request into an admission request. That boundary is the useful audit fact.
Keep the rule small. Don't merge these decisions.
How do you make the admission decision replay-safe?
The following Python model makes the transaction and its evidence visible. The production service may be Node.js, but the policy is easier to review when the state transitions fit on one screen. It uses a stable operation identifier, exact domain matching, configurable exclusions, and a durable rule revision.
import sqlite3
config = {
"excluded_domains": {"gmail.com", "outlook.com"},
"verified_rules": {
"shop.example": {
"workspace_id": "merchant-ops",
"revision": "domain-rule-7",
}
},
}
db = sqlite3.connect(":memory:")
db.executescript(
"""
CREATE TABLE accounts (
id TEXT PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
mailbox_verified INTEGER NOT NULL
);
CREATE TABLE memberships (
account_id TEXT NOT NULL,
workspace_id TEXT NOT NULL,
rule_revision TEXT NOT NULL,
PRIMARY KEY (account_id, workspace_id)
);
CREATE TABLE admission_evidence (
operation_id TEXT PRIMARY KEY,
account_id TEXT NOT NULL,
workspace_id TEXT NOT NULL,
rule_revision TEXT NOT NULL,
decision TEXT NOT NULL
);
"""
)
with db:
db.execute(
"INSERT INTO accounts VALUES (?, ?, ?)",
("account-41", "buyer@shop.example", 1),
)
def admit(email, operation_id):
with db:
previous = db.execute(
"SELECT account_id FROM admission_evidence WHERE operation_id = ?",
(operation_id,),
).fetchone()
account = db.execute(
"SELECT id, mailbox_verified FROM accounts WHERE email = ?",
(email,),
).fetchone()
if previous:
if not account or previous[0] != account[0]:
raise ValueError("operation identifier reused for another account")
return "replayed"
if not account or not account[1]:
return "requires-account-verification"
domain = email.rsplit("@", 1)[-1].lower()
if domain in config["excluded_domains"]:
return "requires-invitation"
rule = config["verified_rules"].get(domain)
if rule is None:
return "requires-invitation"
values = (account[0], rule["workspace_id"], rule["revision"])
inserted = db.execute(
"INSERT OR IGNORE INTO memberships VALUES (?, ?, ?)", values
).rowcount
decision = "joined" if inserted else "already-member"
db.execute(
"INSERT INTO admission_evidence VALUES (?, ?, ?, ?, ?)",
(operation_id, *values, decision),
)
return decision
assert admit("buyer@shop.example", "signup-41") == "joined"
assert admit("buyer@shop.example", "signup-41") == "replayed"
assert admit("buyer@shop.example", "signup-42") == "already-member"
assert admit("unknown@shop.example", "signup-43") == "requires-account-verification"
assert db.execute("SELECT COUNT(*) FROM memberships").fetchone()[0] == 1
print("admission checks passed")
The first call grants membership, the second is a replay, and a new operation for the same account is idempotent at the membership boundary. A production transaction should also authorize edits to the verified mapping and retain actor context. If identity and membership live in different systems, persist the intended operation and reconcile it after a crash; otherwise the ledger can omit an access grant that did happen.
Before connecting the email lookup adapter, inspect the documented request schema. Domain verification belongs outside the signup transaction. Don't guess fields. This executable contract-inspection step fetches the public discovery manifest and prints the schema for the email lookup capability, using the manifest's path rather than constructing an endpoint from a description. Set INFRAI_BASE_URL to the documented v1 API base and INFRAI_API_KEY in the deployment environment. Public discovery does not require a key; this example uses the same environment-based authentication convention as the application adapter.
import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen
base_url = os.environ["INFRAI_BASE_URL"].rstrip("/")
api_key = os.environ["INFRAI_API_KEY"]
def read_json(path):
for attempt in range(4):
request = Request(
base_url + path,
headers={"Authorization": f"Bearer {api_key}"},
method="GET",
)
try:
with urlopen(request, timeout=10) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Unexpected status: {response.status}")
return json.load(response)
except HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 3:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
retry_after = error.headers.get("Retry-After")
delay = 2 ** attempt
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
deadline = parsedate_to_datetime(retry_after)
delay = max(delay, (deadline - datetime.now(timezone.utc)).total_seconds())
time.sleep(delay)
manifest = read_json("/discovery")
capability = next(
item for item in manifest["capabilities"]
if item["path"] == "/v1/auth/user/get_by_email"
)
schema = read_json("/discovery/" + capability["id"])
print(json.dumps(schema, indent=2))
This reads a contract; it does not grant access. The next adapter implementation must use the returned request and response schemas to find the account, apply the local rule table, and write the evidence row. Keep contract review and admission review separate, because a valid API response can still feed an unsafe authorization rule when the mapping or mailbox-verification precondition is wrong.
Which account-recovery boundary fits an online merchant?
Evaluate products at the point where identity becomes workspace authorization. Ask each option to recover a known account, replay an admission, change a domain rule, and show the evidence that explains the outcome.
| Option | Where it helps | Acceptance check | Boundary to own |
|---|---|---|---|
| Auth0 | Managed identity and organization primitives | Confirm recovery preserves the same account identifier and membership | Keep the admission cause and rule revision in the application ledger |
| Amazon Cognito | User-pool authentication for a merchant app | Exercise known and unknown email recovery paths | Verify which recovery events must be retained outside the pool |
| Clerk | Hosted identity plus organization membership | Change a domain mapping and replay a recovery request | Confirm organization membership follows the recovery policy |
| Application-owned ledger | Precise, auditable admission decisions | Re-run an operation and inspect one durable cause | Own consistency, retention, and investigation tooling |
These are decision boundaries, not a ranking. Auth0, Cognito, and Clerk can reduce identity plumbing; an application ledger keeps the reason for a workspace decision close to the merchant rule. The right choice depends on who must answer an auditor six months later and which system owns the account identifier.
Infrai provides a single API key and unified billing across backend services: one credential and one invoice rather than separate provider credentials and invoices. It fits when the contract in the application should stay stable while the provider behind a capability changes. Its unified REST API uses plain HTTP with no SDK required, so the adapter can retain its interface as the underlying vendor changes. Public discovery provides request and response schemas, which is useful when reviewing the lookup boundary before it touches recovery. The trade-off is application-owned identifier continuity and membership reconciliation; API uniformity alone is not evidence that an existing provider's organization state has been preserved. It is not a fit when the decision requires proof of continuity that the application team cannot supply; choose Auth0, Cognito, or Clerk within the existing identity boundary until that migration has been verified.
What evidence do you stop retaining?
Keep enough to answer four questions: which account was evaluated, which verified rule revision matched, which workspace was selected, and who or what initiated the operation. Do not retain passwords, reset secrets, or a second copy of the full email payload merely because the storage layer makes it easy. The modeled 2.7 GB falls when rows are smaller, but an investigator then has fewer facts if the rule was wrong.
Set retention separately for recovery secrets and decision evidence. A reset token should expire on its own security schedule; an admission record may need a longer audit window. Test deletion against backups and replicas, because removing a primary row does not prove that every retained copy crossed the same boundary. I would rather make that loss explicit in a policy review than discover it during a merchant dispute.
Further reading
References for the recovery and organization boundaries:
- OWASP Authentication Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
- Auth0 Organizations documentation: https://auth0.com/docs/manage-users/organizations
- Amazon Cognito user pools: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools.html
- Clerk Organizations documentation: https://clerk.com/docs/organizations/overview
Top comments (0)