-
Notifications
You must be signed in to change notification settings - Fork 18
Full implementation of all three JWS serialization shapes #419
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
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 c0305fd
Update SignatureElement
n0900 0352cce
Implement equality and hashcode
n0900 4e65d34
Add JwsCompact Serializer
n0900 04492ce
Add Serialnames etc
n0900 3318615
Remove unnecessary parameter
n0900 b02463f
Move to functions to companion object
n0900 b55e475
Add sealed class JWS serializer
n0900 a6ab6e7
Add partial JWS Header Class
n0900 ae0da32
Add quality-of-life functions
n0900 636d006
Add test cases
n0900 4489670
Use the fact that JwsCompact is serializable
n0900 aeeb230
Parse JwsHeader immediatly
n0900 421c7ae
Stricter invoke JwsCompact
n0900 dfb013a
Strict parse SignatureElement JwsHeader
n0900 74da761
Add replaceWith
n0900 5e6312c
More eager parsing
n0900 3cbb023
Remove registered Serializer from JwsCompact leaving intentional seri…
n0900 1f7c851
Use SerialNames
n0900 a14dd8f
Replace exceptionOrNull with shouldBeFailure
n0900 0697697
Add JwsHeader Documentation
n0900 3018134
Add Jws Documentation
n0900 a021c53
Add CHANGELOG entry
n0900 822848f
Add shape names to SerialNames
n0900 5a3254f
Remove deprectated .deserialize
n0900 c9d9468
Remove deprectated .serialize
n0900 762cace
Only parse valid base64url strings
n0900 6158d3d
Test JWS serializer more thoroughly
n0900 c34ecf3
Usability improvements
n0900 ebfedba
Convenience function
n0900 f20caa1
Make constructors internal
n0900 9674d76
Correctly de-/encode empty protected header
n0900 58ae28b
Add SerialNames Object
n0900 93fb7d3
Make constructors internal
n0900 60a1aeb
Add clarifying comments about bytearray encoding
n0900 1f147d5
Add clarifying comments about private header parameters
n0900 8a86ff8
Add typed JWS wrapper (#425)
n0900 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
154 changes: 154 additions & 0 deletions
154
indispensable-josef/src/commonMain/kotlin/at/asitplus/signum/indispensable/josef/Jws.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } | ||
155 changes: 155 additions & 0 deletions
155
...pensable-josef/src/commonMain/kotlin/at/asitplus/signum/indispensable/josef/JwsCompact.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
n0900 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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), | ||
JesusMcCloud marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
n0900 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } 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()) | ||
nodh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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( | ||
nodh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| plainProtectedHeader = plainProtectedHeader, | ||
| unprotectedHeader = null, | ||
| plainPayload = plainPayload, | ||
| plainSignature = plainSignature, | ||
| ) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.