Inferensys

Prompt

Authentication and Authorization Test Prompt

A practical prompt playbook for using Authentication and Authorization Test Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the ideal scenario, required inputs, and explicit boundaries for using the Authentication and Authorization Test Prompt.

This prompt is designed for security engineers and QA leads who need to validate access control implementations before they ship. It takes an authorization model definition, role hierarchy, and endpoint inventory as input, then produces a structured test matrix covering role-based access, token validation, session management, and privilege escalation attempts. The primary job-to-be-done is systematic coverage: ensuring every role, resource, and action combination is evaluated against the intended permission model, not just the happy path.

Use this prompt when you have a defined permission model and need to generate a comprehensive test plan. Required context includes a formal role hierarchy (e.g., admin, editor, viewer), a resource-to-action mapping (e.g., GET /api/documents, DELETE /api/users), and any token or session lifecycle rules. The prompt works best when fed structured definitions—YAML or JSON representations of your authorization model—rather than prose descriptions. Do not use this prompt for runtime penetration testing or live system exploitation. It generates test plans, not attack payloads. It will not execute requests, analyze live traffic, or validate actual token signatures.

Before running this prompt, ensure you have completed the authorization design and documented it in a machine-readable format. The output is a test matrix, not a replacement for dynamic analysis tools like OWASP ZAP or Burp Suite. After generating the matrix, you should review it for completeness against your threat model, then wire the test cases into your CI pipeline or manual QA runbook. Avoid using this prompt for systems where the permission model is implicit or undocumented—the output quality degrades sharply without structured input.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Authentication and Authorization Test Prompt fits your current security review workflow.

01

Good Fit: Structured Access Control Review

Use when: you have defined roles, permissions, and access policies in code or configuration. The prompt excels at generating test matrices from role-based access control (RBAC) definitions, policy files, or middleware configurations. Guardrail: Provide explicit role-to-permission mappings as [INPUT] to avoid the model guessing authorization logic.

02

Bad Fit: Undocumented or Implicit Policies

Avoid when: authorization logic exists only in tribal knowledge or scattered across undocumented legacy code. The prompt cannot reverse-engineer intent from incomplete signals. Risk: generated tests will miss critical access paths or assert incorrect expected behavior. Guardrail: require a human-authored policy specification before running this prompt.

03

Required Inputs

Must provide: role definitions, permission sets, resource types, and action mappings. Token validation logic, session management rules, and privilege escalation boundaries should be included in [CONTEXT]. Guardrail: if any of these inputs are missing, scope the prompt to only the available surface and flag gaps explicitly in the output.

04

Operational Risk: False Sense of Coverage

What to watch: a comprehensive-looking test matrix can create overconfidence. The prompt generates tests from what you describe, not from what actually exists in production. Guardrail: always cross-reference generated test cases against live policy enforcement points and run them in a staging environment before trusting coverage claims.

05

Operational Risk: Privilege Escalation Blind Spots

What to watch: the prompt may miss indirect privilege escalation paths such as parameter tampering, IDOR vulnerabilities, or chained permission bugs. These require runtime analysis beyond static policy review. Guardrail: supplement generated tests with dynamic application security testing (DAST) and manual penetration testing for escalation vectors.

06

Variant: Token and Session Focus

Use when: testing JWT validation, OAuth flows, session fixation, or token refresh logic. Narrow the prompt scope by specifying [CONSTRAINTS] that focus on token lifecycle rather than full RBAC matrices. Guardrail: include expected token claims, expiry behavior, and refresh policies in [CONTEXT] to prevent the model from hallucinating standard but incorrect token behavior.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating comprehensive authentication and authorization test matrices from access control implementations.

This prompt template is designed to be pasted directly into your AI coding agent or test generation pipeline. It instructs the model to analyze authentication and authorization logic—whether expressed in code, configuration, or specification—and produce a structured test matrix covering role-based access, token validation, session management, and privilege escalation attempts. The placeholders allow you to adapt the prompt to your specific codebase, identity provider, and risk profile without rewriting the core instruction.

text
You are a security test engineer reviewing an authentication and authorization implementation. Your task is to generate a comprehensive test matrix that validates access control correctness, session integrity, and resistance to common privilege escalation vectors.

## INPUT
Source code, configuration, or specification to analyze:

[INPUT]

code

