diff --git a/CHANGELOG.md b/CHANGELOG.md index bc3b11affc..cd8cf1caa7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -211,6 +211,33 @@ Each item below is described in full under Security, Added, Changed or Fixed; th treated as credentials, and stripping does not recurse into nested objects. Declare credentials as top-level entity fields until that is fixed. +- **Fix, Java and Kotlin: a credential was returned in every response under a snake or kebab + Jackson naming strategy.** The generated Spring controllers (`codegen-spring` and + `codegen-kotlin`) omitted a credential (a `view.password` field) by serializing the row to a + JSON tree and removing the key spelled with the field name (`pinHash`). The generated DTO and + data class carry no wire annotation for it, so its key is whatever the host's `ObjectMapper` + makes of the property: under `PropertyNamingStrategies.SNAKE_CASE` (what + `spring.jackson.property-naming-strategy=SNAKE_CASE` sets) the key is `pin_hash`, under + `KEBAB_CASE` it is `pin-hash`, the removal found nothing, and a multi-word credential was sent + in every list, get, create and update echo, M:N traversal, TPH, projection and report response. + **Released Java and Kotlin 8.2.0 to 8.2.3 are affected**; a host on Jackson's default naming + with no mixin or `@JsonProperty` rename was safe. 1.3.0 fixes it: the generated `redact` helper + reads each credential's key from the mapper's own serialization contract + (`SerializationConfig.introspect(...).findProperties()`, matched on the property's internal + name), so a naming strategy, a mixin or a `@JsonProperty` cannot escape it, and caches the keys + per row class. Stripping **fails closed**, as the C# fix does: when the contract cannot be read + (the row's serializer is not a bean serializer, or the class declares the credential but the + contract has no property for it and does not ignore it), the request is refused with an + exception naming the type and the credential property (never a value) instead of being sent + unstripped. A key that spells the credential ignoring case, `_` and `-` is also removed. The + report CSV and XML exports were not affected: they write a fixed column list chosen at codegen + time, with credential columns left out, and never go through Jackson. Regenerate every Java or + Kotlin project whose host sets a naming strategy; adopters with ejected (owned) controller + generators need the same change made by hand. Gated by a `none`/`snake`/`kebab` naming + parameter on the Java and Kotlin `secret-fields` generated-controller lanes (list, get by id and + an inheriting projection), which leak under `snake` and `kebab` without the fix. Request bodies + are unchanged and out of scope here: a PATCH or PUT key is still read by the field name. + ### Added - **A working loop first in the agent context.** The always-on file `meta init` scaffolds diff --git a/fixtures/api-contract-conformance/secret-fields/README.md b/fixtures/api-contract-conformance/secret-fields/README.md index 4807ce6836..a7cc3b7f69 100644 --- a/fixtures/api-contract-conformance/secret-fields/README.md +++ b/fixtures/api-contract-conformance/secret-fields/README.md @@ -23,6 +23,12 @@ The model is one `Account`: - **A present `null` is a write**, so it does not reach a denied column either. - **A credential is never returned**: not by list, not by get, not in the echo of a create or an update. The key is absent from the object, not `null`. +- **Redaction does not depend on the host's JSON naming.** The credential is absent whatever key + the host's serializer would give it: a snake or kebab naming strategy or policy (`pin_hash`, + `pin-hash`), a rename, a mixin. Each port reads the key from its serializer's own contract + rather than spelling the field name, and refuses a response it cannot strip instead of + sending it. The Java and Kotlin generated lanes drive the corpus's reads under no naming + strategy, `SNAKE_CASE` and `KEBAB_CASE`. - **A `readOnly` field is ignored on every write the same way**, and returned like any other field: the server owns its value (here, the seeded `role`), so a create leaves it `null`. - **`@formExclude` alone does not hide a field.** It says how the field is written, and the diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt index 45203ad6e0..42015261f3 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt @@ -272,13 +272,82 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase) { + private fun appendRedactor(sb: StringBuilder, shortName: String, creds: Collection, strips: Boolean) { + if (strips) appendStripCredentials(sb) if (creds.isEmpty()) return sb.append("/** GENERATED — the ${shortName} response value with its credential field(s) removed. */\n") sb.append("private fun redact${shortName}(mapper: ObjectMapper, row: ${shortName}): Any =\n") - sb.append(" mapper.valueToTree(row).apply { remove(listOf(${creds.joinToString(", ") { "\"$it\"" }})) }\n\n") + sb.append(" stripCredentials(mapper, row, ${creds.joinToString(", ") { "\"$it\"" }})\n\n") + } + + /** + * #484: the file-private helper every redaction goes through. The data class carries no wire annotation + * for a credential, so its JSON key is whatever the host's ObjectMapper makes of the property: a naming + * strategy (`SNAKE_CASE` writes `pinHash` as `pin_hash`), a mixin, a `@JsonProperty`. The key is READ from + * that mapper's serialization contract, never re-derived from the property name, and cached per row + * class. A contract that cannot be read (a custom serializer, a credential the class declares but the + * contract has no property for) refuses the response (throws, 500) instead of sending it unstripped. + * As a second line of defence any key spelling a credential ignoring case, `_` and `-` is removed too. + */ + private fun appendStripCredentials(sb: StringBuilder) { + sb.append( + """ + |/** GENERATED — #484: the wire keys of each row class's credentials, read once from the mapper's contract. */ + |private val credentialWireKeys = java.util.concurrent.ConcurrentHashMap, List>, Set>() + | + |/** + | * GENERATED — #484: [row] as a JSON tree with its credential properties [hidden] removed, under the keys + | * [mapper] actually writes them with (a naming strategy, mixin or @JsonProperty is honoured), plus any key + | * that spells one ignoring case, `_` and `-`. Throws rather than send a row it cannot strip. + | */ + |private fun stripCredentials(mapper: ObjectMapper, row: Any, vararg hidden: String): com.fasterxml.jackson.databind.node.ObjectNode { + | val node = mapper.valueToTree(row) + | node.remove(credentialWireKeys.computeIfAbsent(Triple(mapper, row.javaClass, hidden.toList())) { credentialKeysOf(mapper, row.javaClass, hidden) }) + | val spelled = hidden.map { normalizedKey(it) }.toSet() + | node.remove(node.fieldNames().asSequence().filter { normalizedKey(it) in spelled }.toList()) + | return node + |} + | + |/** GENERATED — #484: the JSON keys [mapper] writes the credential properties [hidden] of [type] under. */ + |private fun credentialKeysOf(mapper: ObjectMapper, type: Class<*>, hidden: Array): Set { + | val desc: com.fasterxml.jackson.databind.BeanDescription = mapper.serializationConfig.introspect(mapper.constructType(type)) + | val serializer = try { + | mapper.serializerProviderInstance.findValueSerializer(type) + | } catch (e: com.fasterxml.jackson.databind.JsonMappingException) { + | throw unstrippable(type, hidden.toList(), "the mapper has no serializer for it", e) + | } + | if (serializer !is com.fasterxml.jackson.databind.ser.std.BeanSerializerBase) { + | throw unstrippable(type, hidden.toList(), "its serializer is not a bean serializer (a custom serializer?)", null) + | } + | val keys = HashSet() + | for (name in hidden) { + | val matched = desc.findProperties().filter { it.internalName == name }.map { it.name } + | if (matched.isEmpty() && declaresMember(type, name) && name !in desc.ignoredPropertyNames) { + | throw unstrippable(type, listOf(name), "the credential has no property in the mapper's contract", null) + | } + | keys += matched + | } + | return keys + |} + | + |private fun declaresMember(type: Class<*>, name: String): Boolean = + | generateSequence(type) { it.superclass }.takeWhile { it != Any::class.java }.any { c -> c.declaredFields.any { it.name == name } } + | + |private fun normalizedKey(key: String): String = key.replace("_", "").replace("-", "").lowercase() + | + |private fun unstrippable(type: Class<*>, credentials: List, why: String, cause: Throwable?): IllegalStateException = + | IllegalStateException( + | "cannot strip the credential " + credentials.joinToString(", ") { type.simpleName + "." + it } + " from a response: " + why + + | ". Credential stripping reads the ObjectMapper's serialization contract; the response is refused rather than sent unstripped.", + | cause, + | ) + | + | + """.trimMargin() + ) } private fun credentialNames(fields: Collection>): List = @@ -350,7 +419,8 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase navs.any { it.targetCredentialFields.isNotEmpty() } } + val needsMapper = anyPatchFields || rejectUnknown || strips val src = buildString { if (pkg.isNotEmpty()) append("package $pkg\n\n") @@ -1062,7 +1133,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase" else ""} = $query.map { row ->\n") - if (creds.isNotEmpty()) out.append(" objectMapper.valueToTree(\n") + if (creds.isNotEmpty()) out.append(" stripCredentials(\n objectMapper,\n") out.append(" $targetType(\n") for (fname in nav.targetScalarFields) { out.append(" $fname = row[${nav.targetTableObj}.$fname],\n") } - out.append(" )\n") + out.append(" )${if (creds.isNotEmpty()) "," else ""}\n") if (creds.isNotEmpty()) { - out.append(" ).apply { remove(listOf(${creds.joinToString(", ") { "\"$it\"" }})) }\n") + out.append(" ${creds.joinToString(", ") { "\"$it\"" }},\n )\n") } out.append(" }\n") out.append(" ResponseEntity.ok(rows)\n") @@ -2342,7 +2413,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase hidden) { StringBuilder b = new StringBuilder(); - for (String h : hidden) b.append(", \"").append(h).append('"'); + // The record component's name, which is the member Jackson's contract knows it by. + for (String h : hidden) b.append(", \"").append(SpringNaming.recordComponentName(h)).append('"'); return b.toString(); } @@ -1919,11 +1920,28 @@ private static String okMapper(List hidden) { * #484 — the helpers a controller uses to leave credential fields out of response bodies. The * shared DTO keeps the member (the application's own code reads and writes it); only the * generated HTTP boundary drops the key, so a credential is ABSENT, not null. + * + *

