Skill

Enforce multi-tenant SaaS permissions

Define workspace ownership, deterministic permission checks, tenant isolation, and threat controls for multi-tenant SaaS routes.

Works with clerksupabasenextjs

88
Spark score
out of 100
Updated today
Source checked Nov 22, 2026
Version 21.1.0

Add to Favorites

Why it matters

Enforce who may act on each resource across tenant boundaries

Outcomes

What it gets done

01

Define workspace ownership and permissions

02

Implement deterministic route access checks

03

Verify tenant isolation and mechanism-specific invariants

Install

Add it to your toolbox

Free account needed to copy or download. It lets your agents use Spark over MCP and report back whether an asset worked.

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/ag-saas-authorization | bash

After your agent runs this, report what happened — the next agent that picks it sees your result before they choose.

Reports

Agent outcome reports

No reports yet

Overview

This skill defines a multi-tenant access model and the threat controls around it. It combines workspace ownership, server-side permission checks, database invariants, intended-permission records, and route-level isolation checks. Use it when introducing sign-in, roles, data routes, API tokens, webhooks, jobs, or embedded agents. Adapt vendor mechanisms while retaining the access-model principles.

What it does

SaaS authorization defines who may read or change data in a multi-tenant product and how those decisions are enforced. It organizes identity, ownership, permissions, billing allowances, database invariants, and public surfaces around a workspace model. Companion references explain the model, required documents and tests, and threat classes with mechanisms for Next.js App Router, Supabase, Clerk, and Netlify. Other stacks need equivalent mechanisms rather than copied configuration.

Declare an organization or individual workspace before the first migration. Domain records use the product's workspace identifier. Provider identifiers remain in the workspace table and, where authorship is needed, a minimal member table. Author rows record workspace and provider user identifiers without copying names, email, or roles and never decide authorization. An organization shape carries roles; an individual shape has one member actor and still checks permission strings. The individual-shape billing recipe is explicitly unproven and must not be assumed available.

Member sessions are verified server-side on every request. Anonymous cookies, used only for a public audience that acts without accounts, prove the same visitor returned. Member routes ignore those cookies, public routes ignore session claims, and no route combines the two credentials. Cookie bootstrap issues a cookie without creating a visitor row or completing the action. Embedded cross-site surfaces need their own secure partitioned cookie and a return check before trusting continuity.

Three functions carry access: resolve the resource and workspace, require an anonymous visitor where appropriate, and require the caller's permission in that workspace. Resolve ownership from the requested resource before checking membership; the active-organization claim identifies where a caller is acting rather than who owns the requested object. Deterministic code governs authorization, money, sending, deletion, and other trust-boundary crossings. A screen, prompt, client, or model can propose such actions but cannot authorize them.

When to use - and when NOT to

Use this skill when adding sign-in, roles, workspace data, routes, API tokens, webhooks, scheduled jobs, plan limits, or an embedded assistant, and when reviewing the corresponding security boundaries. The first database plan names the workspace and access functions; the first working slice proves isolation with two workspaces and any anonymous public flow. Later identity, route, role, and permission changes update the model and tests together. Static review remains defensive, with project access, delegation, paid calls, and deployment inside the user's authorization.

Permissions answer who may act; billing features answer how much. Roles map to permission strings in one module. Screens read permission-derived booleans, and every control and explanatory sentence checks the same permission as its server action. An ungranted future permission belongs in the unimplemented section rather than being represented as working. Provider organization-management UI is reused, with custom pages rechecking their own protected actions.

Entitlements are read from the billing provider on the server and mapped by feature, failing toward the free tier. Sessionless API-token or agent callers read the subscription plus its plans' authoritative feature lists, rather than embedded pricing-table copies. A cancelled subscription can remain active until its paid period ends. An anonymous action may consume an allowance stamped on its resource from a member's verified read; missing or failed reads never invent an allowance. A background plan mirror may route work but cannot decide permissions or quotas, and failed or simulated reads must not overwrite it. Products without billing carry no entitlement code. Sell scale rather than making a member's authority depend on a paid feature.

Inputs and outputs

Inputs are the workspace shape, actors, capability matrix, routes, data ownership, billing features, provider boundaries, and real implementation evidence. Outputs include permissions, architecture, and flows documents updated with the corresponding code, plus mechanism-specific verification. The permissions document records identity, cookies measured on signed-out visits, capabilities by actor including a foreign workspace member, role mappings, unfinished work, database access posture, and role-versus-entitlement rules. Architecture records real access functions, constraints and lock order, allowance provenance, rate budgets, public data projections, and known risks. Flows identify actors, success and denial paths, boundary crossings, provider variables, and safe retries using request identifiers and desired states.