## CONTEXT
- Identity provider: [IDP_TYPE] (e.g., Auth0, Okta, Cognito, custom JWT issuer)
- Token format: [TOKEN_FORMAT] (e.g., JWT with RS256, opaque token, session cookie)
- Role definitions and permission mappings: [ROLE_DEFINITIONS]
- Session management approach: [SESSION_MANAGEMENT] (e.g., stateless JWT, server-side sessions, refresh token rotation)
- Multi-tenancy model (if applicable): [TENANCY_MODEL]
- Relevant compliance requirements: [COMPLIANCE_REQUIREMENTS] (e.g., SOC2, HIPAA, PCI-DSS)

## OUTPUT_SCHEMA
Return a JSON object with the following structure:
{
  "test_matrix": [
    {
      "test_id": "AUTH-001",
      "category": "authentication | authorization | session | token | privilege_escalation",
      "scenario": "Human-readable description of what is being tested",
      "preconditions": ["List of required state before test execution"],
      "action": "The specific request, call, or operation to perform",
      "expected_result": "The expected outcome including HTTP status, error codes, or behavior",
      "risk_level": "critical | high | medium | low",
      "test_type": "unit | integration | manual | automated",
      "references": ["Links to relevant code, config, or spec sections"]
    }
  ],
  "coverage_summary": {
    "total_tests": 0,
    "by_category": {},
    "by_risk_level": {},
    "uncovered_scenarios": ["List of scenarios not covered by current implementation"]
  },
  "privilege_escalation_vectors": [
    {
      "vector": "Description of potential escalation path",
      "severity": "critical | high | medium | low",
      "current_mitigation": "How the implementation currently handles this",
      "recommended_test": "Test ID that validates this vector"
    }
  ]
}

## CONSTRAINTS
- Generate tests for every role and permission combination defined in [ROLE_DEFINITIONS]
- Include negative test cases: expired tokens, malformed tokens, missing scopes, wrong audience, tampered claims
- Cover token refresh, revocation, and rotation scenarios
- Test cross-tenant access attempts if [TENANCY_MODEL] is present
- Include session fixation, session hijacking, and concurrent session tests
- Verify that authorization decisions are enforced at the appropriate layer (middleware, service, data access)
- Flag any authorization checks that appear to be client-side only
- For each test, specify whether it requires automated or manual execution

## EXAMPLES
Example test case:
{
  "test_id": "AUTH-042",
  "category": "authorization",
  "scenario": "User with 'viewer' role attempts to access admin-only endpoint",
  "preconditions": ["Valid JWT for user with role=viewer", "Admin endpoint /api/admin/users is deployed"],
  "action": "GET /api/admin/users with viewer JWT in Authorization header",
  "expected_result": "HTTP 403 Forbidden with error code 'insufficient_permissions'",
  "risk_level": "high",
  "test_type": "automated",
  "references": ["src/middleware/authz.ts:45-78", "src/routes/admin.ts:12"]
}

## RISK_LEVEL
[RISK_LEVEL] (Use 'high' for production authentication systems, 'medium' for internal tools, 'low' for development environments)

After pasting this template, replace each square-bracket placeholder with your actual implementation details. The [INPUT] placeholder should contain the source code, configuration files, or specification documents you want analyzed. For large codebases, consider providing focused excerpts—middleware, guards, decorators, and policy definitions—rather than entire repositories. The [ROLE_DEFINITIONS] placeholder is critical: include a complete mapping of roles to permissions, as gaps here produce incomplete test matrices. If your system uses attribute-based access control (ABAC) rather than role-based (RBAC), adapt the [ROLE_DEFINITIONS] to describe your attribute policies instead. Before running the generated tests, validate the output against your existing test patterns and ensure the test IDs and references map to real code paths.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the Authentication and Authorization Test Prompt needs to produce a reliable test matrix. Each placeholder must be resolved before the prompt is sent. Validation notes describe how to check the input before execution.

PlaceholderPurposeExampleValidation Notes

[ACCESS_CONTROL_MODEL]

Defines the authorization paradigm under test

RBAC, ABAC, ReBAC, PBAC, ACL

Must match one of the enumerated model types. Reject unknown values and request clarification.

[ROLE_DEFINITIONS]

Lists all roles, permissions, and inheritance relationships

admin:full, editor:write, viewer:read

Parse as JSON array of role objects with permissions arrays. Validate no circular inheritance. Schema check required.

[RESOURCE_HIERARCHY]

Describes protected resources and their parent-child relationships

org/{id}/project/{id}/doc/{id}

Must be a valid URI template or JSON tree. Validate that all leaf resources are reachable. Null allowed for flat permission models.

[AUTH_ENDPOINT_SPEC]

OpenAPI or equivalent spec for the authorization endpoints

openapi.yaml or JSON schema

Validate spec parses without errors. Confirm presence of securitySchemes and scopes. Reject if endpoints are missing 401/403 response definitions.

