Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
57cb9e4
Outline of new classes
n0900 Mar 6, 2026
c0305fd
Update SignatureElement
n0900 Mar 6, 2026
0352cce
Implement equality and hashcode
n0900 Mar 6, 2026
4e65d34
Add JwsCompact Serializer
n0900 Mar 6, 2026
04492ce
Add Serialnames etc
n0900 Mar 6, 2026
3318615
Remove unnecessary parameter
n0900 Mar 6, 2026
b02463f
Move to functions to companion object
n0900 Mar 6, 2026
b55e475
Add sealed class JWS serializer
n0900 Mar 9, 2026
a6ab6e7
Add partial JWS Header Class
n0900 Mar 11, 2026
ae0da32
Add quality-of-life functions
n0900 Mar 11, 2026
636d006
Add test cases
n0900 Mar 11, 2026
4489670
Use the fact that JwsCompact is serializable
n0900 Mar 11, 2026
aeeb230
Parse JwsHeader immediatly
n0900 Mar 12, 2026
421c7ae
Stricter invoke JwsCompact
n0900 Mar 12, 2026
dfb013a
Strict parse SignatureElement JwsHeader
n0900 Mar 12, 2026
74da761
Add replaceWith
n0900 Mar 12, 2026
5e6312c
More eager parsing
n0900 Mar 16, 2026
3cbb023
Remove registered Serializer from JwsCompact leaving intentional seri…
n0900 Mar 16, 2026
1f7c851
Use SerialNames
n0900 Mar 16, 2026
a14dd8f
Replace exceptionOrNull with shouldBeFailure
n0900 Mar 16, 2026
0697697
Add JwsHeader Documentation
n0900 Mar 16, 2026
3018134
Add Jws Documentation
n0900 Mar 16, 2026
a021c53
Add CHANGELOG entry
n0900 Mar 16, 2026
822848f
Add shape names to SerialNames
n0900 Mar 16, 2026
5a3254f
Remove deprectated .deserialize
n0900 Mar 16, 2026
c9d9468
Remove deprectated .serialize
n0900 Mar 16, 2026
762cace
Only parse valid base64url strings
n0900 Mar 16, 2026
6158d3d
Test JWS serializer more thoroughly
n0900 Mar 16, 2026
c34ecf3
Usability improvements
n0900 Mar 19, 2026
ebfedba
Convenience function
n0900 Mar 19, 2026
f20caa1
Make constructors internal
n0900 Mar 24, 2026
9674d76
Correctly de-/encode empty protected header
n0900 Mar 24, 2026
58ae28b
Add SerialNames Object
n0900 Mar 24, 2026
93fb7d3
Make constructors internal
n0900 Mar 24, 2026
60a1aeb
Add clarifying comments about bytearray encoding
n0900 Mar 24, 2026
1f147d5
Add clarifying comments about private header parameters
n0900 Mar 24, 2026
8a86ff8
Add typed JWS wrapper (#425)
n0900 Apr 14, 2026
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
# Changelog

## NEXT
* Rework JWS support around explicit compact, flattened, and general representations
* Add sealed `JWS` support with dedicated `JwsCompact`, `JwsFlattened`, `JwsGeneral`
* Add conversions between compact, flattened, and general JWS representations
* Represent protected and unprotected header fragments explicitly via `JwsHeader.Part`, merging them into a `JwsHeader` only when the combined header is valid
* Parse `JwsHeader.attestationJwt` and `JwsHeader.keyAttestation` as `JwsCompact` instead of raw strings
* Deprecate `JwsSigned` in favor of `JwsCompact`
* Typed payloads remain supported via `JwsTyped`

## 3.21.0 / Supreme 0.13.0
* Drop Apple X64 targets
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
package at.asitplus.signum.indispensable.josef

import at.asitplus.KmmResult
import at.asitplus.KmmResult.Companion.wrap
import at.asitplus.signum.indispensable.CryptoSignature
import at.asitplus.signum.indispensable.io.Base64UrlStrict
import at.asitplus.signum.indispensable.josef.io.joseCompliantSerializer
import io.matthewnelson.encoding.core.Encoder.Companion.encodeToString
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.PolymorphicKind
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonEncoder
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive


/**
* Wrapper for all JWS formats.
*
* If [plainPayload] data structure is defined as part of the contact consider [JwsTyped]
*/
@Serializable(with = JWS.JwsSerializer::class)
sealed class JWS {
/**
* Raw payload bytes.
*
* JWS serializers and signature-input construction base64url-encode these bytes where required.
* Callers should not pre-encode the payload.
*/
abstract val plainPayload: ByteArray

fun <P> getPayload(serializer: KSerializer<P>, serialFormat: SerialFormat = joseCompliantSerializer): KmmResult<P> = runCatching {
when (serialFormat) {
is StringFormat -> serialFormat.decodeFromString(serializer, plainPayload.decodeToString())
is BinaryFormat -> serialFormat.decodeFromByteArray(serializer, plainPayload)
else -> throw NotImplementedError("Unknown serial format $serialFormat")
}
}.wrap()

/**
* Find correct serializer at compile time
*/
@Suppress("unused")
inline fun <reified P> getPayload(serialFormat: SerialFormat = joseCompliantSerializer): KmmResult<P> =
getPayload(serialFormat.serializersModule.serializer(), serialFormat)

object SerialNames {
const val PROTECTED = "protected"
const val HEADER = "header"
const val SIGNATURE = "signature"
const val SIGNATURES = "signatures"
const val PAYLOAD = "payload"

/* Shapes */
const val COMPACT = "compact"
const val FLATTENED = "flattened"
const val GENERAL = "general"

}

companion object {
fun getSignature(algorithm: JwsAlgorithm, plainSignature: ByteArray): CryptoSignature.RawByteEncodable =
when (algorithm) {
is JwsAlgorithm.Signature.EC -> CryptoSignature.EC.fromRawBytes(algorithm.ecCurve, plainSignature)
is JwsAlgorithm.Signature.RSA -> CryptoSignature.RSA(plainSignature)
else -> throw SerializationException("Unsupported algorithm for JWS signature element: $algorithm")
}

fun getEncodedProtectedHeader(protectedHeader: ByteArray?): String =
protectedHeader?.encodeToString(Base64UrlStrict).orEmpty()

/**
* Builds the RFC 7515 signing input from raw protected-header bytes and raw payload bytes.
*
* [payload] must be plain payload bytes; this helper base64url-encodes it internally.
*/
fun getSignatureInput(protectedHeader: ByteArray?, payload: ByteArray) =
"${getEncodedProtectedHeader(protectedHeader)}.${payload.encodeToString(Base64UrlStrict)}".encodeToByteArray()
}

object JwsSerializer: KSerializer<JWS> {
@OptIn(InternalSerializationApi::class)
override val descriptor: SerialDescriptor = buildSerialDescriptor("JWS", PolymorphicKind.SEALED) {
element(SerialNames.COMPACT, JwsCompactStringSerializer.descriptor)
element(SerialNames.FLATTENED, JwsFlattened.serializer().descriptor)
element(SerialNames.GENERAL, JwsGeneral.serializer().descriptor)
}

override fun serialize(
encoder: Encoder,
value: JWS
) {
require(encoder is JsonEncoder) { "JWS serialization requires a JsonDecoder" }
when (value) {
is JwsCompact -> encoder.encodeSerializableValue(JwsCompactStringSerializer, value)
is JwsFlattened -> encoder.encodeSerializableValue(JwsFlattened.serializer(), value)
is JwsGeneral -> encoder.encodeSerializableValue(JwsGeneral.serializer(), value)
}
}

override fun deserialize(decoder: Decoder): JWS {
require(decoder is JsonDecoder) { "JWS deserialization requires a JsonDecoder" }
val jsonElement = decoder.decodeJsonElement()

return when (jsonElement) {
is JsonPrimitive -> decoder.json.decodeFromJsonElement(JwsCompactStringSerializer, jsonElement)
is JsonObject -> {
val hasGeneralSignatures = SerialNames.SIGNATURES in jsonElement
val hasFlattenedSignature = SerialNames.SIGNATURE in jsonElement

when {
hasGeneralSignatures && hasFlattenedSignature ->
throw SerializationException(
"Invalid JWS JSON serialization: object must not contain both " +
"'${SerialNames.SIGNATURE}' and '${SerialNames.SIGNATURES}'"
)

hasGeneralSignatures ->
decoder.json.decodeFromJsonElement(JwsGeneral.serializer(), jsonElement)

hasFlattenedSignature ->
decoder.json.decodeFromJsonElement(JwsFlattened.serializer(), jsonElement)

else ->
throw SerializationException(
"Invalid JWS JSON serialization: object must contain " +
"'${SerialNames.SIGNATURE}' or '${SerialNames.SIGNATURES}'"
)
}
}

else -> throw SerializationException(
"Invalid JWS JSON serialization: expected a compact string or JSON object"
)
}
}
}
}

internal fun JsonObject?.strictUnion(other: JsonObject?): JsonObject {
if (this == null) return other ?: JsonObject(emptyMap())
if (other == null) return this

val duplicates = this.keys intersect other.keys
require(duplicates.isEmpty()) {
"Duplicate keys: ${duplicates.joinToString()}"
}

return JsonObject(this + other)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package at.asitplus.signum.indispensable.josef

import at.asitplus.KmmResult
import at.asitplus.catching
import at.asitplus.signum.indispensable.io.Base64UrlStrict
import io.matthewnelson.encoding.core.Decoder.Companion.decodeToByteArray
import io.matthewnelson.encoding.core.Encoder.Companion.encodeToString
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.Transient
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder

/**
* Implements compact serialization as defined in [RFC 7515](https://datatracker.ietf.org/doc/html/rfc7515)
*
* Serialized output is of the form
* BASE64URL(UTF8(HEADER)).BASE64URL(PAYLOAD).BASE64URL(SIGNATURE)
*
* This class does not support an unprotected header field!
*
* [JwsCompact] is intentionally *not* annotated with `@Serializable`: its JSON representation is only the compact
* JWS string, not a JSON object. Use [JwsCompactStringSerializer] explicitly when you want that string form inside
* a JSON document.
*
* For a standalone compact JWS string, use [toString] and [JwsCompact.invoke].
*
* If [plainPayload] data structure is defined as part of the contact consider [JwsCompactTyped]
*/
@ConsistentCopyVisibility
data class JwsCompact internal constructor(
val plainProtectedHeader: ByteArray,
override val plainPayload: ByteArray,
val plainSignature: ByteArray,
) : JWS() {

@Transient
val jwsHeader = JwsHeader.fromParts(plainProtectedHeader, null)

@Transient
val signature = getSignature(jwsHeader.algorithm, plainSignature)

@Transient
val signatureInput = getSignatureInput(plainProtectedHeader, plainPayload)

override fun toString() = "${signatureInput.decodeToString()}.${plainSignature.encodeToString(Base64UrlStrict)}"

override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false

other as JwsCompact

if (!plainProtectedHeader.contentEquals(other.plainProtectedHeader)) return false
if (!plainPayload.contentEquals(other.plainPayload)) return false
if (!plainSignature.contentEquals(other.plainSignature)) return false

return true
}

override fun hashCode(): Int {
var result = plainProtectedHeader.contentHashCode()
result = 31 * result + plainPayload.contentHashCode()
result = 31 * result + plainSignature.contentHashCode()
return result
}

companion object {

/**
* Build a [at.asitplus.signum.indispensable.josef.JwsCompact] received as string
* and immediately resolve the payload
*/
inline fun <reified P> parse(base64UrlString: String): KmmResult<Pair<JwsCompact, P>> = catching{
val jws = JwsCompact(base64UrlString)
val payload = jws.getPayload<P>().getOrThrow()
jws to payload
}

/**
* Build a [at.asitplus.signum.indispensable.josef.JwsCompact] received as string
*/
operator fun invoke(
base64UrlString: String,
): JwsCompact {
require(!base64UrlString.contains("=")) { "Trailing = are not supported. See RFC 7515" }
val parts = base64UrlString.split('.')

if (parts.size != 3) {
throw SerializationException(
"Invalid JWS compact serialization: expected 3 parts, got ${parts.size}"
)
}

return try {
JwsCompact(
plainProtectedHeader = parts[0].decodeToByteArray(Base64UrlStrict),
plainPayload = parts[1].decodeToByteArray(Base64UrlStrict),
plainSignature = parts[2].decodeToByteArray(Base64UrlStrict),
)
} catch (e: Exception) {
throw SerializationException("Invalid base64url content in JWS compact serialization", e)
}
}

/**
* Build a new [at.asitplus.signum.indispensable.josef.JwsCompact]
* from components and immediately sign the correct representation.
*
* [payload] must be the plain payload bytes. Do not base64url-encode it before calling this overload;
* compact serialization and signing input construction apply base64url encoding internally.
*/
suspend operator fun invoke(
protectedHeader: JwsHeader,
payload: ByteArray,
signer: suspend (ByteArray) -> ByteArray
): JwsCompact {
val plainProtectedHeader = JwsProtectedHeaderSerializer.encodeToByteArray(protectedHeader.toPart())
return JwsCompact(
plainProtectedHeader = plainProtectedHeader,
plainPayload = payload,
plainSignature = signer(getSignatureInput(plainProtectedHeader, payload)),
)
}
}
}

/**
* Serializes a [JwsCompact] as its compact JWS string form inside JSON.
*
* This serializer must be opted into explicitly to avoid accidentally treating [JwsCompact] as a JSON object.
*/
object JwsCompactStringSerializer : KSerializer<JwsCompact> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("JwsCompact", PrimitiveKind.STRING)

override fun serialize(encoder: Encoder, value: JwsCompact) = encoder.encodeString(value.toString())

override fun deserialize(decoder: Decoder): JwsCompact = JwsCompact(decoder.decodeString())
}

/**
* Converts compact serialization to the equivalent flattened JSON form.
*
* The protected header bytes are preserved and the unprotected header is absent, because compact serialization does
* not support unprotected header parameters.
*/
fun JwsCompact.toJwsFlattened(): JwsFlattened = JwsFlattened(
plainProtectedHeader = plainProtectedHeader,
unprotectedHeader = null,
plainPayload = plainPayload,
plainSignature = plainSignature,
)
Loading
Loading