-
Notifications
You must be signed in to change notification settings - Fork 105
feat: support @httpApiKeyAuth trait #473
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
trivikr
merged 5 commits into
smithy-lang:main
from
glb:453-support-http-apikey-auth-trait
Jan 25, 2022
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
7684950
feat: support @httpApiKeyAuth trait
glb 2969bab
fixup! feat: support @httpApiKeyAuth trait
glb 960f792
fixup! feat: support @httpApiKeyAuth trait
glb 5dd6606
fixup! feat: support @httpApiKeyAuth trait
glb 1f16a17
Merge branch 'main' into 453-support-http-apikey-auth-trait
trivikr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
169 changes: 169 additions & 0 deletions
169
...n/java/software/amazon/smithy/typescript/codegen/integration/AddHttpApiKeyAuthPlugin.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,169 @@ | ||
/* | ||
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). | ||
* You may not use this file except in compliance with the License. | ||
* A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0 | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed | ||
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
* express or implied. See the License for the specific language governing | ||
* permissions and limitations under the License. | ||
*/ | ||
|
||
package software.amazon.smithy.typescript.codegen.integration; | ||
|
||
import java.nio.file.Paths; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Set; | ||
import java.util.function.BiConsumer; | ||
import java.util.function.Consumer; | ||
import software.amazon.smithy.codegen.core.Symbol; | ||
import software.amazon.smithy.codegen.core.SymbolDependency; | ||
import software.amazon.smithy.codegen.core.SymbolProvider; | ||
import software.amazon.smithy.model.Model; | ||
import software.amazon.smithy.model.knowledge.ServiceIndex; | ||
import software.amazon.smithy.model.knowledge.TopDownIndex; | ||
import software.amazon.smithy.model.shapes.OperationShape; | ||
import software.amazon.smithy.model.shapes.ServiceShape; | ||
import software.amazon.smithy.model.traits.HttpApiKeyAuthTrait; | ||
import software.amazon.smithy.model.traits.OptionalAuthTrait; | ||
import software.amazon.smithy.typescript.codegen.CodegenUtils; | ||
import software.amazon.smithy.typescript.codegen.TypeScriptSettings; | ||
import software.amazon.smithy.typescript.codegen.TypeScriptWriter; | ||
import software.amazon.smithy.utils.IoUtils; | ||
import software.amazon.smithy.utils.ListUtils; | ||
import software.amazon.smithy.utils.SmithyInternalApi; | ||
|
||
/** | ||
* Add config and middleware to support a service with the @httpApiKeyAuth trait. | ||
*/ | ||
@SmithyInternalApi | ||
public final class AddHttpApiKeyAuthPlugin implements TypeScriptIntegration { | ||
|
||
/** | ||
* Plug into code generation for the client. | ||
* | ||
* This adds the configuration items to the client config and plugs in the | ||
* middleware to operations that need it. | ||
* | ||
* The middleware will inject the client's configured API key into the | ||
* request as defined by the @httpApiKeyAuth trait. If the trait says to | ||
* put the API key into a named header, that header will be used, optionally | ||
* prefixed with a scheme. If the trait says to put the API key into a named | ||
* query parameter, that query parameter will be used. | ||
*/ | ||
@Override | ||
public List<RuntimeClientPlugin> getClientPlugins() { | ||
return ListUtils.of( | ||
// Add the config if the service uses HTTP API key authorization. | ||
RuntimeClientPlugin.builder() | ||
kstich marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.inputConfig(Symbol.builder() | ||
.namespace("./" + CodegenUtils.SOURCE_FOLDER + "/middleware/HttpApiKeyAuth", "/") | ||
.name("HttpApiKeyAuthInputConfig") | ||
.build()) | ||
.resolvedConfig(Symbol.builder() | ||
.namespace("./" + CodegenUtils.SOURCE_FOLDER + "/middleware/HttpApiKeyAuth", "/") | ||
.name("HttpApiKeyAuthResolvedConfig") | ||
.build()) | ||
.resolveFunction(Symbol.builder() | ||
.namespace("./" + CodegenUtils.SOURCE_FOLDER + "/middleware/HttpApiKeyAuth", "/") | ||
.name("resolveHttpApiKeyAuthConfig") | ||
.build()) | ||
.servicePredicate((m, s) -> hasEffectiveHttpApiKeyAuthTrait(m, s)) | ||
.build(), | ||
|
||
// Add the middleware to operations that use HTTP API key authorization. | ||
RuntimeClientPlugin.builder() | ||
.pluginFunction(Symbol.builder() | ||
.namespace("./" + CodegenUtils.SOURCE_FOLDER + "/middleware/HttpApiKeyAuth", "/") | ||
trivikr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.name("getHttpApiKeyAuthPlugin") | ||
.build()) | ||
.additionalPluginFunctionParamsSupplier((m, s, o) -> new HashMap<String, Object>() {{ | ||
// It's safe to do expectTrait() because the operation predicate ensures that the trait | ||
// exists `in` and `name` are required attributes of the trait, `scheme` is optional. | ||
put("in", s.expectTrait(HttpApiKeyAuthTrait.class).getIn().toString()); | ||
put("name", s.expectTrait(HttpApiKeyAuthTrait.class).getName()); | ||
s.expectTrait(HttpApiKeyAuthTrait.class).getScheme().ifPresent(scheme -> | ||
put("scheme", scheme)); | ||
}}) | ||
.operationPredicate((m, s, o) -> ServiceIndex.of(m).getEffectiveAuthSchemes(s, o) | ||
.keySet() | ||
.contains(HttpApiKeyAuthTrait.ID) | ||
&& !o.hasTrait(OptionalAuthTrait.class)) | ||
.build() | ||
); | ||
} | ||
|
||
@Override | ||
public void writeAdditionalFiles( | ||
TypeScriptSettings settings, | ||
Model model, | ||
SymbolProvider symbolProvider, | ||
BiConsumer<String, Consumer<TypeScriptWriter>> writerFactory | ||
) { | ||
ServiceShape service = settings.getService(model); | ||
|
||
// If the service doesn't use HTTP API keys, we don't need to do anything and the generated | ||
// code doesn't need any additional files. | ||
if (!hasEffectiveHttpApiKeyAuthTrait(model, service)) { | ||
return; | ||
} | ||
|
||
String noTouchNoticePrefix = "// Please do not touch this file. It's generated from a template in:\n" | ||
+ "// https://github.com/awslabs/smithy-typescript/blob/main/smithy-typescript-codegen/" | ||
+ "src/main/resources/software/amazon/smithy/aws/typescript/codegen/integration/"; | ||
|
||
// Write the middleware source. | ||
writerFactory.accept( | ||
kstich marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Paths.get(CodegenUtils.SOURCE_FOLDER, "middleware", "HttpApiKeyAuth", "index.ts").toString(), | ||
writer -> { | ||
String source = IoUtils.readUtf8Resource(getClass(), "http-api-key-auth.ts"); | ||
writer.write("$L$L", noTouchNoticePrefix, "http-api-key-auth.ts"); | ||
writer.write("$L", source); | ||
}); | ||
|
||
// Write the middleware tests. | ||
writerFactory.accept( | ||
Paths.get(CodegenUtils.SOURCE_FOLDER, "middleware", "HttpApiKeyAuth", "index.spec.ts").toString(), | ||
writer -> { | ||
writer.addDependency(SymbolDependency.builder() | ||
.dependencyType("devDependencies") | ||
.packageName("@types/jest") | ||
.version("latest") | ||
.build()); | ||
|
||
String source = IoUtils.readUtf8Resource(getClass(), "http-api-key-auth.spec.ts"); | ||
writer.write("$L$L", noTouchNoticePrefix, "http-api-key-auth.spec.ts"); | ||
writer.write("$L", source); | ||
}); | ||
} | ||
|
||
// The service has the effective trait if it's in the "effective auth schemes" response | ||
// AND if not all of the operations have the optional auth trait. | ||
private static boolean hasEffectiveHttpApiKeyAuthTrait(Model model, ServiceShape service) { | ||
return ServiceIndex.of(model).getEffectiveAuthSchemes(service) | ||
.keySet() | ||
.contains(HttpApiKeyAuthTrait.ID) | ||
&& !areAllOptionalAuthOperations(model, service); | ||
} | ||
|
||
|
||
// This is derived from https://github.com/aws/aws-sdk-js-v3/blob/main/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddAwsAuthPlugin.java. | ||
private static boolean areAllOptionalAuthOperations(Model model, ServiceShape service) { | ||
TopDownIndex topDownIndex = TopDownIndex.of(model); | ||
Set<OperationShape> operations = topDownIndex.getContainedOperations(service); | ||
ServiceIndex index = ServiceIndex.of(model); | ||
|
||
for (OperationShape operation : operations) { | ||
if (index.getEffectiveAuthSchemes(service, operation).isEmpty() | ||
kstich marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|| !operation.hasTrait(OptionalAuthTrait.class)) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} | ||
} |
3 changes: 2 additions & 1 deletion
3
...-INF/services/software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
software.amazon.smithy.typescript.codegen.integration.AddEventStreamDependency | ||
software.amazon.smithy.typescript.codegen.integration.AddChecksumRequiredDependency | ||
software.amazon.smithy.typescript.codegen.integration.AddDefaultsModeDependency | ||
software.amazon.smithy.typescript.codegen.integration.AddDefaultsModeDependency | ||
software.amazon.smithy.typescript.codegen.integration.AddHttpApiKeyAuthPlugin |
170 changes: 170 additions & 0 deletions
170
...resources/software/amazon/smithy/typescript/codegen/integration/http-api-key-auth.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
import { | ||
getHttpApiKeyAuthPlugin, | ||
httpApiKeyAuthMiddleware, | ||
resolveHttpApiKeyAuthConfig, | ||
} from "./index"; | ||
import { HttpRequest } from "@aws-sdk/protocol-http"; | ||
|
||
describe("resolveHttpApiKeyAuthConfig", () => { | ||
it("should return the input unchanged", () => { | ||
const config = { | ||
apiKey: "exampleApiKey", | ||
}; | ||
expect(resolveHttpApiKeyAuthConfig(config)).toEqual(config); | ||
}); | ||
}); | ||
|
||
describe("getHttpApiKeyAuthPlugin", () => { | ||
it("should apply the middleware to the stack", () => { | ||
const plugin = getHttpApiKeyAuthPlugin( | ||
{ | ||
apiKey: "exampleApiKey", | ||
}, | ||
{ | ||
in: "query", | ||
name: "key", | ||
} | ||
); | ||
|
||
const mockAdd = jest.fn(); | ||
const mockOther = jest.fn(); | ||
|
||
// TODO there's got to be a better way to do this mocking | ||
plugin.applyToStack({ | ||
add: mockAdd, | ||
// We don't expect any of these others to be called. | ||
addRelativeTo: mockOther, | ||
concat: mockOther, | ||
resolve: mockOther, | ||
applyToStack: mockOther, | ||
use: mockOther, | ||
clone: mockOther, | ||
remove: mockOther, | ||
removeByTag: mockOther, | ||
}); | ||
|
||
expect(mockAdd.mock.calls.length).toEqual(1); | ||
expect(mockOther.mock.calls.length).toEqual(0); | ||
}); | ||
}); | ||
|
||
describe("httpApiKeyAuthMiddleware", () => { | ||
describe("returned middleware function", () => { | ||
const mockNextHandler = jest.fn(); | ||
|
||
beforeEach(() => { | ||
jest.clearAllMocks(); | ||
}); | ||
|
||
it("should set the query parameter if the location is `query`", async () => { | ||
const middleware = httpApiKeyAuthMiddleware( | ||
{ | ||
apiKey: "exampleApiKey", | ||
}, | ||
{ | ||
in: "query", | ||
name: "key", | ||
} | ||
); | ||
|
||
const handler = middleware(mockNextHandler, {}); | ||
|
||
await handler({ | ||
input: {}, | ||
request: new HttpRequest({}), | ||
}); | ||
|
||
expect(mockNextHandler.mock.calls.length).toEqual(1); | ||
expect( | ||
mockNextHandler.mock.calls[0][0].request.query.key | ||
).toBe("exampleApiKey"); | ||
}); | ||
|
||
it("should skip if the api key has not been set", async () => { | ||
const middleware = httpApiKeyAuthMiddleware( | ||
{}, | ||
{ | ||
in: "header", | ||
name: "auth", | ||
scheme: "scheme", | ||
} | ||
); | ||
|
||
const handler = middleware(mockNextHandler, {}); | ||
|
||
await handler({ | ||
input: {}, | ||
request: new HttpRequest({}), | ||
}); | ||
|
||
expect(mockNextHandler.mock.calls.length).toEqual(1); | ||
}); | ||
|
||
it("should skip if the request is not an HttpRequest", async () => { | ||
const middleware = httpApiKeyAuthMiddleware( | ||
{}, | ||
{ | ||
in: "header", | ||
name: "Authorization", | ||
} | ||
); | ||
|
||
const handler = middleware(mockNextHandler, {}); | ||
|
||
await handler({ | ||
input: {}, | ||
request: {}, | ||
}); | ||
|
||
expect(mockNextHandler.mock.calls.length).toEqual(1); | ||
}); | ||
|
||
it("should set the API key in the lower-cased named header", async () => { | ||
const middleware = httpApiKeyAuthMiddleware( | ||
{ | ||
apiKey: "exampleApiKey", | ||
}, | ||
{ | ||
in: "header", | ||
name: "Authorization", | ||
} | ||
); | ||
|
||
const handler = middleware(mockNextHandler, {}); | ||
|
||
await handler({ | ||
input: {}, | ||
request: new HttpRequest({}), | ||
}); | ||
|
||
expect(mockNextHandler.mock.calls.length).toEqual(1); | ||
expect( | ||
mockNextHandler.mock.calls[0][0].request.headers.authorization | ||
).toBe("exampleApiKey"); | ||
}); | ||
|
||
it("should set the API key in the named header with the provided scheme", async () => { | ||
const middleware = httpApiKeyAuthMiddleware( | ||
{ | ||
apiKey: "exampleApiKey", | ||
}, | ||
{ | ||
in: "header", | ||
name: "authorization", | ||
scheme: "exampleScheme", | ||
} | ||
); | ||
const handler = middleware(mockNextHandler, {}); | ||
|
||
await handler({ | ||
input: {}, | ||
request: new HttpRequest({}), | ||
}); | ||
|
||
expect(mockNextHandler.mock.calls.length).toEqual(1); | ||
expect( | ||
mockNextHandler.mock.calls[0][0].request.headers.authorization | ||
).toBe("exampleScheme exampleApiKey"); | ||
}); | ||
}); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.