The DTO carries no wire annotation for the credential, so its key is whatever the host's + * {@code ObjectMapper} makes of the member: a property naming strategy ({@code SNAKE_CASE} writes + * {@code pinHash} as {@code pin_hash}), a mixin, a {@code @JsonProperty}. The key is therefore + * READ from that mapper's own serialization contract, never re-derived from the field name, and + * cached per row class. When the contract cannot be read (a custom serializer, a credential the + * class declares but the contract has no property for) the response is refused (500), never + * sent unstripped. As a second line of defence any key that spells a credential ignoring case, + * {@code _} and {@code -} is removed too. */ private static void appendRedactHelpers(StringBuilder src) { + src.append(" /** #484: the wire keys of each row class's credentials, read once from objectMapper's contract. */\n"); + src.append(" private final java.util.Map, java.util.Set> credentialWireKeys = new java.util.concurrent.ConcurrentHashMap<>();\n\n"); src.append(" private Object redact(Object row, String... hidden) {\n"); src.append(" com.fasterxml.jackson.databind.node.ObjectNode node = objectMapper.valueToTree(row);\n"); - src.append(" node.remove(java.util.Arrays.asList(hidden));\n"); + src.append(" node.remove(credentialWireKeys.computeIfAbsent(\n"); + src.append(" List.of(row.getClass(), List.of(hidden)), k -> credentialKeysOf(row.getClass(), hidden)));\n"); + src.append(" java.util.Set spelled = new java.util.HashSet<>();\n"); + src.append(" for (String h : hidden) spelled.add(normalizedKey(h));\n"); + src.append(" List stray = new java.util.ArrayList<>();\n"); + src.append(" node.fieldNames().forEachRemaining(k -> { if (spelled.contains(normalizedKey(k))) stray.add(k); });\n"); + src.append(" node.remove(stray);\n"); src.append(" return node;\n"); src.append(" }\n\n"); src.append(" private List redactAll(List rows, String... hidden) {\n"); @@ -1931,6 +1949,49 @@ private static void appendRedactHelpers(StringBuilder src) { src.append(" for (Object row : rows) out.add(redact(row, hidden));\n"); src.append(" return out;\n"); src.append(" }\n\n"); + src.append(" /**\n"); + src.append(" * The JSON keys objectMapper writes the credential members {@code hidden} of {@code type} under,\n"); + src.append(" * read from its serialization contract so a naming strategy, mixin or @JsonProperty is honoured.\n"); + src.append(" * Throws (the response is refused, never sent unstripped) when the contract cannot be read.\n"); + src.append(" */\n"); + src.append(" private java.util.Set credentialKeysOf(Class type, String... hidden) {\n"); + src.append(" com.fasterxml.jackson.databind.SerializationConfig config = objectMapper.getSerializationConfig();\n"); + src.append(" com.fasterxml.jackson.databind.BeanDescription desc = config.introspect(objectMapper.constructType(type));\n"); + src.append(" try {\n"); + src.append(" if (!(objectMapper.getSerializerProviderInstance().findValueSerializer(type)\n"); + src.append(" instanceof com.fasterxml.jackson.databind.ser.std.BeanSerializerBase)) {\n"); + src.append(" throw unstrippable(type, hidden, \"its serializer is not a bean serializer (a custom serializer?)\");\n"); + src.append(" }\n"); + src.append(" } catch (com.fasterxml.jackson.databind.JsonMappingException e) {\n"); + src.append(" throw unstrippable(type, hidden, \"the mapper has no serializer for it\");\n"); + src.append(" }\n"); + src.append(" java.util.Set keys = new java.util.HashSet<>();\n"); + src.append(" for (String name : hidden) {\n"); + src.append(" boolean matched = false;\n"); + src.append(" for (com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition p : desc.findProperties()) {\n"); + src.append(" if (p.getInternalName().equals(name)) { keys.add(p.getName()); matched = true; }\n"); + src.append(" }\n"); + src.append(" if (!matched && declaresMember(type, name) && !desc.getIgnoredPropertyNames().contains(name)) {\n"); + src.append(" throw unstrippable(type, new String[] {name}, \"the credential has no property in the mapper's contract\");\n"); + src.append(" }\n"); + src.append(" }\n"); + src.append(" return keys;\n"); + src.append(" }\n\n"); + src.append(" private static boolean declaresMember(Class type, String name) {\n"); + src.append(" for (Class c = type; c != null && c != Object.class; c = c.getSuperclass()) {\n"); + src.append(" for (java.lang.reflect.Field f : c.getDeclaredFields()) if (f.getName().equals(name)) return true;\n"); + src.append(" }\n"); + src.append(" return false;\n"); + src.append(" }\n\n"); + src.append(" private static String normalizedKey(String key) {\n"); + src.append(" return key.replace(\"_\", \"\").replace(\"-\", \"\").toLowerCase(java.util.Locale.ROOT);\n"); + src.append(" }\n\n"); + src.append(" private static IllegalStateException unstrippable(Class type, String[] credentials, String why) {\n"); + src.append(" return new IllegalStateException(\"cannot strip the credential \" + type.getSimpleName() + \".\"\n"); + src.append(" + String.join(\", \" + type.getSimpleName() + \".\", credentials) + \" from a response: \" + why\n"); + src.append(" + \". Credential stripping reads the ObjectMapper's serialization contract; the response is\"\n"); + src.append(" + \" refused rather than sent unstripped.\");\n"); + src.append(" }\n\n"); } private static void appendServerOwnedOnCreate(StringBuilder src, MetaObject entity) { diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/SecretFieldsGeneratedApiContractConformanceTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/SecretFieldsGeneratedApiContractConformanceTest.kt index 92cf42d370..7fa90768f6 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/SecretFieldsGeneratedApiContractConformanceTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/SecretFieldsGeneratedApiContractConformanceTest.kt @@ -1,6 +1,8 @@ package com.metaobjects.integration.kotlin.api.secretfields import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.PropertyNamingStrategies +import com.fasterxml.jackson.databind.PropertyNamingStrategy import com.metaobjects.integration.kotlin.api.ApiContractAssertions import com.metaobjects.integration.kotlin.api.ApiContractScenarioLoader import com.metaobjects.integration.kotlin.api.ApiContractScenarios.ApiScenario @@ -8,6 +10,7 @@ import com.metaobjects.integration.kotlin.api.secretfields.generated.GeneratedSe import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments @@ -15,6 +18,9 @@ import org.junit.jupiter.params.provider.MethodSource import java.nio.charset.StandardCharsets import java.nio.file.Files import java.util.stream.Stream +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue /** * #484 secret-fields api-contract conformance, Kotlin GENERATED-controller lane: a `@formExclude` or @@ -37,6 +43,103 @@ internal class SecretFieldsGeneratedApiContractConformanceTest { } } + /** + * A credential is never returned whatever the host mapper's property naming strategy: under `SNAKE_CASE` the + * key is `pin_hash`, under `KEBAB_CASE` `pin-hash`, and the generated controller reads that key from the + * mapper's own contract rather than spelling it `pinHash`. Drives the entity's list and get-by-id and the + * inheriting projection's. + */ + @ParameterizedTest(name = "naming={0}") + @MethodSource("namingStrategies") + fun `a credential is never returned under any naming strategy`(label: String, naming: PropertyNamingStrategy?) { + val corpus = ApiContractScenarioLoader.findCorpusRoot() + val genDir = Files.createTempDirectory("secret-fields-naming-$label") + GeneratedSecretFieldsControllerHarness(corpus, genDir, SEED, naming).use { harness -> + harness.reset() + for (path in listOf("/api/accounts", "/api/accounts/1", "/api/account_views", "/api/account_views/1")) { + val res = harness.exchange("GET", path, null) + assertEquals(200, res.status, "$label $path: ${res.body}") + assertTrue("Ada Lovelace" in res.body, "$label $path: ${res.body}") + for (secret in listOf("pin-hash-1", "pin-hash-2")) { + assertFalse(secret in res.body, "$label $path leaked the credential: ${res.body}") + } + } + // @formExclude alone still returns the field, under the strategy's own key. + val tokenKey = (naming as? PropertyNamingStrategies.NamingBase)?.translate("tokenHash") ?: "tokenHash" + val one = harness.exchange("GET", "/api/accounts/1", null).body + assertTrue("\"$tokenKey\":\"token-hash-1\"" in one, "$label: tokenHash must still be returned as $tokenKey: $one") + } + } + + /** Renames the credential's JSON key to one that does not spell its property name at all. */ + abstract class RenameCredentialMixin { + @com.fasterxml.jackson.annotation.JsonProperty("secret") + abstract fun getPinHash(): String? + } + + /** + * A credential is never returned when the host mapper renames it with a mixin to a key that does not normalise + * to the property name (`secret`): only the mapper's own contract reveals the key. Oracle: the seeded `pinHash` + * values from `seed.json`; a helper that removed the key spelled `pinHash` would return them under `secret`. + */ + @Test + fun `a credential renamed by a mixin is never returned`() { + val genDir = Files.createTempDirectory("secret-fields-mixin") + GeneratedSecretFieldsControllerHarness( + ApiContractScenarioLoader.findCorpusRoot(), genDir, SEED, null, + ) { mapper, data -> mapper.addMixIn(data, RenameCredentialMixin::class.java) }.use { harness -> + harness.reset() + for (path in listOf("/api/accounts", "/api/accounts/1")) { + val res = harness.exchange("GET", path, null) + assertEquals(200, res.status, "$path: ${res.body}") + assertTrue("Ada Lovelace" in res.body, "$path: ${res.body}") + assertFalse("secret" in res.body, "$path kept the renamed credential key: ${res.body}") + for (row in SEED) { + assertFalse(row["pinHash"] as String in res.body, "$path leaked the credential: ${res.body}") + } + } + } + } + + /** + * Fail closed: when the mapper writes the row through a custom serializer, the credential's key cannot be read + * from its contract, so the response is refused (500) instead of returning the row. Oracle: the seeded `pinHash` + * values from `seed.json`, which this serializer writes out in full, so a helper that sent the row unstripped + * would return them. + */ + @Test + fun `a custom serializer for the row refuses the response`() { + val genDir = Files.createTempDirectory("secret-fields-custom-serializer") + GeneratedSecretFieldsControllerHarness( + ApiContractScenarioLoader.findCorpusRoot(), genDir, SEED, null, + ) { mapper, data -> + val module = com.fasterxml.jackson.databind.module.SimpleModule() + @Suppress("UNCHECKED_CAST") + module.addSerializer(data as Class, object : com.fasterxml.jackson.databind.JsonSerializer() { + override fun serialize( + value: Any, + gen: com.fasterxml.jackson.core.JsonGenerator, + provider: com.fasterxml.jackson.databind.SerializerProvider, + ) { + gen.writeStartObject() + gen.writeStringField("name", data.getMethod("getName").invoke(value) as String) + gen.writeStringField("pinHash", data.getMethod("getPinHash").invoke(value) as String) + gen.writeEndObject() + } + }) + mapper.registerModule(module) + }.use { harness -> + harness.reset() + for (path in listOf("/api/accounts", "/api/accounts/1")) { + val res = harness.exchange("GET", path, null) + assertEquals(500, res.status, "$path: ${res.body}") + for (row in SEED) { + assertFalse(row["pinHash"] as String in res.body, "$path leaked the credential: ${res.body}") + } + } + } + } + /** * The write side of #484, observed on the STORED row (the repository), not on the response: a seeded row's * `tokenHash` and `pinHash` are exactly as seeded after every forged create / PATCH / PUT / present-null, and @@ -80,6 +183,13 @@ internal class SecretFieldsGeneratedApiContractConformanceTest { if (::HARNESS.isInitialized) HARNESS.close() } + @JvmStatic + fun namingStrategies(): Stream = Stream.of( + Arguments.of("none", null), + Arguments.of("snake", PropertyNamingStrategies.SNAKE_CASE), + Arguments.of("kebab", PropertyNamingStrategies.KEBAB_CASE), + ) + @JvmStatic fun scenarios(): Stream { val corpus = ApiContractScenarioLoader.findCorpusRoot() diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/generated/GeneratedSecretFieldsControllerHarness.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/generated/GeneratedSecretFieldsControllerHarness.kt index f0751814ce..b9ccc7bd4f 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/generated/GeneratedSecretFieldsControllerHarness.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/generated/GeneratedSecretFieldsControllerHarness.kt @@ -1,6 +1,7 @@ package com.metaobjects.integration.kotlin.api.secretfields.generated import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.PropertyNamingStrategy import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.module.kotlin.registerKotlinModule @@ -28,12 +29,21 @@ import kotlin.io.path.readText /** * #484: host the GENERATED Kotlin Spring `AccountController` for the secret-fields corpus over real HTTP * (embedded Tomcat, in-memory H2). Same generate, compile, serve mechanism as the write-through harness. + * + * Beside the corpus model it loads [ACCOUNT_VIEW], a read-only projection whose `pinHash` extends + * `Account.pinHash`, and mounts its generated controller too, so the read-only path's credential + * redaction is driven over HTTP as well. [naming] is the host mapper's property naming strategy (what + * `spring.jackson.property-naming-strategy` sets), null for Jackson's default. [customize] is applied to the host + * mapper once the generated data class exists, with that class: it registers a mixin or serializer on it, as an + * adopter's own mapper configuration may. */ @OptIn(org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi::class) class GeneratedSecretFieldsControllerHarness( corpusRoot: Path, genDir: Path, private val rows: List>, + naming: PropertyNamingStrategy? = null, + customize: ((ObjectMapper, Class<*>) -> Unit)? = null, ) : AutoCloseable { private val mapper: ObjectMapper = ObjectMapper() @@ -43,17 +53,22 @@ class GeneratedSecretFieldsControllerHarness( .disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModule(JavaTimeModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .apply { if (naming != null) propertyNamingStrategy = naming } private val controllerClass: Class<*> + private val viewControllerClass: Class<*> private val accountTable: Table - private val dbSeq = AtomicInteger(0) private var host: TomcatHost? = null private var db: Database? = null init { val metaJson = corpusRoot.resolve("secret-fields/meta.json") val uri: URI = URIHelper.toURI("model:file:" + metaJson.toAbsolutePath().toString().replace('\\', '/')) - val loader = loadUris("api-contract-secret-fields-generated", listOf(uri)) + Files.createDirectories(genDir) + val viewModel = genDir.resolve("account-view.json") + Files.writeString(viewModel, ACCOUNT_VIEW) + val viewUri: URI = URIHelper.toURI("model:file:" + viewModel.toAbsolutePath().toString().replace('\\', '/')) + val loader = loadUris("api-contract-secret-fields-generated", listOf(uri, viewUri)) // ADR-0058 — this corpus's committed .metaobjects/config.json (at corpusRoot, // fixtures/api-contract-conformance/) declares naming.columns: literal; every field // here declares no @column, so the generated columns and the runtime's reads of them @@ -101,7 +116,9 @@ class GeneratedSecretFieldsControllerHarness( "generated Kotlin failed to compile:\n${result.messages}" } + customize?.invoke(mapper, result.classLoader.loadClass("$ENTITY_PKG.Account")) this.controllerClass = result.classLoader.loadClass(CONTROLLER_FQCN) + this.viewControllerClass = result.classLoader.loadClass(VIEW_CONTROLLER_FQCN) this.accountTable = result.classLoader.loadClass(ACCOUNT_TABLE_FQCN).getDeclaredField("INSTANCE").get(null) as Table } @@ -117,13 +134,17 @@ class GeneratedSecretFieldsControllerHarness( for (r in rows) { exec("INSERT INTO accounts (\"name\", \"tokenHash\", \"pinHash\", \"role\") VALUES (${sqlStr(r["name"])}, ${sqlStr(r["tokenHash"])}, ${sqlStr(r["pinHash"])}, ${sqlStr(r["role"])})") } + // Exposed cannot create a view; the projection reads this one. + exec("CREATE VIEW v_account AS SELECT id, \"name\", \"pinHash\" FROM accounts") } val controller = controllerClass .getDeclaredConstructor(ObjectMapper::class.java, jakarta.validation.Validator::class.java) .newInstance(mapper, jakarta.validation.Validation.buildDefaultValidatorFactory().validator) + val viewCtor = viewControllerClass.declaredConstructors.single() + val viewController = if (viewCtor.parameterCount == 0) viewCtor.newInstance() else viewCtor.newInstance(mapper) host?.close() - host = TomcatHost.start(mapper, controller) + host = TomcatHost.start(mapper, controller, viewController) } /** The stored rows as the repository sees them (raw SQL, so the generated HTTP boundary is bypassed). */ @@ -158,6 +179,22 @@ class GeneratedSecretFieldsControllerHarness( const val ENTITY_PKG = "acme.secrets" const val CONTROLLER_FQCN = "$ENTITY_PKG.AccountController" const val ACCOUNT_TABLE_FQCN = "$ENTITY_PKG.AccountTable" + /** JVM-wide: a named in-memory H2 outlives its harness (DB_CLOSE_DELAY=-1), so names never repeat. */ + val dbSeq = AtomicInteger(0) + const val VIEW_CONTROLLER_FQCN = "$ENTITY_PKG.AccountViewController" + + /** A view-backed projection of `Account` that inherits the credential. */ + val ACCOUNT_VIEW = """ + { "metadata.root": { "package": "acme::secrets", "children": [ + { "object.projection": { "name": "AccountView", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_account" } }, + { "field.long": { "name": "id", "extends": "Account.id" } }, + { "field.string": { "name": "name", "extends": "Account.name" } }, + { "field.string": { "name": "pinHash", "extends": "Account.pinHash" } }, + { "identity.primary": { "name": "id", "extends": "Account.id" } } + ] } } + ] } } + """.trimIndent() fun sqlStr(v: Any?): String = "'" + (v as String).replace("'", "''") + "'" } diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/SecretFieldsGeneratedApiContractConformanceTest.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/SecretFieldsGeneratedApiContractConformanceTest.java index b8200e5b7e..94648f419b 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/SecretFieldsGeneratedApiContractConformanceTest.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/SecretFieldsGeneratedApiContractConformanceTest.java @@ -23,6 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * #484 — the Java GENERATED-controller lane for the {@code secret-fields} api-contract @@ -105,6 +106,118 @@ void projectionInheritingACredentialNeverReturnsIt() throws Exception { assertFalse(row.containsKey("pinHash"), one.body()); } + static Stream namingStrategies() { + return Stream.of( + Arguments.of("none", null), + Arguments.of("snake", com.fasterxml.jackson.databind.PropertyNamingStrategies.SNAKE_CASE), + Arguments.of("kebab", com.fasterxml.jackson.databind.PropertyNamingStrategies.KEBAB_CASE)); + } + + /** + * A credential is never returned whatever the host mapper's property naming strategy: under + * {@code SNAKE_CASE} the key is {@code pin_hash}, under {@code KEBAB_CASE} {@code pin-hash}, and + * the generated controller reads that key from the mapper's own contract rather than spelling it + * {@code pinHash}. Drives the entity's list and get-by-id and the inheriting projection's. + */ + @ParameterizedTest(name = "naming={0}") + @MethodSource("namingStrategies") + void credentialIsNeverReturnedUnderAnyNamingStrategy( + String label, com.fasterxml.jackson.databind.PropertyNamingStrategy naming) throws Exception { + Path genDir = Files.createTempDirectory("secret-fields-naming-" + label); + try (GeneratedAccountControllerHarness harness = + new GeneratedAccountControllerHarness(ROOT, CONFIG_ROOT, genDir, seedRows(), naming)) { + harness.reset(); + for (String path : List.of("/api/accounts", "/api/accounts/1", "/api/account_views", "/api/account_views/1")) { + GeneratedAccountControllerHarness.Response res = harness.exchange("GET", path, null); + assertEquals(200, res.status(), label + " " + path + ": " + res.body()); + assertTrue(res.body().contains("Ada Lovelace"), label + " " + path + ": " + res.body()); + assertFalse(res.body().contains("pin-hash-1"), label + " " + path + " leaked the credential: " + res.body()); + assertFalse(res.body().contains("pin-hash-2"), label + " " + path + " leaked the credential: " + res.body()); + } + // @formExclude alone still returns the field, under the strategy's own key. + String tokenKey = naming == null ? "tokenHash" + : ((com.fasterxml.jackson.databind.PropertyNamingStrategies.NamingBase) naming).translate("tokenHash"); + assertTrue(harness.exchange("GET", "/api/accounts/1", null).body().contains("\"" + tokenKey + "\":\"token-hash-1\""), + label + ": tokenHash must still be returned as " + tokenKey); + } + } + + /** Renames the credential's JSON key to one that does not spell its field name at all. */ + abstract static class RenameCredentialMixin { + @com.fasterxml.jackson.annotation.JsonProperty("secret") + abstract String pinHash(); + } + + /** + * A credential is never returned when the host mapper renames it with a mixin to a key that does + * not normalise to the field name ({@code secret}): only the mapper's own contract reveals the key. + * Oracle: the seeded {@code pinHash} values from {@code seed.json}; a helper that removed the key + * spelled {@code pinHash} would return them under {@code secret}. + */ + @Test + void credentialRenamedByAMixinIsNeverReturned() throws Exception { + Path genDir = Files.createTempDirectory("secret-fields-mixin"); + try (GeneratedAccountControllerHarness harness = new GeneratedAccountControllerHarness( + ROOT, CONFIG_ROOT, genDir, seedRows(), null, + (mapper, dto) -> mapper.addMixIn(dto, RenameCredentialMixin.class))) { + harness.reset(); + for (String path : List.of("/api/accounts", "/api/accounts/1")) { + GeneratedAccountControllerHarness.Response res = harness.exchange("GET", path, null); + assertEquals(200, res.status(), path + ": " + res.body()); + assertTrue(res.body().contains("Ada Lovelace"), path + ": " + res.body()); + assertFalse(res.body().contains("secret"), path + " kept the renamed credential key: " + res.body()); + for (Map row : seedRows()) { + assertFalse(res.body().contains((String) row.get("pinHash")), + path + " leaked the credential: " + res.body()); + } + } + } + } + + /** + * Fail closed: when the mapper writes the row through a custom serializer, the credential's key + * cannot be read from its contract, so the response is refused (500) instead of returning the row. + * Oracle: the seeded {@code pinHash} values from {@code seed.json}, which this serializer writes + * out in full, so a helper that sent the row unstripped would return them. + */ + @Test + @SuppressWarnings("unchecked") + void customSerializerForTheRowRefusesTheResponse() throws Exception { + Path genDir = Files.createTempDirectory("secret-fields-custom-serializer"); + try (GeneratedAccountControllerHarness harness = new GeneratedAccountControllerHarness( + ROOT, CONFIG_ROOT, genDir, seedRows(), null, + (mapper, dto) -> { + com.fasterxml.jackson.databind.module.SimpleModule module = + new com.fasterxml.jackson.databind.module.SimpleModule(); + module.addSerializer((Class) dto, new com.fasterxml.jackson.databind.JsonSerializer() { + @Override + public void serialize(Object value, com.fasterxml.jackson.core.JsonGenerator gen, + com.fasterxml.jackson.databind.SerializerProvider provider) + throws IOException { + try { + gen.writeStartObject(); + gen.writeStringField("name", (String) dto.getMethod("name").invoke(value)); + gen.writeStringField("pinHash", (String) dto.getMethod("pinHash").invoke(value)); + gen.writeEndObject(); + } catch (ReflectiveOperationException e) { + throw new IOException(e); + } + } + }); + mapper.registerModule(module); + })) { + harness.reset(); + for (String path : List.of("/api/accounts", "/api/accounts/1")) { + GeneratedAccountControllerHarness.Response res = harness.exchange("GET", path, null); + assertEquals(500, res.status(), path + ": " + res.body()); + for (Map row : seedRows()) { + assertFalse(res.body().contains((String) row.get("pinHash")), + path + " leaked the credential: " + res.body()); + } + } + } + } + /** * The stored rows, read from the repository seam: a seeded row still holds its seed * {@code tokenHash} and {@code pinHash} (neither was writable), and a row the scenario created diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAccountControllerHarness.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAccountControllerHarness.java index ca1991e87e..e056f325cd 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAccountControllerHarness.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAccountControllerHarness.java @@ -61,9 +61,12 @@ public final class GeneratedAccountControllerHarness implements AutoCloseable { ] } } """; - // Mirrors Spring Boot's default mapper. The generated request handling does not depend on it: - // it reads body keys off the raw JSON and the DTOs ignore unknown properties. - private final ObjectMapper mapper = new ObjectMapper() + // Mirrors Spring Boot's default mapper, plus the property naming strategy the host app may set + // (what spring.jackson.property-naming-strategy does). The generated request handling does not + // depend on it: it reads body keys off the raw JSON and the DTOs ignore unknown properties. + private final ObjectMapper mapper; + // Seeds the repository from the corpus's camelCase seed rows whatever the host's naming is. + private final ObjectMapper seedMapper = new ObjectMapper() .disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); private final URLClassLoader classLoader; private final Class dtoClass; @@ -84,7 +87,33 @@ public final class GeneratedAccountControllerHarness implements AutoCloseable { */ public GeneratedAccountControllerHarness(Path corpusRoot, Path configRoot, Path genDir, List> seedRows) throws Exception { + this(corpusRoot, configRoot, genDir, seedRows, null); + } + + /** + * @param naming the host mapper's property naming strategy, or null for Jackson's default (the + * field name as written) + */ + public GeneratedAccountControllerHarness(Path corpusRoot, Path configRoot, Path genDir, + List> seedRows, + com.fasterxml.jackson.databind.PropertyNamingStrategy naming) + throws Exception { + this(corpusRoot, configRoot, genDir, seedRows, naming, null); + } + + /** + * @param customize applied to the host mapper once the generated DTO class exists, with that class: + * registers a mixin or serializer on it, as an adopter's own mapper configuration may + */ + public GeneratedAccountControllerHarness(Path corpusRoot, Path configRoot, Path genDir, + List> seedRows, + com.fasterxml.jackson.databind.PropertyNamingStrategy naming, + java.util.function.BiConsumer> customize) + throws Exception { this.seedRows = seedRows; + ObjectMapper hostMapper = new ObjectMapper() + .disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + this.mapper = naming == null ? hostMapper : hostMapper.setPropertyNamingStrategy(naming); Path srcDir = genDir.resolve("src"); Path classesDir = genDir.resolve("classes"); Files.createDirectories(srcDir); @@ -115,6 +144,7 @@ public GeneratedAccountControllerHarness(Path corpusRoot, Path configRoot, Path this.classLoader = new URLClassLoader( new URL[]{ classesDir.toUri().toURL() }, getClass().getClassLoader()); this.dtoClass = classLoader.loadClass(ENTITY_PKG + ".AccountDto"); + if (customize != null) customize.accept(mapper, dtoClass); Class repoInterface = classLoader.loadClass(ENTITY_PKG + ".AccountRepository"); this.controllerCtor = classLoader.loadClass(ENTITY_PKG + ".AccountController") .getDeclaredConstructor(repoInterface, ObjectMapper.class, Validator.class); @@ -130,14 +160,14 @@ public GeneratedAccountControllerHarness(Path corpusRoot, Path configRoot, Path /** Re-seed for a scenario: a fresh repository, controller and Tomcat. */ public void reset() throws Exception { List dtos = new ArrayList<>(); - for (Map row : seedRows) dtos.add(mapper.convertValue(row, dtoClass)); + for (Map row : seedRows) dtos.add(seedMapper.convertValue(row, dtoClass)); this.repo = repoCtor.newInstance(dtos); Object controller = controllerCtor.newInstance(repo, mapper, validator); List viewDtos = new ArrayList<>(); for (Map row : seedRows) { Map view = new java.util.LinkedHashMap<>(); for (String col : List.of("id", "name", "pinHash")) view.put(col, row.get(col)); - viewDtos.add(mapper.convertValue(view, viewDtoClass)); + viewDtos.add(seedMapper.convertValue(view, viewDtoClass)); } Object viewRepo = viewRepoCtor.newInstance(viewDtos); Object viewController = viewControllerCtor.getParameterCount() == 1