Inferensys

Prompt

Multi-Tenancy Isolation Test Case Prompt from SaaS Specs

A practical prompt playbook for generating tenant isolation verification tests from SaaS platform specifications. Produces test cases for cross-tenant data access attempts, tenant-specific configuration leakage, and resource quota enforcement with eval checks for tenant context propagation and shared infrastructure isolation gaps.
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the precise conditions, required inputs, and boundaries for using the multi-tenancy isolation test case generation prompt.

This prompt is designed for SaaS platform testers and QA engineers who need to verify that tenant isolation boundaries hold under real-world conditions. Use it when you have a multi-tenant architecture specification, access control matrix, or tenant data model and need to generate structured test cases that validate cross-tenant data access prevention, configuration leakage between tenants, and resource quota enforcement per tenant. The ideal user is a senior QA engineer or SDET who understands the platform's tenancy model and can provide detailed specifications, not just a high-level architectural diagram.

The prompt requires concrete input documents: a tenant data model showing how tenant IDs propagate through the stack, an access control matrix defining per-role permissions across tenant boundaries, and isolation requirements specifying what must never leak between tenants. It produces test cases with explicit tenant context setup (e.g., 'Authenticate as Tenant A, create resource X, then attempt access as Tenant B'), attack vectors (e.g., IDOR attempts, shared cache poisoning, metadata enumeration), expected isolation behavior, and traceability back to specific isolation requirements. Each generated test case includes a unique test ID, preconditions, steps, expected results, and a risk classification.

Do not use this prompt for single-tenant application testing, general authentication testing, or performance load testing. It is specifically scoped to multi-tenancy isolation verification. If your specifications are incomplete or you lack a documented tenant isolation model, run a specification review first—this prompt cannot infer isolation requirements from code alone. For regulated environments, always route generated test cases through a security architect review before execution, and ensure test data is synthetic rather than copied from production tenants.

PRACTICAL GUARDRAILS

Use Case Fit

Where the multi-tenancy isolation test prompt delivers value and where you should reach for a different tool.

01

Good Fit: Structured Tenant Specifications

Use when: you have documented tenant isolation requirements, data partitioning rules, or access control matrices. The prompt excels at translating explicit isolation boundaries into reproducible test cases. Guardrail: feed the prompt structured specs, not vague descriptions—output quality depends on input precision.

02

Bad Fit: Undocumented Legacy Systems

Avoid when: tenant isolation behavior is undocumented, emergent, or reverse-engineered from code. The prompt cannot discover isolation gaps you haven't specified. Guardrail: invest in architecture documentation or runtime analysis before generating test cases; otherwise, tests will miss real isolation boundaries.

03

Required Inputs: Tenant Context Model

What you need: tenant identifier propagation rules, shared vs. dedicated infrastructure inventory, cross-tenant access prohibition rules, and resource quota definitions per tenant. Guardrail: missing any of these inputs produces incomplete test coverage—validate input completeness with a checklist before prompting.

04

Operational Risk: False Confidence in Coverage

Risk: generated test cases may pass while real isolation gaps exist in unspecified infrastructure layers (caches, message queues, connection pools). Guardrail: treat prompt output as a starting point, not exhaustive coverage—supplement with infrastructure-level penetration testing and shared-resource auditing.

05

Integration Point: Test Management Systems

Use when: you need structured test cases importable into TestRail, Xray, Zephyr, or similar tools. The prompt produces schema-ready output with preconditions, steps, and expected results. Guardrail: verify output schema compatibility with your target test management system before bulk generation—field mapping may require post-processing.

06

Boundary: Not a Substitute for Threat Modeling

Avoid when: you need novel attack path discovery or threat modeling. The prompt generates tests from known isolation rules, not unknown vulnerabilities. Guardrail: pair this prompt with dedicated threat modeling sessions and red-team exercises for tenant escape vectors the spec doesn't anticipate.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A ready-to-use prompt for generating multi-tenancy isolation test cases from SaaS architecture and specification documents.