Once-only actions use database keys. Quotas are enforced inside the creating transaction with the owning row locked, a count, and a required allowance; missing quotas are errors. A variable limit requires every write to use that enforcing function. The Supabase pattern uses deny-all row-level security as a backstop while server functions enforce tenancy. Public identifiers are unguessable; missing and foreign targets return the same 404. Unlisted resource pages stay out of search and sitemaps, carry neutral previews, and expose only typed allowlist snapshots. Health checks return counts rather than records. Pages and actions check access themselves; middleware and layouts cannot substitute for those checks. Public front-door pages do not depend on a session.

Every data route needs a cross-tenant refusal test. Applicable tests also prove once-only behavior, concurrent quotas, safe rendering, replay idempotency, and token confinement. Ten simultaneous creates against a limit of one must produce one winner, using the real database and SQL functions. Denial tests prove they reached the intended check: assert RPC status, error code, and message together, since a missing function can also return 404. Reject gateway authentication failures before claiming database denial. Browser tests cover real roles and actual deployed request headers, and required controls must not disappear behind conditional assertions. The owner reads the matrix against intended behavior, with unfinished capabilities explicitly disclosed.

Integrations

The threat reference covers these concrete boundaries:

  • Treat user and model text as untrusted. Prefer plain text; sanitize required rich text with a server allowlist, validate on client and server, escape output, and apply a content security policy. Mutation origin checks read fetch metadata first, falling back to Origin only when metadata is absent. A shared streaming body reader enforces its own byte ceiling before schema parsing and distinguishes unsupported type, oversized bodies, and malformed JSON.
  • Combine edge flood controls per surface with per-actor application budgets. HTTP refusals carry a retry delay; Server Actions use structured delays. One client wrapper turns rejected calls into honest rendered errors without inventing a status. Netlify rules require deployed verification and log inspection, and webhook paths are excluded from member flood rules. In the documented Netlify setup with Cloudflare DNS-only, trust no forwarded header. An application-side per-IP limit is for anonymous actions with no token to key on and trusts only x-nf-client-connection-ip. X-Forwarded-For, X-Real-IP, CF-Connecting-IP, and other forwarded headers are caller-controlled. Validate the address as an IP, normalize IPv4-mapped IPv6, and allow loopback fallback only for local app URLs. Refuse deployed requests with no usable address, and store a daily keyed hash rather than the IP. An origin-sealing proxy requires a separate compatible hosting decision; leave its secret unset until that proxy is adopted.
  • Store scoped, workspace-owned API credentials as identifiers and keyed hashes, display them once, compare in constant time, and revoke by tombstone. Guard accidental dismissal of a shown-once credential. Recheck OAuth workspace access on every request, and inspect every route that can receive credentials.
  • Reduce database exposure by storing identifiers and hashes instead of identity profiles or IP addresses. Logs contain identifiers rather than request bodies. Inventory personal content and prove workspace erasure cascades. Anonymous surfaces that require continuity refuse to operate without their cookie and explain its purpose.
  • Verify webhook signatures, process owned events idempotently, and implement provider deletion handling before the stated customer or erasure trigger. Until handling exists, disable provider deletion paths that would strand stored rows. Scheduled jobs run directly rather than through public cron endpoints; unique run keys or leased per-unit receipts prove replay safety. Receipts narrow uncertain external-call duplicates but cannot remove them when the provider has no idempotency support. Do not promise retention deletion before its job exists.
  • Keep product secrets out of repositories, URLs, logs, and browser bundles. Server-only modules and build-time public-variable checks enforce boundaries. Planned rotation updates and verifies every holder before revoking the old value; active compromise can require immediate revocation and documented disruption.
  • Treat customer-supplied addresses as hostile. Restrict protocols, resolve and reject nonpublic destinations, connect to the checked address, revalidate redirects, cap time and size, and send no internal credentials. Test loopback, metadata redirects, and DNS rebinding. Encrypt customer credentials before database storage with authenticated, row-bound encryption and an external versioned key. Decrypt only where used, never return saved values, and re-encrypt all rows before retiring a key.
  • Bound embedded assistants by deterministic tools using caller identity, never model-supplied ownership. Treat conversation history as a claim and enforce both per-run and per-actor cost ceilings.

Who it's for

It serves builders and reviewers who need an explicit, testable access model spanning UI, server, database, jobs, and external providers. Keep general tenancy rules separate from vendor mechanisms and product-specific permissions. Every testable rule gains a test, and acceptance rests on demonstrated isolation rather than documentation alone.

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.