QA How-To
Testing API key authentication (2026)
Learn testing API key authentication across credential states, scopes, tenants, rotation, gateways, secret leakage, and CI with runnable Node.js tests.
22 min read | 4,055 words
TL;DR
Testing API key authentication requires a credential-state and permission matrix, plus lifecycle and leakage checks across the deployed gateway path. Prove each denial causes no protected effect, then verify rotation, revocation, rate policy, caching, and CI secret hygiene.
Key Takeaways
- Test API keys at the real trust boundary, including gateways, caches, services, and alternate routes.
- Separate credential authentication from scope, tenant, object, and administrative authorization.
- Missing, malformed, unknown, expired, disabled, and revoked keys must fail closed without protected effects.
- Rotation tests need explicit old-key overlap, cutoff, new-key continuity, and distributed propagation assertions.
- Use a disposable canary key to search logs, traces, metrics, analytics, and CI artifacts for leakage.
- Run rate and abuse cases with bounded attempts, dedicated accounts, and approved monitoring.
- Keep test keys out of source and reports, issue minimal scope, and fail closed on an unapproved target.
Testing API key authentication requires proof that the service accepts only valid keys at the intended trust boundary, rejects missing or unusable credentials safely, applies the correct tenant and scope, supports rotation, and never leaks secrets through URLs, logs, errors, or observability data.
An API that returns 401 for a random key has only passed one negative case. A production-quality QA strategy also covers gateway behavior, header parsing, key lifecycle, authorization after authentication, rate controls, caching, distributed revocation, and CI secret hygiene. This guide turns those risks into an executable test plan.
TL;DR
| Test area | High-value assertion |
|---|---|
| Placement | The key is accepted only in the documented header or location |
| Negative credentials | Missing, malformed, unknown, revoked, and expired keys fail closed |
| Identity | A valid key maps to the correct client and tenant |
| Authorization | Scope and resource permissions are enforced after key validation |
| Rotation | Old and new keys follow the documented overlap and cutoff policy |
| Leakage | Keys never appear in URLs, bodies, errors, traces, analytics, or logs |
| Abuse controls | Rate limits and alerts are keyed to an appropriate identity |
| Distribution | Revocation reaches every gateway and service instance within policy |
Use dedicated QA keys with minimal scope, test only approved hosts, and assert both the response and the absence of protected side effects. Never place a real API key directly in test source or a command history.
1. Define Testing API Key Authentication at the Trust Boundary
An API key is a credential presented by a calling application or integration. The service uses it to identify a client, project, tenant, or workload. It may also carry or reference permissions. Unlike a user password, an API key commonly represents software rather than a human, and unlike an OAuth access token, it may not have a short lifetime or standardized scope format.
Begin by drawing the trust path: client -> CDN or web application firewall -> API gateway -> service -> downstream service. Identify where the key is extracted, validated, normalized, cached, rate limited, and removed or forwarded. A test against the application process alone can miss a gateway that accepts a query parameter, caches an authenticated response incorrectly, or forwards the credential to an unnecessary dependency.
Write explicit authentication invariants:
- No protected operation succeeds without one valid credential in the approved location.
- One key maps to one documented client identity and tenant context.
- Revoked, expired, disabled, or malformed keys never reach protected business logic.
- Authentication failure reveals no key existence, owner, prefix, or secret fragment.
- Credential material is protected in transit, storage, logging, and test artifacts.
Then separate authentication from authorization. A valid key can identify partner-a but still lack orders:write, access to another partner's order, or permission to call an administrative route. Successful key validation must not become a universal allow decision.
This definition keeps testing API key authentication focused on the credential boundary while connecting it to the authorization and operational controls that make the boundary trustworthy.
2. Document the API Key Contract Before Automating
The contract must state the key location, header name, syntax, identity mapping, status behavior, lifecycle, and rotation rules. OpenAPI 3.2 models API keys with a security scheme whose type is apiKey and whose in value can be header, query, or cookie. That modeling capability is descriptive, not a security recommendation. For server-to-server APIs, a header is usually easier to keep out of URLs and browser history than a query parameter.
An illustrative OpenAPI fragment is:
openapi: 3.2.0
info:
title: Partner Orders API
version: 1.0.0
components:
securitySchemes:
PartnerKey:
type: apiKey
in: header
name: X-API-Key
security:
- PartnerKey: []
This uses real OpenAPI 3.2 security scheme fields. Confirm whether security applies globally or is overridden per operation. An empty operation-level security array can intentionally make an endpoint anonymous, or accidentally expose it.
Define key format only as far as clients need it. A visible prefix can help operators identify the issuing system, but it must not be treated as authentication. Avoid tests that hard-code an assumed length unless the public contract promises it. Server storage should generally avoid retaining recoverable plaintext when a one-way verifier is sufficient, but QA should verify behavior rather than prescribe an implementation without context.
Specify whether header values are trimmed, whether multiple header field values are rejected, and whether an Authorization scheme is used instead of a custom header. Do not silently accept credentials from several locations. Ambiguity creates downgrade and leakage paths.
Finally, document 401 versus 403 policy, error body schema, correlation headers, retry behavior, key expiration, revocation propagation objective, rotation overlap, and support contacts. Automation should enforce this contract rather than inventing universal status expectations.
3. Build a Credential and Authorization Matrix
Use controlled key fixtures that represent lifecycle and permission states. At minimum include valid minimal-scope, valid read-only, valid writer, valid other-tenant, unknown, disabled, revoked, expired, and scheduled-for-rotation keys. Generate malformed strings at runtime. Store real test values in a secret manager or ephemeral fixture service, never in the repository.
Cross credential state with operation sensitivity:
| Credential | Public health | Read own order | Create order | Read other tenant | Admin route |
|---|---|---|---|---|---|
| Missing | Allow if documented | Deny | Deny | Deny | Deny |
| Unknown | Same as missing | Deny | Deny | Deny | Deny |
| Valid read-only | Allow | Allow | Deny | Deny | Deny |
| Valid writer | Allow | Allow | Allow | Deny | Deny |
| Other tenant | Allow | Own tenant only | Own tenant only | Deny | Deny |
| Revoked | Allow if public | Deny | Deny | Deny | Deny |
| Admin test key | Allow | As policy states | As policy states | As policy states | Allow |
Keep authentication and resource authorization assertions distinct. If a read-only key receives 403 on create, that can prove scope enforcement. If the same key receives another tenant's order, authentication worked but object-level authorization failed. Reports should name the failed control correctly.
Add transport variations: correct header, wrong header, query parameter, cookie, duplicate header, blank value, whitespace-only value, unexpected scheme, mixed case header name, and oversized value. HTTP field names are case-insensitive, so a server cannot safely require one capitalization of X-API-Key. The credential value itself can be case-sensitive.
For each denial, assert no durable state change, no queued job, and no protected cache population. Authentication middleware can return the correct response after downstream logic already ran, especially when filters are misordered.
4. Create a Runnable Node.js API Key Test Harness
The following file uses current built-in Node.js APIs. It refuses an unapproved host, reads credentials from environment variables, applies a timeout, and makes focused assertions. Save it as api-key-auth.test.mjs and adjust paths to a dedicated QA API.
import test from 'node:test';
import assert from 'node:assert/strict';
const baseUrl = new URL(process.env.API_BASE_URL ?? '');
const validKey = process.env.QA_PARTNER_API_KEY;
const readOnlyKey = process.env.QA_READ_ONLY_API_KEY;
const allowedHosts = new Set(['localhost', '127.0.0.1', 'api.qa.example.test']);
assert.ok(allowedHosts.has(baseUrl.hostname), `Unapproved test host: ${baseUrl.hostname}`);
assert.ok(validKey, 'QA_PARTNER_API_KEY is required');
assert.ok(readOnlyKey, 'QA_READ_ONLY_API_KEY is required');
async function request(path, { key, method = 'GET', body } = {}) {
const headers = { accept: 'application/json' };
if (key !== undefined) headers['x-api-key'] = key;
if (body !== undefined) headers['content-type'] = 'application/json';
const response = await fetch(new URL(path, baseUrl), {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(8_000),
});
const text = await response.text();
const payload = text ? JSON.parse(text) : null;
return { response, payload };
}
test('valid key reads its client profile', async () => {
const { response, payload } = await request('/v1/client-profile', {
key: validKey,
});
assert.equal(response.status, 200);
assert.equal(payload.environment, 'qa');
assert.equal(typeof payload.clientId, 'string');
assert.equal(Object.hasOwn(payload, 'apiKey'), false);
});
test('missing and unknown keys fail with the same safe shape', async () => {
const missing = await request('/v1/client-profile');
const unknown = await request('/v1/client-profile', {
key: `qa_unknown_${crypto.randomUUID()}`,
});
assert.equal(missing.response.status, 401);
assert.equal(unknown.response.status, 401);
assert.equal(missing.payload.code, 'AUTHENTICATION_REQUIRED');
assert.equal(unknown.payload.code, 'AUTHENTICATION_REQUIRED');
assert.deepEqual(Object.keys(unknown.payload).sort(), Object.keys(missing.payload).sort());
});
test('read-only key cannot create an order', async () => {
const reference = `authz-${crypto.randomUUID()}`;
const { response, payload } = await request('/v1/orders', {
key: readOnlyKey,
method: 'POST',
body: { clientReference: reference, sku: 'QA-BOOK', quantity: 1 },
});
assert.equal(response.status, 403);
assert.equal(payload.code, 'INSUFFICIENT_SCOPE');
});
API_BASE_URL=https://api.qa.example.test \
QA_PARTNER_API_KEY=secret-from-ci \
QA_READ_ONLY_API_KEY=another-secret-from-ci \
node --test api-key-auth.test.mjs
The example does not log headers or payloads on failure. In a real helper, parse error bodies defensively based on content type because a gateway might return HTML or an empty body. Use a secret redaction function for diagnostics and never include even a valid key prefix unless your security policy permits it.
5. Test Missing, Malformed, Unknown, Expired, and Revoked Keys
Negative credential cases should fail closed and look similar to an unauthenticated caller. Test header absence, empty string, spaces, tabs if the client can send them, truncated values, extra suffixes, changed case, non-ASCII data, control-character rejection at the client boundary, oversized input, random valid-looking input, and a real key with one character changed.
Many HTTP clients reject illegal header characters before sending. Record that as client-side protection, then use an approved lower-level component or gateway test for server parsing when necessary. Do not claim the server rejected a value it never received.
Unknown, revoked, and expired credentials should not reveal different owner details or lookup timing that makes key discovery practical. Perfect timing equality is unrealistic in a distributed system, so do not write a brittle millisecond comparison. Instead, review the validation path, collect controlled distributions, and investigate stable, material differences. Error codes should be useful to legitimate operators without confirming sensitive credential state to arbitrary callers.
Test expiration immediately before, at, and after the authoritative boundary using an injected clock or short-lived fixture. Avoid waiting hours in CI. Confirm all instances interpret timestamps consistently and allow only the documented clock tolerance. A key accepted because one node has stale time or stale cache is a distributed security defect.
For revocation, obtain a disposable key, prove it works, revoke it through the supported administration path, and poll until the stated propagation objective. Then call through different gateway nodes or regions if the topology permits. Assert protected state cannot change after the cutoff. Finally, ensure revoking one key does not disable unrelated keys for the same tenant unless the product promises account-wide revocation.
Do not automate repeated guesses at production. Negative tests need a bounded dataset, an approved QA target, and monitoring coordination.
6. Verify Scope, Tenant Isolation, and Object Authorization
API key validation should produce a principal with explicit identity and permissions. Test that the principal is not built from client-controlled headers such as X-Tenant-Id, X-User-Id, or X-Forwarded-For unless a trusted proxy strips and replaces them. Send conflicting identity headers directly to the public edge and confirm the authenticated key remains authoritative.
Use two tenants with similarly shaped data. A key for tenant A should not read, update, delete, search, export, or infer tenant B resources. Cover direct IDs, list filters, bulk endpoints, nested resources, file downloads, asynchronous job status, and error messages. Test both opaque and sequential identifiers.
Scope tests should cover exact permissions and dangerous combinations. A read key cannot write. An orders:write key should not automatically gain customers:read or admin:*. When the API accepts multiple credentials, test how permissions combine. Two insufficient keys must not accidentally produce sufficient privilege unless the contract explicitly supports composite authentication.
Distinguish 401 and 403 according to the service contract. A common design uses 401 when authentication is absent or invalid, then 403 when an authenticated principal lacks permission. Resource-hiding policies may return 404 for an unauthorized object. Whatever the choice, verify consistent behavior and no data leakage through response length, headers, or secondary endpoints.
Assert side effects after every denied write. Search by a unique client reference, inspect the controlled event sink, and verify quotas or counters were not consumed unless denial accounting is intentional. Middleware order can allow a job or audit action to run before authorization returns 403.
The API security testing basics guide expands this matrix into object, property, function, and resource-level controls.
7. Test Key Issuance, Rotation, Revocation, and Recovery
Authentication quality depends on the whole credential lifecycle. Test who can create a key, which scopes can be assigned, whether the secret is shown only at issuance, how key metadata is listed, who can disable it, and how operators recover from accidental exposure. Administrative UI and API paths need the same authorization rigor as the protected business API.
At issuance, verify high-privilege scopes require the intended approval, the key belongs to the selected tenant, and the full secret is not returned by later list or read calls. Metadata can include a safe identifier, created time, last-used time, status, and owner according to policy. Test that a low-privilege administrator cannot mint a more privileged key than their own authority permits.
Rotation normally creates a new credential while an old one remains valid for a controlled overlap. Test the exact timeline:
- Old key works before rotation.
- New key is issued and works with the same intended scope.
- Old and new keys follow the documented overlap.
- Old key fails after explicit revocation or cutoff.
- New key continues to work.
- Audit records identify issuance, activation, and revocation without storing secrets.
Test zero-overlap policies separately. Clients may need an atomic secret update or a dual-key deployment strategy. QA should not assume overlap is always desirable.
Recovery tests simulate a leaked key in an approved environment. Revoke it, confirm propagation, inspect alerts, issue a replacement, and prove unrelated integrations remain stable. If key compromise triggers tenant-wide action, verify the blast radius is intentional and documented.
Lifecycle tests must clean up their generated credentials, but retain safe identifiers for audit assertions. Never store full values in test reports or teardown messages.
8. Detect API Key Leakage Through Transport and Observability
Always use TLS for credentials in transit. Test the public HTTP endpoint, if one exists, and expect a redirect before credentials are sent or a hard rejection. Do not deliberately send a valid key over plaintext. Use a fake value or inspect configuration and gateway behavior safely.
Query parameters are especially risky because URLs appear in browser history, proxy logs, referrer data, monitoring labels, and analytics. If the contract specifies a header key, send a fake key in the query string and confirm it is not accepted. Also test body, cookie, alternate header, and duplicated locations to prevent undocumented fallbacks.
Review sanitized evidence from every layer:
- Edge access logs and web application firewall events.
- Gateway traces and authentication plugin diagnostics.
- Application logs, exception reports, and audit events.
- Distributed traces and baggage.
- Metrics labels and dashboards.
- Message headers and dead-letter payloads.
- CI request dumps, screenshots, videos, and test reports.
Search for the complete disposable key and unique substrings after a controlled request. Secret scanners can help, but direct canary searching gives precise evidence. Ensure redaction happens before data leaves the process, not only in the log viewer. A downstream exporter can retain the original secret even if the UI masks it.
Test error paths because verbose diagnostics often serialize request headers after timeouts or exceptions. Trigger a controlled 500, gateway timeout, unsupported media type, and malformed body with a disposable key, then inspect telemetry. The client helper should redact errors too.
Cache behavior matters. An authenticated response must not become publicly reusable because a CDN ignored the credential header. Request a unique protected resource with a valid key, then repeat without a key and with another tenant's key. Assert no cached data crosses identity boundaries.
9. Validate Rate Limits, Abuse Controls, and Alerts
API keys often serve as the identity for quotas and abuse detection. Test the documented limit with a small configurable threshold in QA. Send requests just below, at, and above the boundary. Assert the status, stable machine code, retry guidance, and whether rejected requests count toward the quota.
Confirm counters use the right scope. A single key may have its own quota, all keys for one tenant may share a quota, or limits may combine client identity, route cost, and source network. Test two keys from one tenant and keys from two tenants. A noisy partner must not exhaust every customer unless a global safety limit intentionally activates.
Invalid key attempts need protection too. If rate limiting occurs only after successful authentication, attackers can generate unlimited verifier work or key lookups. If limiting occurs only by source IP, shared networks can cause collateral blocking. QA should verify the layered policy rather than demand one universal algorithm.
Use bounded load in an isolated environment. Coordinate with operations and define a stop condition. Confirm rate-limit testing does not page the real incident team unless alert validation is the approved objective.
Alert tests use a canary credential and unique run identifier. Verify repeated invalid attempts, use of a revoked key, unusual route access, or impossible location changes produce the intended security signal without including the secret. Validate deduplication and routing so one event is actionable rather than thousands of alerts.
Inspect reset behavior and clock boundaries. Fixed-window, rolling-window, and token-bucket implementations produce different valid results. Assert the product's documented model, not an assumed second-by-second pattern. The API rate limiting testing guide covers deeper concurrency and recovery cases.
10. Test Gateways, Caches, and Distributed Validation
In many systems, the gateway authenticates the key and forwards trusted identity metadata to services. Test the public edge and the service boundary separately. Direct service access should be network-restricted or require equivalent authentication. A caller must not bypass the gateway and supply a forged X-Authenticated-Client header.
Verify the gateway strips inbound identity headers before adding its own. Use a fake key with a privileged client header and expect denial. Use a valid low-privilege key with the same forged header and expect the permissions of the real key. Repeat through alternate hostnames, ports, legacy paths, and versioned routes.
Authentication caches improve availability but complicate revocation. Test cache hit behavior, expiration, negative caching, key rotation, authorization changes, and verifier outage. Decide whether the service fails closed during an identity-store outage. If a short grace period is part of the availability policy, document and test its exact limits for already validated keys versus new keys.
Distributed systems also need consistent key parsing. One gateway version must not trim or normalize differently from another. Send boundary cases through multiple nodes or deployment revisions during a rolling release. A key accepted only by half the fleet creates intermittent failures and can create security gaps.
Check response caching with Vary and private cache policies as appropriate, but test behavior rather than relying only on header presence. Proxies can be misconfigured. Also confirm health, documentation, and preflight routes are anonymously reachable only when intended, while similarly named business routes remain protected.
Use correlation IDs to link edge denial and service absence. For an invalid key, the expected trace should end at the authentication boundary without protected resolver, repository, or publisher work.
11. Keep API Key Tests Safe and Maintainable in CI
Create a small credential fixture catalog with clear owners and scopes. Prefer short-lived or automatically rotated QA keys. Keep values in the CI secret store and expose them only to jobs that need them. Forked pull requests and untrusted branches should not receive shared secrets.
Fail closed on configuration. Validate the target scheme and hostname before reading or sending a key. Do not default to production. Avoid commands that place secrets in process lists or shell history. Environment variables are common for examples, but a mature CI platform should inject secrets through its supported protected mechanism and mask output.
Split the suite by cost and privilege. Pull requests can run missing, malformed, valid minimal-scope, and authorization smoke cases. Main-branch jobs can add tenant matrices and rotation checks. Scheduled security jobs can test revocation propagation, telemetry leakage, rate policies, and controlled verifier failures.
Use unique business references and disposable tenants. Authentication tests that create resources must prove denial caused no write and must clean successful fixtures safely. Do not share a mutable quota or key across parallel workers unless the test is explicitly about shared behavior.
Reports should include safe key identifiers, never secrets. Record credential state, expected client identity, route, status, error code, correlation ID, target revision, and postcondition evidence. If a secret appears in an artifact, treat that as a security incident for the test environment and rotate it.
Review the OpenAPI security scheme and deployed route inventory together. New endpoints can omit global security or override it accidentally. Contract linting helps, but a runtime crawler or route manifest check should confirm each protected operation denies an anonymous request.
12. Scale Testing API Key Authentication by Risk
Not every endpoint needs every lifecycle scenario. Build a core conformance suite that runs against representative read and write operations, then add focused coverage where risk changes. Administrative, bulk export, billing, destructive, and cross-tenant endpoints deserve the deepest scope and side-effect assertions.
At the component layer, test verifier hashing, constant-shape errors, status transitions, cache entries, and trusted principal construction. At the gateway layer, test extraction, header stripping, limits, caching, and routing. At the deployed API layer, test the external contract, tenant isolation, and observable business effects. This separation gives fast diagnosis without duplicating every case at every layer.
Track coverage as behaviors, not request count. Useful measures include protected operations checked anonymously, scope classes exercised, tenant boundaries tested, lifecycle states represented, gateways covered, revocation propagation sampled, and telemetry sinks searched for canary secrets.
Revisit the threat model when a key moves from internal service use to a partner, browser, mobile app, command-line tool, or customer-controlled environment. A key embedded in distributed client software cannot remain secret. That architecture may require a user-mediated OAuth flow, short-lived tokens, a backend-for-frontend, or another design rather than stronger obfuscation.
Testing API key authentication is complete only when the credential behavior, permission boundary, lifecycle, distributed enforcement, and secret handling all match the documented risk decision.
Interview Questions and Answers
Q: What is the first thing you clarify before testing API key authentication?
I clarify where the key is sent, which component validates it, what identity and scopes it creates, and the expected failure contract. I also map gateways, caches, and downstream forwarding. That tells me where bypass, leakage, and stale revocation can occur.
Q: How do you distinguish authentication from authorization in these tests?
Authentication answers which client the key represents. Authorization decides whether that client can execute an operation or access an object. I use valid keys with different scopes and tenants so a 403 or resource-hiding response tests authorization separately from invalid-key behavior.
Q: Which negative API key cases are essential?
I cover missing, blank, malformed, unknown, expired, disabled, and revoked keys, plus wrong placement and duplicate credentials. Every denial must fail closed, use a safe error shape, and cause no protected state change. I also check that telemetry does not capture the supplied value.
Q: How would you test API key rotation?
I prove the old key works before rotation, issue the new key, verify the documented overlap, revoke or expire the old key, and confirm the new key continues working. I test propagation across nodes and inspect safe audit events. The exact overlap is a product policy, not a universal rule.
Q: Why are API keys in query parameters risky?
URLs are commonly copied into histories, access logs, analytics, referrer data, and monitoring labels. A header credential is less likely to spread through those paths, though it still needs redaction. If the contract uses a header, I verify query and body fallbacks are rejected.
Q: How do you test revocation in a distributed system?
I use a disposable working key, revoke it through the supported path, and poll through different gateway or service nodes until the stated objective. I verify no writes occur after cutoff and review cache behavior. I also confirm unrelated keys remain valid.
Q: What evidence would you include in an authentication defect?
I include the safe key identifier and state, route, credential placement, expected identity or denial, actual status and code, correlation ID, node or region, revision, and postcondition evidence. I redact the full key and sensitive resource data. For leakage, I identify the exact telemetry sink and retention path.
Q: Can an API key be safely embedded in a browser or mobile app?
A secret distributed to untrusted client devices should be assumed extractable. I would flag the architecture and clarify what the key protects. Public client scenarios usually need a design based on user authorization, short-lived tokens, sender constraints where applicable, or a trusted backend rather than a long-lived shared secret.
Common Mistakes
- Testing one random invalid key and declaring authentication complete.
- Confusing a valid key with permission to every route and object.
- Accepting the same credential from headers, query strings, bodies, and cookies.
- Requiring one capitalization of an HTTP header field name.
- Hard-coding real QA or production keys in source, fixtures, or examples.
- Logging request headers when a test fails.
- Testing status codes without proving denied writes made no side effects.
- Ignoring gateway caches and testing revocation on one process only.
- Using production traffic to test brute-force or rate controls.
- Treating a visible key prefix as proof of authenticity.
- Rotating the old key before proving the new deployment works, unless zero overlap is intentional.
- Embedding a shared secret in distributed client software and relying on obfuscation.
Conclusion
Testing API key authentication is a trust-boundary exercise, not a single 401 assertion. Verify credential placement and parsing, identity mapping, scope and tenant isolation, lifecycle transitions, distributed revocation, abuse controls, cache behavior, and secret-safe telemetry.
Begin with a credential-state matrix and one read plus one write operation. Add postcondition checks for every denial, then expand into rotation, gateway bypass, canary leakage, and revocation propagation according to the API's real deployment and risk.
Interview Questions and Answers
How do you start testing API key authentication?
I map where the key enters, which component validates it, and which identity and permissions result. Then I define credential states and representative protected operations. I also include gateways, caches, and alternate routes in the trust path.
How is API key authentication different from authorization?
Authentication maps the key to a client identity. Authorization controls scopes, operations, objects, and tenant data for that client. I use valid keys with different permissions so those controls are tested independently.
Which negative API key cases are essential?
I cover missing, blank, malformed, unknown, disabled, expired, revoked, wrong-location, and duplicate credentials. Each case must fail closed and create no protected business effect. I also inspect errors and telemetry for leakage.
How would you test key rotation?
I validate the old key, issue the new one, test the documented overlap, enforce the old-key cutoff, and prove new-key continuity. I sample multiple gateway nodes and inspect safe audit events. I never include full key values in evidence.
How do you test tenant isolation with API keys?
I use two tenants with similar data and vary resource ownership independently from the key. I cover direct IDs, lists, bulk operations, exports, and asynchronous jobs. Denials must not leak existence or create side effects.
How do you test for API key leakage?
I use a disposable canary key, trigger normal and error paths, and search logs, traces, metrics, analytics, cache diagnostics, and CI artifacts. Redaction must occur before data leaves the process. The canary is revoked after the test.
How do you test rate limits safely?
I configure a small QA threshold, use bounded requests and a stop condition, and coordinate with operations. I test the boundary, reset, counter scope, and alternate routes. I never use customer keys or uncontrolled production traffic.
What should an API key defect report contain?
It should contain a safe credential identifier and state, route, expected identity or denial, status and error code, correlation ID, node or region, revision, and postcondition evidence. The key itself and sensitive data must be redacted.
Frequently Asked Questions
What test cases are needed for API key authentication?
Cover valid, missing, blank, malformed, unknown, expired, disabled, revoked, wrong-location, and duplicate credentials. Add scope, tenant, object authorization, rotation, revocation propagation, rate controls, cache isolation, and leakage checks.
Should an API key be sent in a header or query parameter?
Follow the documented API contract, but headers are generally easier to keep out of URL histories, referrer data, analytics, and access logs. If a header is specified, tests should prove query, body, and cookie fallbacks are not accepted.
What status should an invalid API key return?
Many APIs use 401 for missing or invalid authentication and 403 for an authenticated principal that lacks permission. Resource-hiding policies may differ. Tests should enforce the published contract and safe error shape.
How do you test API key rotation?
Prove the old key works, issue and validate the new key, exercise the documented overlap, then revoke or expire the old key. Verify the new key remains valid and the cutoff propagates across every relevant node.
How do you test API key revocation?
Use a disposable working key, revoke it through the supported administration path, and poll until the stated propagation objective. Call through different gateways or regions and prove no protected write succeeds after cutoff.
How can QA detect API key leakage?
Send a disposable canary key through controlled success and error paths, then search each telemetry and artifact sink for the full value and unique substrings. Verify redaction occurs before export, not only in the log viewer.
Can API keys be safely stored in browser code?
A shared secret distributed to an untrusted browser or mobile client should be assumed extractable. The architecture may need user authorization, short-lived tokens, a trusted backend, or another public-client design instead of obfuscation.