This prompt template converts your SaaS platform's tenant isolation specifications, architecture diagrams, and access control matrices into a structured suite of negative test cases. It is designed to produce tests that verify cross-tenant data access prevention, tenant-specific configuration leakage, resource quota enforcement, and tenant context propagation across shared infrastructure layers. Replace every square-bracket placeholder with your actual specifications before running the prompt. The output is a traceable test suite with preconditions, attack steps, expected isolation behavior, and evidence requirements.

text
You are a senior SaaS security test architect. Your task is to generate a comprehensive suite of multi-tenancy isolation test cases from the provided specifications.

## INPUTS
- Tenant isolation architecture specification: [TENANT_ISOLATION_SPEC]
- Access control matrix and role definitions: [ACCESS_CONTROL_MATRIX]
- Shared infrastructure component list: [SHARED_COMPONENTS]
- Tenant data model and partitioning strategy: [DATA_PARTITIONING_STRATEGY]
- Resource quota and rate limit policies: [RESOURCE_QUOTA_POLICIES]
- Tenant context propagation mechanism: [CONTEXT_PROPAGATION_MECHANISM]
- Known isolation boundaries and trust zones: [ISOLATION_BOUNDARIES]

## OUTPUT SCHEMA
Return a JSON array of test case objects with this exact structure:
{
  "testCases": [
    {
      "testId": "string (e.g., TI-001)",
      "testName": "string",
      "isolationCategory": "cross_tenant_data_access | config_leakage | quota_enforcement | context_spoofing | shared_infrastructure_isolation",
      "riskLevel": "critical | high | medium | low",
      "tenantSetup": {
        "tenantA": "string (description of source tenant state)",
        "tenantB": "string (description of target tenant state)",
        "sharedResource": "string (if applicable)"
      },
      "preconditions": ["string"],
      "attackVector": "string (detailed steps the attacker tenant attempts)",
      "expectedIsolationBehavior": "string (what the system must do to prevent the breach)",
      "expectedEvidence": ["string (logs, response codes, audit entries that prove isolation held)"],
      "bypassScenario": "string (what failure looks like if isolation is broken)",
      "affectedComponents": ["string"],
      "testType": "automated | manual | semi_automated",
      "cleanupSteps": ["string"]
    }
  ]
}

## CONSTRAINTS
- Generate at least one test case for each isolationCategory.
- For cross_tenant_data_access, include tests for direct API calls, SQL injection attempts, and object reference manipulation.
- For config_leakage, include tests for feature flags, rate limits, and custom domain settings.
- For quota_enforcement, include tests where one tenant's resource exhaustion must not affect another tenant.
- For context_spoofing, include tests where Tenant A attempts to pass Tenant B's tenant ID in headers, tokens, or request parameters.
- For shared_infrastructure_isolation, include tests for connection pool exhaustion, cache key collision, and message queue cross-delivery.
- Every test case must specify what logs or audit trails prove isolation held.
- Flag any test that requires destructive actions or production data access as manual with human review required.

## EXAMPLES
Input: A SaaS platform using row-level security with a tenant_id column in a shared PostgreSQL database, JWT-based tenant context propagation, and per-tenant rate limiting via Redis.

