Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions fixtures/api-contract-conformance/secret-fields/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,13 +272,82 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase<MetaOb
/**
* #484: a credential is never returned. The shared data class keeps its declared types, so the key is
* dropped from the serialized tree at the HTTP boundary (absent, not null), through the same mapper
* (and so the same wire annotations) the response would use.
* (and so the same wire annotations) the response would use. [strips] says whether this file needs the
* shared `stripCredentials` helper at all (its own [creds], or an M:N target's).
*/
private fun appendRedactor(sb: StringBuilder, shortName: String, creds: Collection<String>) {
private fun appendRedactor(sb: StringBuilder, shortName: String, creds: Collection<String>, 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<com.fasterxml.jackson.databind.node.ObjectNode>(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<Triple<ObjectMapper, Class<*>, List<String>>, Set<String>>()
|
|/**
| * 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<com.fasterxml.jackson.databind.node.ObjectNode>(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<out String>): Set<String> {
| 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<String>()
| 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<String>, 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<MetaField<*>>): List<String> =
Expand Down Expand Up @@ -350,7 +419,8 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase<MetaOb
// #484: credential fields are removed from every response at the HTTP boundary.
val creds = credentialNames(entity.metaFields)
val m2mNavsForMapper = KotlinM2mSupport.resolve(entity, loader, providedEnums)
val needsMapper = hasPatchFields || rejectUnknown || creds.isNotEmpty() || m2mNavsForMapper.any { it.targetCredentialFields.isNotEmpty() }
val strips = creds.isNotEmpty() || m2mNavsForMapper.any { it.targetCredentialFields.isNotEmpty() }
val needsMapper = hasPatchFields || rejectUnknown || strips

// #203/ADR-0045: @autoSet columns are stamped by the generated controller, not bound from
// the caller. insert stamps BOTH onCreate+onUpdate (a fresh row's updatedAt == createdAt —
Expand Down Expand Up @@ -516,7 +586,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase<MetaOb
emitFilterPipeline(this, shortName, readObj, allowlistName, scalarFields)

appendRowToMapper(this, shortName, entity, readObj)
appendRedactor(this, shortName, creds)
appendRedactor(this, shortName, creds, strips)

append("/**\n")
append(" * GENERATED — REST controller for ${shortName} entity. Implements the cross-port API contract.\n")
Expand Down Expand Up @@ -932,8 +1002,9 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase<MetaOb
// #484: credential columns (base or subtype-only) are removed from every response; the controller
// then needs the ObjectMapper even when no subtype has a settable column.
val creds = credentialNames(markFields)
val needsMapper = anyPatchFields || rejectUnknown || creds.isNotEmpty() ||
val strips = creds.isNotEmpty() ||
(listOf(baseM2mNavs) + plan.subtypes.map { subtypeM2mNavs(it) }).any { navs -> navs.any { it.targetCredentialFields.isNotEmpty() } }
val needsMapper = anyPatchFields || rejectUnknown || strips

val src = buildString {
if (pkg.isNotEmpty()) append("package $pkg\n\n")
Expand Down Expand Up @@ -1062,7 +1133,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase<MetaOb
append("private fun rowTo${shortName}(row: ResultRow): $shortName = $shortName(\n")
for (field in scalarFields) append(" ${field.name} = row[$table.${field.name}],\n")
append(")\n\n")
appendRedactor(this, shortName, creds)
appendRedactor(this, shortName, creds, strips)

append("/**\n")
append(" * GENERATED — TPH discriminator-base controller for $shortName (polymorphic + per-subtype CRUD).\n")
Expand Down Expand Up @@ -2054,14 +2125,14 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase<MetaOb
private fun appendM2mRows(out: StringBuilder, nav: KotlinM2mSupport.M2mNav, targetType: String, query: String) {
val creds = nav.targetCredentialFields
out.append(" val rows${if (creds.isNotEmpty()) ": List<Any>" else ""} = $query.map { row ->\n")
if (creds.isNotEmpty()) out.append(" objectMapper.valueToTree<com.fasterxml.jackson.databind.node.ObjectNode>(\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")
Expand Down Expand Up @@ -2342,7 +2413,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase<MetaOb
appendSortSurface(this, shortName, entity, sortFields)
emitFilterPipeline(this, shortName, readObj, allowlistName, scalarFields)
appendRowToMapper(this, shortName, entity, readObj)
appendRedactor(this, shortName, creds)
appendRedactor(this, shortName, creds, creds.isNotEmpty())

append("/**\n")
append(" * GENERATED — READ-ONLY REST controller for the ${shortName} $noun.\n")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ class KotlinReportCredentialTest {
fun `a report over a credential dimension omits it from its rows and export`() {
val files = generate()
val controller = file(files, "AccountsByPinController.kt")
assertTrue("remove(listOf(\"pinHash\"))" in controller, controller)
assertTrue("stripCredentials(mapper, row, \"pinHash\")" in controller, controller)
assertTrue("redactAccountsByPin(objectMapper, rowToAccountsByPin(it))" in controller, controller)
assertTrue("rows.map { redactAccountsByPin(objectMapper, it) }" in controller, controller)
val export = file(files, "AccountsByPinExport.kt")
Expand All @@ -82,7 +82,7 @@ class KotlinReportCredentialTest {
fun `a min measure over a credential is a credential too`() {
val files = generate()
val controller = file(files, "AccountPinRangeController.kt")
assertTrue("remove(listOf(\"firstPin\"))" in controller, controller)
assertTrue("stripCredentials(mapper, row, \"firstPin\")" in controller, controller)
val export = file(files, "AccountPinRangeExport.kt")
assertFalse("firstPin" in export, export)
assertTrue("\"name\"" in export, export)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class KotlinSecretFieldsTest {
@Test
fun `only the credential is redacted on read and the entity keeps its types`() {
val (controller, entity) = controllerAndEntity(marked = true)
assertTrue("remove(listOf(\"pinHash\"))" in controller, controller)
assertTrue("stripCredentials(mapper, row, \"pinHash\")" in controller, controller)
assertFalse("tokenHash\"" in controller.substringAfter("private fun redactAccount").substringBefore("\n\n"), controller)
assertTrue("redactAccount(objectMapper, rowToAccount(it))" in controller, controller)
assertTrue("tokenHash = row[AccountTable.tokenHash]," in controller, controller)
Expand All @@ -58,7 +58,7 @@ class KotlinSecretFieldsTest {
assertTrue(Regex("val pinHash: String[,\\s)]").containsMatchIn(entity), entity)
assertFalse("val pinHash: String?" in entity, entity)
assertFalse("JsonInclude" in entity, entity)
assertTrue("remove(listOf(\"pinHash\"))" in controller, controller)
assertTrue("stripCredentials(mapper, row, \"pinHash\")" in controller, controller)
}

/** A TPH base whose subtypes share `token` and `memo`: plain on AThing (first in subtype order), marked on BThing. */
Expand Down Expand Up @@ -88,7 +88,7 @@ class KotlinSecretFieldsTest {
val loader = loadString("secret-fields-tph-shared", tphSharedColumn)
KotlinSpringControllerGenerator().apply { setArgs(mapOf("outputDir" to out.toString())) }.execute(loader)
val controller = Files.readString(out.resolve("acme/secrets/ThingController.kt"))
assertTrue("remove(listOf(\"token\"))" in controller, controller)
assertTrue("stripCredentials(mapper, row, \"token\")" in controller, controller)
assertFalse("it[token] = dto.token" in controller, controller)
assertFalse("it[memo] = dto.memo" in controller, controller)
} finally {
Expand Down
Loading
Loading