Skip to content

Commit a34a833

Browse files
author
luigi
committed
fix
1 parent 3d8bd69 commit a34a833

File tree

15 files changed

+328
-483
lines changed

15 files changed

+328
-483
lines changed

codegen/smithy-kotlin-codegen/src/main/kotlin/software/amazon/smithy/kotlin/codegen/service/ktor/Authentication.kt

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@ internal fun KtorStubGenerator.writeAuthentication() {
1818

1919
writer.withBlock("internal object BearerValidation {", "}") {
2020
withBlock("public fun bearerValidation(token: String): UserPrincipal? {", "}") {
21-
write("// TODO: implement me")
21+
write("// TODO: implement me:")
22+
write("// Validate the provided bearer token and return a UserPrincipal if valid.")
23+
write("// Return a UserPrincipal with user information (e.g., user id, roles) if valid,")
24+
write("// or return null if the token is invalid or expired.")
2225
write("if (true) return UserPrincipal(#S) else return null", "Authenticated User")
2326
}
2427
}
@@ -39,16 +42,14 @@ internal fun KtorStubGenerator.writeAuthentication() {
3942
}
4043
withBlock("sigV4(name = #S) {", "}", "aws-sigv4") {
4144
write("region = #T.region", ServiceTypes(pkgName).serviceFrameworkConfig)
42-
val serviceSigV4AuthTrait = serviceShape.getTrait<SigV4Trait>()
43-
if (serviceSigV4AuthTrait != null) {
44-
write("service = #S", serviceSigV4AuthTrait.name)
45+
serviceShape.getTrait<SigV4Trait>()?.let {
46+
write("service = #S", it.name)
4547
}
4648
}
4749
withBlock("sigV4A(name = #S) {", "}", "aws-sigv4a") {
4850
write("region = #T.region", ServiceTypes(pkgName).serviceFrameworkConfig)
49-
val serviceSigV4AAuthTrait = serviceShape.getTrait<SigV4ATrait>()
50-
if (serviceSigV4AAuthTrait != null) {
51-
write("service = #S", serviceSigV4AAuthTrait.name)
51+
serviceShape.getTrait<SigV4ATrait>()?.let {
52+
write("service = #S", it.name)
5253
}
5354
}
5455
write("provider(#S) { authenticate { ctx -> ctx.principal(Unit) } }", "no-auth")

codegen/smithy-kotlin-codegen/src/main/kotlin/software/amazon/smithy/kotlin/codegen/service/ktor/AuthenticationAWS.kt

Lines changed: 254 additions & 241 deletions
Large diffs are not rendered by default.

codegen/smithy-kotlin-codegen/src/main/kotlin/software/amazon/smithy/kotlin/codegen/service/ktor/OperationHandlers.kt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,18 @@ internal fun KtorStubGenerator.writePerOperationHandlers() {
2020
write("// 1. Use`#T.Builder()`", outputSymbol)
2121
write("// 2. Set fields like `#T.variable = ...`", outputSymbol)
2222
write("// 3. Return the built object using `return #T.build()`", outputSymbol)
23+
write("//")
24+
val errorSymbolNames: List<String> = shape.errors.map { errorShapeId ->
25+
val errorShape = ctx.model.expectShape(errorShapeId)
26+
ctx.symbolProvider.toSymbol(errorShape).name
27+
}
28+
write("// You may also throw custom errors if needed.")
29+
write("// Custom errors can be created using the same builder pattern.")
30+
if (errorSymbolNames.isNotEmpty()) {
31+
write("// Available errors : ${errorSymbolNames.joinToString(", ")}")
32+
} else {
33+
write("// There are no available errors for this operation.")
34+
}
2335
write("return #T.Builder().build()", outputSymbol)
2436
}
2537
}

tests/codegen/service-codegen-tests/model/service-cbor-test.smithy

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ namespace com.cbor
55
use smithy.protocols#rpcv2Cbor
66

77
@rpcv2Cbor
8-
@httpBearerAuth
98
service CborServiceTest {
109
version: "1.0.0"
1110
operations: [
@@ -17,7 +16,6 @@ service CborServiceTest {
1716
}
1817

1918
@http(method: "POST", uri: "/post", code: 201)
20-
@auth([])
2119
operation PostTest {
2220
input: PostTestInput
2321
output: PostTestOutput

tests/codegen/service-codegen-tests/model/service-constraints-test.smithy

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ namespace com.constraints
55
use smithy.protocols#rpcv2Cbor
66

77
@rpcv2Cbor
8-
@httpBearerAuth
98
service ServiceConstraintsTest {
109
version: "1.0.0"
1110
operations: [

tests/codegen/service-codegen-tests/model/service-json-test.smithy

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ namespace com.json
55
use aws.protocols#restJson1
66

77
@restJson1
8-
@httpBearerAuth
98
service JsonServiceTest {
109
version: "1.0.0"
1110
operations: [

tests/codegen/service-codegen-tests/src/main/kotlin/com/test/CborServiceTestGenerator.kt

Lines changed: 0 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -111,58 +111,6 @@ internal fun generateCborServiceTest() {
111111
""".trimIndent()
112112
manifest.writeFile("src/main/kotlin/$packagePath/operations/HttpErrorTestOperation.kt", httpErrorTestOperation)
113113

114-
val bearerValidation = """
115-
package $packageName.auth
116-
117-
internal object BearerValidation {
118-
public fun bearerValidation(token: String): UserPrincipal? {
119-
// TODO: implement me
120-
if (token == "correctToken") return UserPrincipal("Authenticated User") else return null
121-
}
122-
}
123-
""".trimIndent()
124-
manifest.writeFile("src/main/kotlin/$packagePath/auth/Validation.kt", bearerValidation)
125-
126-
val awsValidation = """
127-
package $packageName.auth
128-
129-
import aws.smithy.kotlin.runtime.auth.awscredentials.Credentials
130-
131-
internal object SigV4CredentialStore {
132-
private val table: Map<String, Credentials> = mapOf(
133-
"AKIAIOSFODNN7EXAMPLE" to Credentials(accessKeyId = "AKIAIOSFODNN7EXAMPLE", secretAccessKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"),
134-
"EXAMPLEACCESSKEY1234" to Credentials(accessKeyId = "EXAMPLEACCESSKEY1234", secretAccessKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"),
135-
)
136-
internal fun get(accessKeyId: String): Credentials? {
137-
// TODO: implement me: return Credentials(accessKeyId = ..., secretAccessKey = ...)
138-
return table[accessKeyId]
139-
}
140-
}
141-
142-
internal object SigV4aPublicKeyStore {
143-
private val table: MutableMap<String, java.security.PublicKey> = mutableMapOf()
144-
145-
init {
146-
val pem = ""${'"'}
147-
-----BEGIN PUBLIC KEY-----
148-
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4BB0k4K89eCESVtC39Kzm0HA+lYx
149-
8YF3OZDop7htXAyhGAXn4U70ViNmtG+eWu2bQOXGEIMtoBAEoRk11WXOAw==
150-
-----END PUBLIC KEY-----
151-
""${'"'}.trimIndent()
152-
val clean = pem.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").replace("\\s".toRegex(), "")
153-
val keyBytes = java.util.Base64.getDecoder().decode(clean)
154-
val spec = java.security.spec.X509EncodedKeySpec(keyBytes)
155-
val kf = java.security.KeyFactory.getInstance("EC")
156-
table["EXAMPLEACCESSKEY1234"] = kf.generatePublic(spec)
157-
}
158-
159-
internal fun get(accessKeyId: String): java.security.PublicKey? {
160-
return table[accessKeyId]
161-
}
162-
}
163-
""".trimIndent()
164-
manifest.writeFile("src/main/kotlin/$packagePath/auth/AWSValidation.kt", awsValidation)
165-
166114
val settingGradleKts = """
167115
rootProject.name = "service-cbor-test"
168116
includeBuild("../../../../../")

tests/codegen/service-codegen-tests/src/main/kotlin/com/test/ConstraintsServiceTestGenerator.kt

Lines changed: 0 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -61,58 +61,6 @@ internal fun generateServiceConstraintsTest() {
6161
.build()
6262
KotlinCodegenPlugin().execute(context)
6363

64-
val bearerValidation = """
65-
package $packageName.auth
66-
67-
internal object BearerValidation {
68-
public fun bearerValidation(token: String): UserPrincipal? {
69-
// TODO: implement me
70-
if (token == "correctToken") return UserPrincipal("Authenticated User") else return null
71-
}
72-
}
73-
""".trimIndent()
74-
manifest.writeFile("src/main/kotlin/$packagePath/auth/Validation.kt", bearerValidation)
75-
76-
val awsValidation = """
77-
package $packageName.auth
78-
79-
import aws.smithy.kotlin.runtime.auth.awscredentials.Credentials
80-
81-
internal object SigV4CredentialStore {
82-
private val table: Map<String, Credentials> = mapOf(
83-
"AKIAIOSFODNN7EXAMPLE" to Credentials(accessKeyId = "AKIAIOSFODNN7EXAMPLE", secretAccessKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"),
84-
"EXAMPLEACCESSKEY1234" to Credentials(accessKeyId = "EXAMPLEACCESSKEY1234", secretAccessKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"),
85-
)
86-
internal fun get(accessKeyId: String): Credentials? {
87-
// TODO: implement me: return Credentials(accessKeyId = ..., secretAccessKey = ...)
88-
return table[accessKeyId]
89-
}
90-
}
91-
92-
internal object SigV4aPublicKeyStore {
93-
private val table: MutableMap<String, java.security.PublicKey> = mutableMapOf()
94-
95-
init {
96-
val pem = ""${'"'}
97-
-----BEGIN PUBLIC KEY-----
98-
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4BB0k4K89eCESVtC39Kzm0HA+lYx
99-
8YF3OZDop7htXAyhGAXn4U70ViNmtG+eWu2bQOXGEIMtoBAEoRk11WXOAw==
100-
-----END PUBLIC KEY-----
101-
""${'"'}.trimIndent()
102-
val clean = pem.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").replace("\\s".toRegex(), "")
103-
val keyBytes = java.util.Base64.getDecoder().decode(clean)
104-
val spec = java.security.spec.X509EncodedKeySpec(keyBytes)
105-
val kf = java.security.KeyFactory.getInstance("EC")
106-
table["EXAMPLEACCESSKEY1234"] = kf.generatePublic(spec)
107-
}
108-
109-
internal fun get(accessKeyId: String): java.security.PublicKey? {
110-
return table[accessKeyId]
111-
}
112-
}
113-
""".trimIndent()
114-
manifest.writeFile("src/main/kotlin/$packagePath/auth/AWSValidation.kt", awsValidation)
115-
11664
val settingGradleKts = """
11765
rootProject.name = "service-constraints-test"
11866
includeBuild("../../../../../")

tests/codegen/service-codegen-tests/src/main/kotlin/com/test/JsonServiceTestGenerator.kt

Lines changed: 0 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -187,58 +187,6 @@ internal fun generateJsonServiceTest() {
187187
""".trimIndent()
188188
manifest.writeFile("src/main/kotlin/$packagePath/operations/HttpErrorTestOperation.kt", httpErrorTestOperation)
189189

190-
val bearerValidation = """
191-
package $packageName.auth
192-
193-
internal object BearerValidation {
194-
public fun bearerValidation(token: String): UserPrincipal? {
195-
// TODO: implement me
196-
if (token == "correctToken") return UserPrincipal("Authenticated User") else return null
197-
}
198-
}
199-
""".trimIndent()
200-
manifest.writeFile("src/main/kotlin/$packagePath/auth/Validation.kt", bearerValidation)
201-
202-
val awsValidation = """
203-
package $packageName.auth
204-
205-
import aws.smithy.kotlin.runtime.auth.awscredentials.Credentials
206-
207-
internal object SigV4CredentialStore {
208-
private val table: Map<String, Credentials> = mapOf(
209-
"AKIAIOSFODNN7EXAMPLE" to Credentials(accessKeyId = "AKIAIOSFODNN7EXAMPLE", secretAccessKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"),
210-
"EXAMPLEACCESSKEY1234" to Credentials(accessKeyId = "EXAMPLEACCESSKEY1234", secretAccessKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"),
211-
)
212-
internal fun get(accessKeyId: String): Credentials? {
213-
// TODO: implement me: return Credentials(accessKeyId = ..., secretAccessKey = ...)
214-
return table[accessKeyId]
215-
}
216-
}
217-
218-
internal object SigV4aPublicKeyStore {
219-
private val table: MutableMap<String, java.security.PublicKey> = mutableMapOf()
220-
221-
init {
222-
val pem = ""${'"'}
223-
-----BEGIN PUBLIC KEY-----
224-
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4BB0k4K89eCESVtC39Kzm0HA+lYx
225-
8YF3OZDop7htXAyhGAXn4U70ViNmtG+eWu2bQOXGEIMtoBAEoRk11WXOAw==
226-
-----END PUBLIC KEY-----
227-
""${'"'}.trimIndent()
228-
val clean = pem.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").replace("\\s".toRegex(), "")
229-
val keyBytes = java.util.Base64.getDecoder().decode(clean)
230-
val spec = java.security.spec.X509EncodedKeySpec(keyBytes)
231-
val kf = java.security.KeyFactory.getInstance("EC")
232-
table["EXAMPLEACCESSKEY1234"] = kf.generatePublic(spec)
233-
}
234-
235-
internal fun get(accessKeyId: String): java.security.PublicKey? {
236-
return table[accessKeyId]
237-
}
238-
}
239-
""".trimIndent()
240-
manifest.writeFile("src/main/kotlin/$packagePath/auth/AWSValidation.kt", awsValidation)
241-
242190
val settingGradleKts = """
243191
rootProject.name = "service-json-test"
244192
includeBuild("../../../../../")

tests/codegen/service-codegen-tests/src/test/kotlin/com/test/AuthenticationServiceTest.kt

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,13 @@ import kotlin.test.assertTrue
2222

2323
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
2424
class AuthenticationServiceTest {
25-
val closeGracePeriodMillis: Long = 5_000L
26-
val closeTimeoutMillis: Long = 1_000L
27-
val requestBodyLimit: Long = 10L * 1024 * 1024
28-
val port: Int = ServerSocket(0).use { it.localPort }
29-
30-
val portListnerTimeout = 60L
25+
val closeGracePeriodMillis = TestParams.CLOSE_GRACE_PERIOD_MILLIS
26+
val closeTimeoutMillis = TestParams.CLOSE_TIMEOUT_MILLIS
27+
val gracefulWindow = TestParams.GRACEFUL_WINDOW
28+
val requestBodyLimit = TestParams.REQUEST_BODY_LIMIT
29+
val portListenerTimeout = TestParams.PORT_LISTENER_TIMEOUT
3130

31+
val port: Int = ServerSocket(0).use { it.localPort }
3232
val baseUrl = "http://localhost:$port"
3333

3434
val projectDir: Path = Paths.get("build/service-authentication-test")
@@ -38,12 +38,12 @@ class AuthenticationServiceTest {
3838
@BeforeAll
3939
fun boot() {
4040
proc = startService("netty", port, closeGracePeriodMillis, closeTimeoutMillis, requestBodyLimit, projectDir)
41-
val ready = waitForPort(port, portListnerTimeout)
42-
assertTrue(ready, "Service did not start within $portListnerTimeout s")
41+
val ready = waitForPort(port, portListenerTimeout)
42+
assertTrue(ready, "Service did not start within $portListenerTimeout s")
4343
}
4444

4545
@AfterAll
46-
fun shutdown() = cleanupService(proc)
46+
fun shutdown() = cleanupService(proc, gracefulWindow)
4747

4848
@Test
4949
fun `checks bearer authentication with correct token`() {

0 commit comments

Comments
 (0)