Example output test case:
{
  "testId": "TI-001",
  "testName": "Cross-Tenant Data Access via Direct Tenant ID Manipulation in API Request",
  "isolationCategory": "cross_tenant_data_access",
  "riskLevel": "critical",
  "tenantSetup": {
    "tenantA": "Authenticated user in Tenant A with valid JWT containing tenant_id=A",
    "tenantB": "Tenant B exists with its own isolated data rows",
    "sharedResource": "PostgreSQL database with row-level security policy on tenant_id column"
  },
  "preconditions": [
    "Tenant A user is authenticated and holds a valid session",
    "Tenant B has data rows with tenant_id=B",
    "Row-level security policy is active on the target table"
  ],
  "attackVector": "Tenant A user sends a GET request to /api/records with a modified JWT claim tenant_id=B or passes X-Tenant-ID: B header",
  "expectedIsolationBehavior": "The API gateway or middleware must reject the tenant context override. The database query must apply row-level security using the verified tenant context from the authenticated session, not the request header. Tenant A must receive only tenant_id=A rows or a 403 Forbidden response.",
  "expectedEvidence": [
    "Application log showing tenant context mismatch detected",
    "403 Forbidden response in API access logs",
    "Database audit log confirming query filtered by correct tenant_id=A",
    "No Tenant B data rows in the response body"
  ],
  "bypassScenario": "If the application trusts the X-Tenant-ID header without re-verifying against the authenticated session, Tenant A receives Tenant B's data rows in the response.",
  "affectedComponents": ["API Gateway", "Authentication Middleware", "PostgreSQL RLS Policy"],
  "testType": "automated",
  "cleanupSteps": ["Revoke any modified tokens", "Reset rate limit counters for Tenant A"]
}

## RISK_LEVEL
High. Multi-tenancy isolation failures can cause data breaches across customer boundaries. All generated test cases must be reviewed by a security architect before execution in any environment that contains production tenant data. Tests marked as manual require human approval before each run.

To adapt this prompt, replace the [TENANT_ISOLATION_SPEC] placeholder with your actual architecture document describing how tenants are separated—whether through database-per-tenant, schema-per-tenant, or row-level security. The [ACCESS_CONTROL_MATRIX] should contain your role-to-permission mappings and tenant-scoping rules. If your platform uses multiple isolation strategies for different components, list each in [SHARED_COMPONENTS] and describe the partitioning approach in [DATA_PARTITIONING_STRATEGY]. The output schema is intentionally strict: every test case must include the expectedEvidence field so that your test automation or manual QA team can confirm isolation held, not just that the test passed. Before running this prompt in a CI pipeline, validate the JSON output against the schema and reject any test case missing a bypassScenario—that field is your canary for whether the model understood the failure mode.

After generating the test suite, run a coverage check: map each isolationCategory to your trust boundaries and confirm no boundary is untested. For high-risk SaaS platforms handling PII or payment data, require a security architect to review all critical and high risk test cases before they enter your test management system. Store the generated test cases with a version reference to the input specifications so that when your isolation architecture changes, you can regenerate and diff the test suite.

IMPLEMENTATION TABLE

Prompt Variables

Replace each placeholder with concrete specifications before generating test cases. Vague inputs produce unreliable isolation tests that miss cross-tenant leakage paths.

PlaceholderPurposeExampleValidation Notes

[TENANT_MODEL]

Defines how tenants are identified and isolated in the system architecture

Pooled schema with tenant_id column on all tables; tenant context propagated via JWT claim 'tid'

Must specify isolation strategy: database-per-tenant, schema-per-tenant, pooled, or hybrid. Missing strategy causes invalid test design

[RESOURCE_TYPES]

Lists all shared resources that must be isolated between tenants

Customer records, billing invoices, uploaded documents, ML model predictions, audit logs, feature flags

Each resource type must map to a concrete API endpoint or data store. Vague resource names produce untestable isolation checks

[ACCESS_PATTERNS]

Describes how tenants interact with resources including API routes and permission models

GET /api/v1/customers/{id}, POST /api/v1/invoices, GET /api/v1/reports?tenant_scope=current

Include HTTP methods, path parameters, query filters, and auth mechanism. Missing access patterns leave cross-tenant endpoints untested

[TENANT_CONTEXT_PROPAGATION]

Specifies how tenant identity flows through the request lifecycle

JWT claim 'tenant_id' extracted by API gateway, injected into request context, used by data access layer for row-level filtering

