TL;DR
- Build app registration, tenant installation, and consent as separate records. Bind credentials and events to an installation and evaluate its current grants.
- Use a maintained OAuth authorization server for authorization code flow with PKCE. Enforce token audience, tenant, permission scope, and object access at the application boundary.
- Persist events with business changes, then deliver signed, versioned webhooks with bounded retries and durable delivery IDs.
- Offer an app-initiated WebSocket connection when partners cannot expose inbound HTTPS. Reuse event identities and authorization rules across both transports.
Decide what an installation authorizes
A B2B SaaS team wants to let approved partners synchronize orders and inventory. A merchant might consent to order reads while declining inventory writes. Later, the same partner signs up another merchant with a completely different set of grants. The marketplace now has to answer which app is calling, which installation the credential represents, and which resource and operation that installation can access.
Use three distinct records. App registration belongs to the developer and holds reviewed metadata, credentials, and registered redirect URIs. Installation belongs to the customer tenant and records its approved grants and lifecycle. Subscription belongs to an installation, identifies an event type and transport, and has independent delivery state. An app can have thousands of installations, while uninstalling one affects only that tenant.
A marketplace discovery page can come after the lifecycle works. Start with a developer portal, test installations, revocable credentials, and visible delivery failures. Customers should be able to view exactly what an app can read or change and how to remove it. During reviews, include requested scopes and related event types, whether the app stores or transmits customer data, and support ownership for failed deliveries.
Implement scoped OAuth 2.0 for tenant installation
Use a standards-based authorization server
Use authorization code flow with PKCE, exact registered redirect URI matching, and a supported authorization server. Bind the authorization transaction to the initiating browser session and verify the callback using the applicable anti-CSRF and issuer checks. Issue access tokens for narrow audiences and use the authorization server's supported refresh-token protection. Do not use a single shared app secret as the bearer credential for every tenant. The OAuth Security Best Current Practice covers client types, redirect protection, PKCE, token privilege restriction, and refresh rotation. RFC 9700 OAuth 2.0 Security Best Current Practice · RFC 7636 PKCE
At consent, verify that the signed-in user may install the app for the selected tenant. Compare requested scopes to the app's reviewed limits and the tenant's policies. Persist the approved set and link issued credentials to the installation. Scope additions need a new approval if they exceed earlier consent. An app update alone should never turn read access into permission to write. Slack's installation model is a useful concrete example of an app receiving scoped authorization from a workspace. Slack OAuth installation
Require both a token scope and a current installation grant
Keep authorizations independent of payload fields. The resource query derives tenant scope from the validated installation context, and its object predicate still checks that customer's order. The snippet below assumes a trusted verifier has already enforced token signature or introspection, issuer, expiration, and audience. It checks the normalized verified values against the live installation before permitting an application action. A verified credential and a currently active grant are both required.
from dataclasses import dataclass
from uuid import UUID
@dataclass(frozen=True)
class VerifiedAccess:
app_id: UUID
installation_id: UUID
tenant_id: UUID
scopes: frozenset[str]
@dataclass(frozen=True)
class Installation:
id: UUID
app_id: UUID
tenant_id: UUID
active: bool
granted_scopes: frozenset[str]
def effective_tenant(
access: VerifiedAccess, install: Installation, required_scope: str
) -> UUID:
same_installation = (
access.installation_id == install.id
and access.app_id == install.app_id
and access.tenant_id == install.tenant_id
)
if not install.active or not same_installation:
raise PermissionError("installation_inactive_or_mismatched")
effective_scopes = access.scopes & install.granted_scopes
if required_scope not in effective_scopes:
raise PermissionError("insufficient_scope")
return install.tenant_id
Use the resulting tenant value to constrain data access alongside the specific object's authorization rule. For install removal, revoke refresh credentials, invalidate or reject access tokens according to the credential model, close event streams, and stop creating deliveries. A short expiry helps bound exposure, but a self-contained signed token may still pass cryptographic verification after revocation unless the API also checks live installation state or a revocation mechanism. If you cache installation state, make the maximum propagation delay explicit. RFC 7009 OAuth token revocation
Build an event pipeline that can retry safely
Record events with the business change
Write the business mutation and an outbox record in one transaction. The outbox event includes a stable event ID, tenant identity, type, schema version, creation time, and a small payload or a data reference. A dispatcher finds subscriptions that match the tenant and type. Assign each subscription-specific delivery a stable ID and make (subscription_id, event_id) unique in storage. A retried dispatch can then resume an existing delivery instead of silently creating a second delivery record. AWS transactional outbox pattern
Evaluate the installation at subscription creation and again near send time. This prevents a queued event from being sent under a grant that was just removed. For stricter boundaries, use a grant revision in the delivery and check it during claim and redrive. A revoked installation can still have a request already on the wire, so document the revocation race and minimize the amount of data carried per event. Include identifiers and status fields first. Where appropriate, let the partner fetch current details through the API under its current permission.
Choose an event retention and schema policy. Preserve the original payload format for replay, and include the event's version in stored data. An event consumer may remain on an earlier version after an SDK upgrade elsewhere. Broad callbacks that send an entire internal model will create both compatibility and privacy problems. Versioning API responses and asynchronous payloads
Sign the exact HTTP body and validate delivery freshness
Use a maintained webhook signing implementation or adopt a documented public protocol such as Standard Webhooks. The example below demonstrates a small illustrative protocol over a delivery UUID, decimal timestamp, and exact body bytes. Sender and receiver must agree on the framing and version. Use a per-subscription secret and keep the signed input byte-for-byte intact across proxies. A key ID can allow temporary overlap during rotation. Standard Webhooks specification
import hashlib
import hmac
import re
from uuid import UUID
def sign_attempt(secret: bytes, delivery_id: UUID, at: int, body: bytes) -> str:
prefix = f"{delivery_id}.{at}.".encode("ascii")
digest = hmac.new(secret, prefix + body, hashlib.sha256).hexdigest()
return f"v1={digest}"
def verify_attempt(
secret: bytes, raw_id: str, raw_time: str,
body: bytes, signature: str, now: int,
) -> bool:
if not re.fullmatch(r"[0-9]{1,10}", raw_time):
return False
if not re.fullmatch(r"v1=[0-9a-f]{64}", signature):
return False
try:
delivery_id = UUID(raw_id)
except ValueError:
return False
at = int(raw_time)
if raw_id != str(delivery_id) or raw_time != str(at):
return False
if abs(now - at) > 300:
return False
expected = sign_attempt(secret, delivery_id, at, body)
return hmac.compare_digest(expected, signature)
Under this example policy, each retry gets a fresh signed timestamp while keeping the delivery ID. Once the signature is verified, record the delivery ID in a durable inbox with a unique constraint and accept it before acknowledging work. A freshness check only bounds how long a captured request is considered fresh. The inbox prevents the same accepted delivery from causing repeated work within that window or on a legitimate later retry. GitHub's platform docs likewise recommend signature verification over the payload and a timing-safe comparison. GitHub webhook signature guidance
Configure separate connect and response timeouts. Retry transient failures with backoff and jitter, set an outcome for exhausted attempts, and make redrive an authorized action that rechecks grants. Preserve successful acknowledgement if a receiver accepts a delivery before its worker finishes business processing. If a customer endpoint is slow, cap outstanding work for that installation so unrelated tenants continue to receive events. Tenant quotas for shared background workers
Webhook destinations are customer-supplied URLs. Run outbound delivery through a controlled egress service, validate destinations against policy, block private and special-use networks, and avoid following redirects unless each new target can be checked. Treat registration-time and delivery-time checks separately because DNS results and endpoint ownership can change. Limit response sizes and prevent credentials or private headers from being forwarded to destinations.
Offer a WebSocket transport for private partner networks
In a socket model, the integration establishes an outbound TLS WebSocket connection to the platform. It authenticates with a purpose-specific credential or a short-lived connection ticket. The server associates the connection with the installation and streams only eligible events. Slack's Socket Mode illustrates an app-initiated connection and envelope acknowledgements, and Slack currently documents limitations for using this transport in its own public Marketplace. A platform copying the transport pattern should define eligibility for its own marketplace. Slack Socket Mode
Keep the delivery model consistent across HTTP and WebSocket connections. Use an envelope ID for an individual acknowledgement and a durable delivery ID for deduplication. A subscriber should acknowledge after it durably accepts the event. On disconnect, either resume from a bounded cursor or retry unacknowledged deliveries. Never infer success from a successful socket write. Document the replay window, what happens after expiration, and how to fetch missing state if the client was offline too long.
WebSockets add connection auth, load balancing, distributed presence, heartbeats, and backpressure. Set a finite number of unacknowledged deliveries per connection. Stop dispatching when a client is slow, and resume only after receiving acknowledgement or reconnecting under an authorized session. If two connections represent one installation, define whether they share a work queue, act as redundant receivers, or define separate subscriptions. Comparing HTTP and Socket Mode
Test consent changes, failed delivery, and reconnects
A grant is removed while the queue is backlogged
Create deliveries with order-read access, remove the scope, and then resume the dispatcher. Assert that queued and manually redriven jobs do not expose the removed data. Repeat while the app has an active connection and verify it cannot continue receiving the affected event type. Test uninstalling one tenant while another installation for the same app remains active.
A receiver persists an event but loses its acknowledgement
Drop the acknowledgement after writing the event to the receiver's inbox. When the publisher retries, assert the delivery ID remains unchanged and the downstream action is scheduled only once. Run the same test across a WebSocket disconnect and reconnect. If the job itself calls an external service, confirm its own side effect uses an operation key or shared uniqueness constraint.
Event volume grows faster than one partner can process
Combine a slow subscriber with a fast one and inspect per-installation queue age, exhausted retries, connection resets, and API errors. Alert on a growing oldest eligible delivery age. Keep event metadata and request traces available to support without logging secrets or customer payloads. Trace correlation for delivery workers
Frequently asked questions
What is the difference between an OAuth app and a tenant installation?
The app registration identifies a developer's integration and contains its registered configuration and reviewed scope limits. An installation records which customer tenant authorized that app and exactly which scopes were approved. The same app may be installed by multiple tenants with different grants and independent revocation.
Should a new app marketplace start with webhooks or WebSockets?
Start with signed HTTPS webhooks when partners can run reachable endpoints and do not need persistent bidirectional communication. Add an outbound WebSocket transport for partners that cannot expose an inbound endpoint or need an active session. Keep identity, authorization, replay, and delivery states consistent across both transports.
Does a valid webhook signature make the event safe to process twice?
The signature authenticates the exact bytes under the signing key and can bind the delivery ID and timestamp. Deduplication is a separate concern. Store the stable delivery ID in a durable inbox and guard downstream effects with an operation-specific uniqueness or idempotency rule.
How do I remove marketplace access when a customer uninstalls an app?
Mark the installation inactive, revoke or expire its credentials under your token model, stop new deliveries, and close active connections. Check current grants before dispatch and redrive. Account for propagation delays and previously sent events, which cannot be recalled after crossing the network.
Further reading
Opening a SaaS platform to third-party integrations? Talk to Dumb Potato about consent, event delivery, and marketplace operations.