[SESSION_TOKEN_CONFIG]

Token type, lifetime, refresh policy, and storage mechanism

JWT, opaque, refresh rotation enabled

Check that token lifetime is a positive integer. Validate refresh policy is one of: rotation, sliding, fixed. Null allowed if testing stateless auth.

[PRIVILEGE_ESCALATION_VECTORS]

Known or suspected paths for unauthorized access

role mutation, parameter tampering, token reuse

Must be a non-empty array of strings. Each vector should map to a testable scenario. Reject if empty when testing escalation.

[EXISTING_TEST_PATTERNS]

Sample test files showing the project's test conventions

auth.service.spec.ts, permissions.test.py

Parse files to extract framework, assertion style, and fixture patterns. Validate files exist and are syntactically valid. Null allowed for greenfield projects.

[COMPLIANCE_STANDARD]

Regulatory or policy framework the implementation must satisfy

SOC2, HIPAA, PCI-DSS, ISO 27001

Must match a supported standard identifier. Reject unknown standards. Triggers additional control-specific test case generation.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the authentication and authorization test prompt into a secure, auditable application workflow.

This prompt is designed to operate as a security analysis tool, not a live decision-maker. It should be integrated into a CI/CD pipeline or a scheduled security review job, never exposed directly to end users. The harness must enforce strict input validation on the [POLICY_DOCUMENT] and [CODE_CONTEXT] fields, ensuring they are sourced from a trusted, version-controlled repository and not from arbitrary user input. The model's output is a structured test matrix, which must be parsed and validated before any test code is generated or executed.

The implementation should follow a validate → generate → review → execute loop. First, validate that the input policy document is parseable and the code context is scoped to the relevant authorization logic. After the model returns the test matrix, a post-processing validator must check that every role, permission, and resource from the policy is covered by at least one test case. Any missing coverage should trigger a retry with a more specific prompt, such as 'Add test cases for the [MISSING_ROLE] role on the [MISSING_RESOURCE] resource.' The generated test cases should be written to a temporary file and flagged for human review before being committed to the test suite. For high-risk systems, require an explicit approval step in the CI pipeline.

Log every interaction for auditability: the prompt version, the input hashes, the raw model output, the validation results, and the reviewer's decision. Use a structured logging format that ties each test case back to the specific policy rule it verifies. Avoid wiring this prompt directly to a test runner without human review, as the model may misinterpret policy nuances or generate tests that pass but don't actually verify the intended security property. The primary failure mode is a false sense of security from incomplete coverage, so the harness must treat the model's output as a draft requiring expert validation.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the test matrix generated by the Authentication and Authorization Test Prompt. Use this contract to parse, validate, and integrate the output into downstream test runners or security review pipelines.

Field or ElementType or FormatRequiredValidation Rule

test_matrix

Array of Objects

Schema check: root must be a non-empty array. If empty, retry with explicit request for coverage.

test_matrix[].test_id

String (slug)

Format check: must match pattern AUTH-[0-9]{4}. Uniqueness check: no duplicate IDs across the array.

test_matrix[].category

Enum String

Enum check: value must be one of role_based_access, token_validation, session_management, privilege_escalation, direct_object_reference.

test_matrix[].target_endpoint

String (URI path)

Format check: must start with /. Null not allowed. If unresolvable from [API_SPEC], flag for human review.

test_matrix[].http_method

Enum String

Enum check: value must be one of GET, POST, PUT, PATCH, DELETE.

test_matrix[].required_role

String or null

Null check: null is allowed only when testing unauthenticated access. Otherwise, must match a role defined in [ROLE_DEFINITIONS].

test_matrix[].expected_status

Integer

Range check: must be a valid HTTP status code (200-599). If 200, confirm a positive test case exists for the same endpoint.

test_matrix[].assertions

Array of Strings

Content check: each string must describe a verifiable condition (e.g., 'response body is empty', 'error code is FORBIDDEN'). Array must not be empty.

PRACTICAL GUARDRAILS

Common Failure Modes

Authentication and authorization test prompts fail in predictable ways. These failure modes stem from ambiguous role definitions, incomplete permission matrices, and model tendencies to hallucinate security boundaries. Each card below identifies a specific failure and the guardrail that prevents it.

01

Role Ambiguity Leads to Permission Gaps

What to watch: The prompt uses vague role labels like 'admin' or 'viewer' without defining exact permissions. The model invents permissions that don't exist in the system, producing test cases that miss real access control gaps. Guardrail: Provide an explicit permission matrix as a structured input table mapping every role to every resource and action. Validate generated test cases against this matrix before execution.