Trace propagation from ingress to data layer. Gaps in propagation spec indicate where isolation tests must inject mismatched tenant context

[QUOTA_AND_LIMIT_SPEC]

Defines per-tenant resource quotas, rate limits, and enforcement points

1000 API calls/min per tenant, 10GB storage per tenant, 5 concurrent long-running jobs per tenant

Include limit values, enforcement layer, and expected error response. Missing quotas mean quota enforcement tests cannot be generated

[SHARED_INFRASTRUCTURE]

Identifies infrastructure components shared across tenants that risk isolation breaches

Shared Redis cache with tenant-prefixed keys, shared S3 bucket with tenant-scoped prefixes, shared CDN, shared message queue with tenant-specific topics

List each shared component with its isolation mechanism. Unlisted shared infrastructure creates blind spots in test coverage

[ERROR_CONTRACT]

Defines expected error responses when isolation violations are attempted

HTTP 403 with error code 'CROSS_TENANT_ACCESS_DENIED', no tenant data leaked in error body, audit event logged with tenant pair

Specify status codes, error body schema, and side effects. Missing error contract means tests cannot validate safe failure behavior

[AUDIT_REQUIREMENTS]

Describes what must be logged when cross-tenant access is attempted or prevented

Log tenant_id of requester, target tenant_id, resource type, timestamp, action attempted, and whether access was blocked

Define required audit fields and log destination. Missing audit spec prevents validation of observability requirements

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the multi-tenancy isolation test prompt into a test generation workflow and what surrounds it in production.

This prompt is not a standalone QA tool. It is a generation engine that must be embedded in a pipeline with validation, human review, and traceability controls. The prompt accepts a SaaS specification document and produces structured test cases, but the output is a candidate artifact—not a verified test suite. The harness must treat every generated test case as a draft that requires schema validation, coverage gap analysis, and security reviewer sign-off before it lands in a test management system.

Wire the prompt into a workflow that first extracts the relevant specification sections (tenant model, data isolation rules, configuration scoping, quota definitions) and passes them as [SPECIFICATION_TEXT]. Set [TENANT_MODEL] to the isolation architecture in use (e.g., shared-database, database-per-tenant, hybrid). The [OUTPUT_SCHEMA] should enforce a strict JSON array of test case objects, each containing test_id, isolation_vector, preconditions, steps, expected_result, tenant_context, and risk_level. Validate every output against this schema programmatically. Reject any test case missing tenant_context—the field that describes which tenant identity is active during the test—because without it, isolation intent is unverifiable.

After schema validation, run a coverage check: compare generated test vectors against a known list of isolation dimensions (cross-tenant data read, cross-tenant data write, configuration leakage, quota bypass, metadata exposure, shared cache poisoning, log leakage). Flag any missing dimensions and re-prompt with the gap list appended to [CONSTRAINTS]. For high-risk vectors like cross-tenant write attempts, route the test case to a human security reviewer before automation. Log every generation run with the prompt version, input spec hash, output test count, validation failures, and reviewer decisions. This audit trail is essential when a tenant isolation bug escapes to production and the investigation asks whether the test suite covered that vector.

Model choice matters. Use a model with strong instruction-following and structured output reliability for the initial generation pass. For the coverage gap analysis pass, a separate classifier prompt or a smaller, faster model can check whether each isolation dimension is represented in the output. Do not rely on the generation model to self-critique its own coverage—use a second pass with a focused eval prompt. When retrying after validation failures, include the specific schema violation or missing dimension in the retry context rather than re-running the original prompt blindly. This targeted repair loop reduces token waste and prevents the model from drifting away from the specification source.

IMPLEMENTATION TABLE

Expected Output Contract

Validate each generated test case against this contract before accepting results. Reject or request repair for any output that does not conform to these field requirements and validation rules.

Field or ElementType or FormatRequiredValidation Rule

test_case_id

string (e.g., MT-ISO-001)

