|
| 1 | +package software.amazon.smithy.kotlin.codegen.service.ktor |
| 2 | + |
| 3 | +import software.amazon.smithy.kotlin.codegen.core.RuntimeTypes |
| 4 | +import software.amazon.smithy.kotlin.codegen.core.withBlock |
| 5 | +import software.amazon.smithy.kotlin.codegen.core.withInlineBlock |
| 6 | +import software.amazon.smithy.kotlin.codegen.service.KtorStubGenerator |
| 7 | +import software.amazon.smithy.kotlin.codegen.service.ServiceTypes |
| 8 | + |
| 9 | +internal fun KtorStubGenerator.writePlugins() { |
| 10 | + renderErrorHandler() |
| 11 | + renderContentTypeGuard() |
| 12 | + renderAcceptTypeGuard() |
| 13 | +} |
| 14 | + |
| 15 | +private fun KtorStubGenerator.renderErrorHandler() { |
| 16 | + delegator.useFileWriter("ErrorHandler.kt", "$pkgName.plugins") { writer -> |
| 17 | + writer.write("internal val ResponseHandledKey = #T<Boolean>(#S)", RuntimeTypes.KtorServerUtils.AttributeKey, "ResponseHandled") |
| 18 | + .write("") |
| 19 | + writer.write("@#T", RuntimeTypes.KotlinxCborSerde.Serializable) |
| 20 | + .write("private data class ErrorPayload(val code: Int, val message: String)") |
| 21 | + .write("") |
| 22 | + .withInlineBlock("internal class ErrorEnvelope(", ")") { |
| 23 | + write("val code: Int,") |
| 24 | + write("val msg: String,") |
| 25 | + write("cause: Throwable? = null,") |
| 26 | + } |
| 27 | + .withBlock(" : RuntimeException(msg, cause) {", "}") { |
| 28 | + withBlock("fun toJson(json: #T = #T): String {", "}", RuntimeTypes.KotlinxJsonSerde.Json, RuntimeTypes.KotlinxJsonSerde.Json) { |
| 29 | + withInlineBlock("return json.encodeToString(", ")") { |
| 30 | + write("ErrorPayload(code, message ?: #S)", "Unknown error") |
| 31 | + } |
| 32 | + } |
| 33 | + withBlock("fun toCbor(cbor: #T = #T { }): ByteArray {", "}", RuntimeTypes.KotlinxCborSerde.Cbor, RuntimeTypes.KotlinxCborSerde.Cbor) { |
| 34 | + withInlineBlock("return cbor.#T(", ")", RuntimeTypes.KotlinxCborSerde.encodeToByteArray) { |
| 35 | + write("ErrorPayload(code, message ?: #S)", "Unknown error") |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + .write("") |
| 40 | + .withInlineBlock("private suspend fun #T.respondEnvelope(", ")", RuntimeTypes.KtorServerCore.ApplicationCallClass) { |
| 41 | + write("envelope: ErrorEnvelope,") |
| 42 | + write("status: #T,", RuntimeTypes.KtorServerHttp.HttpStatusCode) |
| 43 | + } |
| 44 | + .withBlock("{", "}") { |
| 45 | + write("val acceptsCbor = request.#T().any { it.value == #S }", RuntimeTypes.KtorServerRouting.requestAcceptItems, "application/cbor") |
| 46 | + write("val acceptsJson = request.#T().any { it.value == #S }", RuntimeTypes.KtorServerRouting.requestAcceptItems, "application/json") |
| 47 | + write("") |
| 48 | + write("val log = #T.getLogger(#S)", RuntimeTypes.KtorLoggingSlf4j.LoggerFactory, pkgName) |
| 49 | + write("log.info(#S)", "Route Error Message: \${envelope.msg}") |
| 50 | + write("") |
| 51 | + withBlock("when {", "}") { |
| 52 | + withBlock("acceptsCbor -> {", "}") { |
| 53 | + withBlock("#T(", ")", RuntimeTypes.KtorServerRouting.responseRespondBytes) { |
| 54 | + write("bytes = envelope.toCbor(),") |
| 55 | + write("status = status,") |
| 56 | + write("contentType = #T", RuntimeTypes.KtorServerHttp.Cbor) |
| 57 | + } |
| 58 | + } |
| 59 | + withBlock("acceptsJson -> {", "}") { |
| 60 | + withBlock("#T(", ")", RuntimeTypes.KtorServerRouting.responseResponseText) { |
| 61 | + write("envelope.toJson(),") |
| 62 | + write("status = status,") |
| 63 | + write("contentType = #T", RuntimeTypes.KtorServerHttp.Json) |
| 64 | + } |
| 65 | + } |
| 66 | + withBlock("else -> {", "}") { |
| 67 | + withBlock("#T(", ")", RuntimeTypes.KtorServerRouting.responseResponseText) { |
| 68 | + write("envelope.msg,") |
| 69 | + write("status = status") |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + .write("") |
| 75 | + .withBlock("internal fun #T.configureErrorHandling() {", "}", RuntimeTypes.KtorServerCore.Application) { |
| 76 | + write("") |
| 77 | + withBlock( |
| 78 | + "#T(#T) {", |
| 79 | + "}", |
| 80 | + RuntimeTypes.KtorServerCore.install, |
| 81 | + RuntimeTypes.KtorServerStatusPage.StatusPages, |
| 82 | + ) { |
| 83 | + withBlock("status(#T.Unauthorized) { call, status ->", "}", RuntimeTypes.KtorServerHttp.HttpStatusCode) { |
| 84 | + write("if (call.attributes.getOrNull(#T) == true) { return@status }", ServiceTypes(pkgName).responseHandledKey) |
| 85 | + write("call.attributes.put(#T, true)", ServiceTypes(pkgName).responseHandledKey) |
| 86 | + write("val missing = call.request.headers[#S].isNullOrBlank()", "Authorization") |
| 87 | + write("val message = if (missing) #S else #S", "Missing bearer token", "Invalid or expired bearer token") |
| 88 | + write("call.respondEnvelope( ErrorEnvelope(status.value, message), status )") |
| 89 | + } |
| 90 | + write("") |
| 91 | + withBlock("status(#T.NotFound) { call, status ->", "}", RuntimeTypes.KtorServerHttp.HttpStatusCode) { |
| 92 | + write("if (call.attributes.getOrNull(#T) == true) { return@status }", ServiceTypes(pkgName).responseHandledKey) |
| 93 | + write("call.attributes.put(#T, true)", ServiceTypes(pkgName).responseHandledKey) |
| 94 | + write("val message = #S", "Resource not found") |
| 95 | + write("call.respondEnvelope( ErrorEnvelope(status.value, message), status )") |
| 96 | + } |
| 97 | + write("") |
| 98 | + withBlock("status(#T.MethodNotAllowed) { call, status ->", "}", RuntimeTypes.KtorServerHttp.HttpStatusCode) { |
| 99 | + write("if (call.attributes.getOrNull(#T) == true) { return@status }", ServiceTypes(pkgName).responseHandledKey) |
| 100 | + write("call.attributes.put(#T, true)", ServiceTypes(pkgName).responseHandledKey) |
| 101 | + write("val message = #S", "Method not allowed for this resource") |
| 102 | + write("call.respondEnvelope( ErrorEnvelope(status.value, message), status )") |
| 103 | + } |
| 104 | + write("") |
| 105 | + withBlock("#T<Throwable> { call, cause ->", "}", RuntimeTypes.KtorServerStatusPage.exception) { |
| 106 | + withBlock("val status = when (cause) {", "}") { |
| 107 | + write( |
| 108 | + "is ErrorEnvelope -> #T.fromValue(cause.code)", |
| 109 | + RuntimeTypes.KtorServerHttp.HttpStatusCode, |
| 110 | + ) |
| 111 | + write( |
| 112 | + "is #T -> #T.BadRequest", |
| 113 | + RuntimeTypes.KtorServerCore.BadRequestException, |
| 114 | + RuntimeTypes.KtorServerHttp.HttpStatusCode, |
| 115 | + ) |
| 116 | + write( |
| 117 | + "is #T -> #T.PayloadTooLarge", |
| 118 | + RuntimeTypes.KtorServerBodyLimit.PayloadTooLargeException, |
| 119 | + RuntimeTypes.KtorServerHttp.HttpStatusCode, |
| 120 | + ) |
| 121 | + write("else -> #T.InternalServerError", RuntimeTypes.KtorServerHttp.HttpStatusCode) |
| 122 | + } |
| 123 | + write("") |
| 124 | + |
| 125 | + write("val envelope = if (cause is ErrorEnvelope) cause else ErrorEnvelope(status.value, cause.message ?: #S)", "Unexpected error") |
| 126 | + write("call.attributes.put(#T, true)", ServiceTypes(pkgName).responseHandledKey) |
| 127 | + write("call.respondEnvelope( envelope, status )") |
| 128 | + } |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +private fun KtorStubGenerator.renderContentTypeGuard() { |
| 135 | + delegator.useFileWriter("ContentTypeGuard.kt", "$pkgName.plugins") { writer -> |
| 136 | + |
| 137 | + writer.withBlock("private fun #T.hasBody(): Boolean {", "}", RuntimeTypes.KtorServerRouting.requestApplicationRequest) { |
| 138 | + write( |
| 139 | + "return (#T()?.let { it > 0 } == true) || headers.contains(#T.TransferEncoding)", |
| 140 | + RuntimeTypes.KtorServerRouting.requestContentLength, |
| 141 | + RuntimeTypes.KtorServerHttp.HttpHeaders, |
| 142 | + ) |
| 143 | + } |
| 144 | + writer.withBlock("public class ContentTypeGuardConfig {", "}") { |
| 145 | + write("public var allow: List<#T> = emptyList()", RuntimeTypes.KtorServerHttp.ContentType) |
| 146 | + write("") |
| 147 | + withBlock("public fun any(): Unit {", "}") { |
| 148 | + write("allow = listOf(#T)", RuntimeTypes.KtorServerHttp.Any) |
| 149 | + } |
| 150 | + write("") |
| 151 | + withBlock("public fun json(): Unit {", "}") { |
| 152 | + write("allow = listOf(#T)", RuntimeTypes.KtorServerHttp.Json) |
| 153 | + } |
| 154 | + write("") |
| 155 | + withBlock("public fun cbor(): Unit {", "}") { |
| 156 | + write("allow = listOf(#T)", RuntimeTypes.KtorServerHttp.Cbor) |
| 157 | + } |
| 158 | + write("") |
| 159 | + withBlock("public fun text(): Unit {", "}") { |
| 160 | + write("allow = listOf(#T)", RuntimeTypes.KtorServerHttp.PlainText) |
| 161 | + } |
| 162 | + write("") |
| 163 | + withBlock("public fun binary(): Unit {", "}") { |
| 164 | + write("allow = listOf(#T)", RuntimeTypes.KtorServerHttp.OctetStream) |
| 165 | + } |
| 166 | + } |
| 167 | + .write("") |
| 168 | + |
| 169 | + writer.withInlineBlock( |
| 170 | + "public val ContentTypeGuard: #T<ContentTypeGuardConfig> = #T(", |
| 171 | + ")", |
| 172 | + RuntimeTypes.KtorServerCore.ApplicationRouteScopedPlugin, |
| 173 | + RuntimeTypes.KtorServerCore.ApplicationCreateRouteScopedPlugin, |
| 174 | + ) { |
| 175 | + write("name = #S,", "ContentTypeGuard") |
| 176 | + write("createConfiguration = ::ContentTypeGuardConfig,") |
| 177 | + } |
| 178 | + .withBlock("{", "}") { |
| 179 | + write("val allowed: List<#T> = pluginConfig.allow", RuntimeTypes.KtorServerHttp.ContentType) |
| 180 | + write("require(allowed.isNotEmpty()) { #S }", "ContentTypeGuard installed with empty allow-list.") |
| 181 | + write("") |
| 182 | + withBlock("onCall { call ->", "}") { |
| 183 | + write("if (!call.request.hasBody()) return@onCall") |
| 184 | + write("val incoming = call.request.#T()", RuntimeTypes.KtorServerRouting.requestContentType) |
| 185 | + withBlock("if (incoming == #T.Any || allowed.none { incoming.match(it) }) {", "}", RuntimeTypes.KtorServerHttp.ContentType) { |
| 186 | + withBlock("throw #T(", ")", ServiceTypes(pkgName).errorEnvelope) { |
| 187 | + write("#T.UnsupportedMediaType.value, ", RuntimeTypes.KtorServerHttp.HttpStatusCode) |
| 188 | + write("#S", "Not acceptable Content‑Type found: '\${incoming}'. Accepted content types: \${allowed.joinToString()}") |
| 189 | + } |
| 190 | + } |
| 191 | + } |
| 192 | + } |
| 193 | + } |
| 194 | +} |
| 195 | + |
| 196 | +private fun KtorStubGenerator.renderAcceptTypeGuard() { |
| 197 | + delegator.useFileWriter("AcceptTypeGuard.kt", "${ctx.settings.pkg.name}.plugins") { writer -> |
| 198 | + |
| 199 | + writer.withBlock( |
| 200 | + "private fun #T.acceptedContentTypes(): List<#T> {", |
| 201 | + "}", |
| 202 | + RuntimeTypes.KtorServerRouting.requestApplicationRequest, |
| 203 | + RuntimeTypes.KtorServerHttp.ContentType, |
| 204 | + ) { |
| 205 | + write("val raw = headers[#T.Accept] ?: return emptyList()", RuntimeTypes.KtorServerHttp.HttpHeaders) |
| 206 | + write( |
| 207 | + "return #T(raw).mapNotNull { it.value?.let(#T::parse) }", |
| 208 | + RuntimeTypes.KtorServerHttp.parseAndSortHeader, |
| 209 | + RuntimeTypes.KtorServerHttp.ContentType, |
| 210 | + ) |
| 211 | + } |
| 212 | + |
| 213 | + writer.withBlock("public class AcceptTypeGuardConfig {", "}") { |
| 214 | + write("public var allow: List<#T> = emptyList()", RuntimeTypes.KtorServerHttp.ContentType) |
| 215 | + write("") |
| 216 | + withBlock("public fun any(): Unit {", "}") { |
| 217 | + write("allow = listOf(#T)", RuntimeTypes.KtorServerHttp.Any) |
| 218 | + } |
| 219 | + write("") |
| 220 | + withBlock("public fun json(): Unit {", "}") { |
| 221 | + write("allow = listOf(#T)", RuntimeTypes.KtorServerHttp.Json) |
| 222 | + } |
| 223 | + write("") |
| 224 | + withBlock("public fun cbor(): Unit {", "}") { |
| 225 | + write("allow = listOf(#T)", RuntimeTypes.KtorServerHttp.Cbor) |
| 226 | + } |
| 227 | + write("") |
| 228 | + withBlock("public fun text(): Unit {", "}") { |
| 229 | + write("allow = listOf(#T)", RuntimeTypes.KtorServerHttp.PlainText) |
| 230 | + } |
| 231 | + write("") |
| 232 | + withBlock("public fun binary(): Unit {", "}") { |
| 233 | + write("allow = listOf(#T)", RuntimeTypes.KtorServerHttp.OctetStream) |
| 234 | + } |
| 235 | + } |
| 236 | + .write("") |
| 237 | + |
| 238 | + writer.withInlineBlock( |
| 239 | + "public val AcceptTypeGuard: #T<AcceptTypeGuardConfig> = #T(", |
| 240 | + ")", |
| 241 | + RuntimeTypes.KtorServerCore.ApplicationRouteScopedPlugin, |
| 242 | + RuntimeTypes.KtorServerCore.ApplicationCreateRouteScopedPlugin, |
| 243 | + ) { |
| 244 | + write("name = #S,", "AcceptTypeGuard") |
| 245 | + write("createConfiguration = ::AcceptTypeGuardConfig,") |
| 246 | + } |
| 247 | + .withBlock("{", "}") { |
| 248 | + write("val allowed: List<#T> = pluginConfig.allow", RuntimeTypes.KtorServerHttp.ContentType) |
| 249 | + write("require(allowed.isNotEmpty()) { #S }", "AcceptTypeGuard installed with empty allow-list.") |
| 250 | + write("") |
| 251 | + withBlock("onCall { call ->", "}") { |
| 252 | + write("val accepted = call.request.acceptedContentTypes()") |
| 253 | + write("if (accepted.isEmpty()) return@onCall") |
| 254 | + write("") |
| 255 | + write("val isOk = accepted.any { candidate -> allowed.any { candidate.match(it) } }") |
| 256 | + |
| 257 | + withBlock("if (!isOk) {", "}") { |
| 258 | + withBlock("throw #T(", ")", ServiceTypes(pkgName).errorEnvelope) { |
| 259 | + write("#T.NotAcceptable.value, ", RuntimeTypes.KtorServerHttp.HttpStatusCode) |
| 260 | + write("#S", "Not acceptable Accept type found: '\${accepted}'. Accepted types: \${allowed.joinToString()}") |
| 261 | + } |
| 262 | + } |
| 263 | + } |
| 264 | + } |
| 265 | + } |
| 266 | +} |
0 commit comments