02

Token Validation Scenarios Skip Edge Cases

What to watch: Generated tests only cover happy-path token validation (valid token, expired token) and miss expired-with-refresh, malformed claims, wrong audience, or cross-tenant token reuse. Guardrail: Include a token lifecycle state machine in the prompt context. Require the model to enumerate all state transitions and generate at least one test per transition boundary.

03

Privilege Escalation Tests Are Too Shallow

What to watch: The model generates obvious escalation attempts (user tries admin endpoint) but misses indirect paths like parameter tampering, nested resource traversal, or role chaining through group membership. Guardrail: Supply a resource hierarchy diagram and require tests for every parent-child traversal. Add a post-generation check that each privilege boundary has at least one cross-boundary test.

04

Session Management Tests Ignore State Transitions

What to watch: Tests cover login and logout but miss session fixation, concurrent session limits, session invalidation after password change, or session persistence across token refresh. Guardrail: Define a session state model with all valid and invalid transitions. Require the model to generate tests that exercise each invalid transition and verify the system rejects them.

05

Generated Assertions Check Status Codes, Not Behavior

What to watch: Tests assert HTTP 403 on denied access but don't verify that no data leaked in the response body, no side effects occurred, and audit logs recorded the attempt. Guardrail: Include an assertion checklist in the output schema requiring data-leak checks, side-effect verification, and audit trail validation for every negative test case.

06

Cross-Tenant Isolation Tests Are Missing

What to watch: Multi-tenant systems need tests verifying that Tenant A cannot access Tenant B's resources even with valid credentials. The model often omits these because the prompt focuses on role-based access within a single tenant. Guardrail: Explicitly require cross-tenant test cases in the prompt constraints. Provide tenant boundary definitions and require at least one test per resource type that attempts cross-tenant access.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality, completeness, and safety of generated authentication and authorization test matrices before integrating them into a CI pipeline or security review.

CriterionPass StandardFailure SignalTest Method

Permission Coverage

Test matrix includes at least one positive and one negative case for every role-permission pair defined in the policy spec.

A role exists in the policy spec but has zero associated test cases in the output.

Parse the output JSON. Extract all unique role-permission pairs. Diff against the provided [POLICY_SPEC] to find missing pairs.

Privilege Escalation

At least one test case attempts to access a resource with a lower-privilege role token and expects a 403 or 401 status.

All generated test cases use the correct role for the target resource; no cross-role access attempts are present.

Scan the [REQUEST_BODY] or [TOKEN] field in each test case. Verify that at least one case uses a mismatched role for the target endpoint.

Token Validation

Includes test cases for expired tokens, malformed JWTs, tokens signed with the wrong algorithm, and missing Authorization headers.

The test matrix only includes valid-token scenarios.

Check the test case descriptions for keywords: 'expired', 'malformed', 'invalid signature', 'missing header'. Count distinct failure modes.

Session Management

Contains test cases for session fixation, logout invalidation, and concurrent session limits if specified in [CONSTRAINTS].

Session-related test cases are absent despite session management being listed in the input context.

If [CONTEXT] mentions sessions, assert that the output contains at least one test case with a 'session' tag or description keyword.

Schema Adherence

The output is valid JSON that strictly matches the [OUTPUT_SCHEMA] provided in the prompt.

The output fails to parse as JSON, or required fields like 'test_id' or 'expected_status' are missing from any test case object.

Run a JSON schema validator against the output using the [OUTPUT_SCHEMA]. Reject on any validation errors.

Idempotency Check

Test cases include setup and teardown steps that can be run repeatedly without manual state reset.

A test case description includes a manual step like 'create a user in the admin panel' without a corresponding API call in the setup block.

Search for manual action keywords ('manually', 'in the dashboard') in the 'setup' field of each test case. Flag any matches for human review.

Edge Case Inclusion

Includes boundary tests such as extremely long tokens, Unicode characters in headers, and deeply nested role hierarchies.

All test inputs use standard ASCII alphanumeric values with no variation in input size or character set.

Scan test case inputs for string length > 256 characters or presence of non-ASCII Unicode characters. Flag if none are found.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single role and a small permission set. Remove structured output requirements and ask for a human-readable test matrix first. Replace [OUTPUT_SCHEMA] with a simple markdown table request.

code
Generate a test matrix for [AUTH_SYSTEM] covering [ROLE_NAME] across these endpoints: [ENDPOINT_LIST].

Watch for

  • Missing negative test cases for denied access
  • Overlooking token expiry and refresh scenarios
  • No distinction between authentication failures and authorization failures
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.