Must match pattern ^MT-ISO-\d{3}$. Must be unique within the output array.

title

string

Must be non-empty and contain a verb phrase describing the isolation scenario (e.g., 'Attempt cross-tenant data read'). Max 120 characters.

isolation_category

enum: data_access | config_leakage | quota_enforcement | identity_crossing | infrastructure_bleed

Must be exactly one of the allowed enum values. Reject unknown categories.

tenant_context

object with keys: source_tenant_id (string), target_tenant_id (string)

Both tenant IDs must be non-empty strings. source_tenant_id must differ from target_tenant_id. Validate tenant ID format against [TENANT_ID_PATTERN].

preconditions

array of strings

Array must contain at least one precondition. Each string must describe a verifiable state before test execution (e.g., 'Tenant A has resource X with value Y').

test_steps

array of objects with keys: step_number (integer), action (string), expected_behavior (string)

Array must contain at least one step. step_number must be sequential starting from 1. action must be non-empty. expected_behavior must describe the isolation expectation for that step.

expected_result

string

Must explicitly state whether isolation holds or fails (e.g., 'Request is denied with 403 Forbidden' or 'Only Tenant A data is returned'). Must reference the isolation boundary being verified.

assertions

array of objects with keys: assertion_type (enum: http_status | response_body | log_entry | metric | config_value), target (string), expected_value (string)

Array must contain at least one assertion. assertion_type must be a valid enum value. target must identify the check target (e.g., 'response.status_code'). expected_value must be concrete and verifiable.

cleanup_steps

array of strings

If present, each string must describe a reversible action. If null or empty, test is assumed to leave no side effects requiring cleanup.

risk_level

enum: critical | high | medium | low

Must be exactly one of the allowed enum values. critical reserved for tests that, if failing, indicate a confirmed cross-tenant data exposure.

traceability_tags

array of strings

Array must contain at least one tag linking to a requirement or spec section (e.g., 'REQ-SEC-012', 'SPEC-ISO-3.2'). Validate tags against [REQUIREMENT_TAG_LIST] if provided.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when generating multi-tenancy isolation test cases from SaaS specs, and how to guard against it.

01

Tenant Context Bleed in Test Steps

What to watch: The model generates test steps that accidentally use Tenant A's credentials or IDs while asserting Tenant B's isolation, creating a logically impossible test. Guardrail: Require the prompt to output explicit tenant-context variables (e.g., [TENANT_A_TOKEN], [TENANT_B_ID]) in each step and validate that no step mixes contexts.

02

Missing Negative Assertions

What to watch: The model generates positive-path tests that verify Tenant A can access its own data but omits the critical negative assertion that Tenant A cannot access Tenant B's data. Guardrail: Add a hard constraint in the prompt requiring every isolation test case to include at least one explicit 403/404 assertion for a cross-tenant access attempt.

03

Shared Infrastructure Blind Spots

What to watch: The model focuses only on API-level isolation and ignores shared infrastructure risks like cache poisoning, connection pool reuse, or message queue partition errors. Guardrail: Include a checklist in the prompt that forces generation of at least one test case per shared resource type (cache, queue, file storage) mentioned in the spec.

04

Quota Enforcement Scope Errors

What to watch: The model generates a test that verifies Tenant A's resource quota is enforced but fails to verify that Tenant A's consumption does not impact Tenant B's available quota. Guardrail: Require each quota test case to include a cross-tenant assertion confirming that one tenant's quota exhaustion does not degrade another tenant's resource availability.

05

Configuration Leakage Through Defaults

What to watch: The model overlooks tenant-specific configuration isolation, such as custom email templates or feature flags leaking between tenants via global default fallback logic. Guardrail: Add a prompt instruction to generate test cases for every tenant-configurable setting listed in the spec, explicitly checking that Tenant B receives its own configuration, not Tenant A's.

06

Unverifiable Test Preconditions

