diff --git a/docs/articles/testing-api-key-authentication.md b/docs/articles/testing-api-key-authentication.md new file mode 100644 index 00000000..07ec913f --- /dev/null +++ b/docs/articles/testing-api-key-authentication.md @@ -0,0 +1,62 @@ +--- +title: Testing API Key Authentication +--- + +When running tests there are several ways you might want to handle API Key +authentication. This document outlines a few strategies for testing with API Key +authentication both locally and in deployed environments. + +## Testing Locally + +When running API key Authentication locally, if you +[link](/docs/cli/local-development) the project to an project the same API Key +Bucket used in working copy will also be used for local development. + +Alternatively, you can specify any API Key Bucket on the +[API Key Authentication](/docs/policies/api-key-inbound) policy by setting the +`bucketName` property. + +## Selectively Disabling + +:::danger + +Be extremely careful using this strategy. If configured incorrectly this could +leave your API open to unauthorized access. + +::: + +Another option is to disable authentication on endpoints for testing purposes. +One way of doing this is to configure the +[API Key Authentication](/docs/policies/api-key-inbound) policy to allow +unauthenticated requests through. This can be done by setting +`allowUnauthenticatedRequests` to true. + +In order to enforce authentication with this setting disabled, you can create a +policy that comes after that selectively enforces auth based on some condition. + +For example, an environment variable flag could be used to disable auth with the +following policy. + +```ts +import { + ZuploContext, + ZuploRequest, + environment, + HttpProblems, +} from "@zuplo/runtime"; + +export default async function enforceAuth( + request: ZuploRequest, + context: ZuploContext, +) { + if (environment.DISABLE_AUTH === "AUTH_DISABLED") { + return request; + } + + if (!request.user) { + return HttpProblems.unauthorized(request, context); + } + + return request; +} +``` diff --git a/policies/api-key-inbound/doc.md b/policies/api-key-inbound/doc.md index 2157b22c..51034589 100644 --- a/policies/api-key-inbound/doc.md +++ b/policies/api-key-inbound/doc.md @@ -72,3 +72,9 @@ You have now setup API Key Authentication on your API Gateway. See [this document](/docs/articles/api-key-management) for more information about API Keys and API Key Management with Zuplo. + +## Writing Tests with the Auth Policy + +For information on running tests while using API Key Authentication see the +document +[Testing API Key Authentication](/docs/articles/testing-api-key-authentication). diff --git a/sidebars.js b/sidebars.js index 23a579c9..cccf56a4 100644 --- a/sidebars.js +++ b/sidebars.js @@ -331,6 +331,7 @@ const sidebars = { "cli/test", "cli/tunnels", "cli/variables", + "cli/local-development", ], }, ],