What to watch: The model generates test preconditions like "Ensure Tenant A and Tenant B are fully isolated" without specifying how to verify that state, making the test impossible to execute reliably. Guardrail: Require each test case to include a concrete precondition verification step (e.g.,

IMPLEMENTATION TABLE

Evaluation Rubric

Score generated multi-tenancy isolation test cases against these criteria before accepting them into your test suite. Each dimension is scored 0-3. A score of 0 means the test case is rejected; 1-2 means it requires revision; 3 means it is production-ready.

CriterionPass StandardFailure SignalTest Method

Tenant Context Propagation

Test case explicitly sets a tenant context (e.g., header, token claim, or session attribute) before each operation and verifies it is propagated to all downstream calls in the test steps

Test steps reference a tenant ID but never show how the tenant context is established or passed to the system under test

Manual review: confirm every test step that requires tenant isolation includes a precondition step that sets the tenant context

Cross-Tenant Data Access Prevention

Test case includes at least one step where Tenant A attempts to read, write, or list resources belonging to Tenant B, with an expected 403 or 404 response and no data leakage in the response body

Test case only validates same-tenant access or asserts a 200 OK without a negative cross-tenant attempt

Schema check: verify the expected HTTP status code is 403 or 404; manual review: confirm the response body contains no data from the other tenant

Resource Quota Enforcement

Test case attempts to exceed a documented per-tenant resource limit (e.g., max users, max storage) and asserts the operation is rejected with a clear quota-exceeded error

Test case assumes unlimited resources or does not reference any quota limit from the SaaS spec

Schema check: verify the expected error code or message matches the spec; manual review: confirm the quota limit value is traceable to a spec requirement

Tenant-Specific Configuration Isolation

Test case verifies that a configuration change made in Tenant A's scope (e.g., feature flag, branding, notification setting) does not affect Tenant B's behavior or visible state

Test case only checks configuration within a single tenant or asserts global configuration changes without cross-tenant verification

Manual review: confirm the test includes a read-back step from Tenant B after Tenant A's configuration change and asserts no unintended change

Shared Infrastructure Isolation

Test case identifies a shared resource (e.g., cache key, job queue, file storage path) and verifies that tenant-scoped keys or namespaces prevent cross-tenant interference

Test case ignores shared infrastructure or assumes the application layer handles isolation without testing the data layer

Manual review: confirm the test case names a specific shared component and includes a step that attempts cross-tenant access at that layer

Error Message Non-Disclosure

Test case asserts that error responses from cross-tenant access attempts do not reveal tenant IDs, resource existence, or internal system details to the unauthorized caller

Test case only checks the HTTP status code and ignores the response body content for information leakage

Schema check: verify the test case includes an assertion on the response body shape; manual review: confirm the assertion checks that tenant identifiers and resource metadata are absent from error payloads

Test Case Reproducibility

Test case includes all required preconditions (seed data, tenant setup, auth tokens) as explicit steps and can be executed in any order without depending on side effects from other test cases

Test case assumes pre-existing state, uses hardcoded IDs without setup steps, or fails when run independently

Manual review: confirm the test case has a self-contained setup block; execution check: run the test case in isolation and verify it passes without relying on test suite ordering

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with lighter validation. Focus on generating a broad set of isolation scenarios without strict schema enforcement. Accept free-text test case descriptions and manually review for tenant context propagation coverage.

  • Remove strict [OUTPUT_SCHEMA] constraints; request structured markdown instead of JSON.
  • Simplify [CONSTRAINTS] to a single sentence: "Generate test cases covering cross-tenant data access, configuration leakage, and resource quota enforcement."
  • Skip eval assertions; rely on manual QA review of generated test cases.

Watch for

  • Missing schema checks leading to inconsistent test case formats across runs
  • Overly broad instructions producing generic security tests instead of tenant-specific isolation scenarios
  • No traceability between generated tests and the source SaaS spec sections
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.