-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerialization.kt
More file actions
228 lines (189 loc) · 8.4 KB
/
Serialization.kt
File metadata and controls
228 lines (189 loc) · 8.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*
* Copyright (c) 2023-2026 European Commission
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.europa.ec.eudi.openid4vci.internal
import com.nimbusds.jose.jwk.JWK
import com.nimbusds.jose.util.JSONObjectUtils
import com.nimbusds.jwt.JWTClaimsSet
import com.nimbusds.jwt.SignedJWT
import eu.europa.ec.eudi.openid4vci.*
import eu.europa.ec.eudi.openid4vci.ClaimPathElement.AllArrayElements
import eu.europa.ec.eudi.openid4vci.ClaimPathElement.ArrayElement
import kotlinx.serialization.*
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
import kotlinx.serialization.json.*
import java.net.URI
import java.net.URL
import java.security.cert.X509Certificate
import java.time.Instant
import java.util.*
internal val JsonSupport: Json = Json {
ignoreUnknownKeys = true
prettyPrint = true
}
internal object LocaleSerializer : KSerializer<Locale> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Locale", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): Locale =
Locale.forLanguageTag(decoder.decodeString())
override fun serialize(encoder: Encoder, value: Locale) =
encoder.encodeString(value.toString())
}
@OptIn(ExperimentalSerializationApi::class)
internal object ProofSerializer : KSerializer<Proof> {
@Serializable
data class ProofJson(
@SerialName("proof_type") val proofType: String,
@SerialName("jwt") val jwt: String? = null,
@SerialName("di_vp") val diVp: String? = null,
@SerialName("attestation") val attestation: String? = null,
)
private val internal = serializer<ProofJson>()
override val descriptor: SerialDescriptor = SerialDescriptor("Proof", internal.descriptor)
override fun deserialize(decoder: Decoder): Proof {
val deserialized = internal.deserialize(decoder)
return when (deserialized.proofType) {
ProofType.JWT.toString().lowercase() -> {
deserialized.jwt?.let {
Proof.Jwt(SignedJWT.parse(deserialized.jwt))
} ?: error("Invalid JWT proof: missing 'jwt' attribute.")
}
else -> error("Unsupported proof type: ${deserialized.proofType}")
}
}
override fun serialize(encoder: Encoder, value: Proof) {
when (value) {
is Proof.Jwt -> internal.serialize(
encoder,
ProofJson(
proofType = ProofType.JWT.toString().lowercase(),
jwt = value.jwt.serialize(),
),
)
is Proof.DiVp -> internal.serialize(
encoder,
ProofJson(
proofType = ProofType.DI_VP.toString().lowercase(),
jwt = value.diVp,
),
)
is Proof.Attestation -> internal.serialize(
encoder,
ProofJson(
proofType = ProofType.ATTESTATION.toString().lowercase(),
attestation = value.keyAttestation.value,
),
)
}
}
}
@OptIn(ExperimentalSerializationApi::class)
internal object GrantedAuthorizationDetailsSerializer :
KSerializer<Map<CredentialConfigurationIdentifier, List<CredentialIdentifier>>> {
private const val OPENID_CREDENTIAL: String = "openid_credential"
@Serializable
data class AuthorizationDetailJson(
@SerialName("type") @Required val type: String,
@SerialName("credential_configuration_id") val credentialConfigurationId: String,
@SerialName("credential_identifiers") val credentialIdentifiers: List<String> = emptyList(),
) {
init {
require(type == OPENID_CREDENTIAL) { "type must be $OPENID_CREDENTIAL" }
}
}
private fun authDetails(
credentialConfigurationId: CredentialConfigurationIdentifier,
credentialIdentifiers: List<CredentialIdentifier>,
): AuthorizationDetailJson =
AuthorizationDetailJson(
type = OPENID_CREDENTIAL,
credentialConfigurationId = credentialConfigurationId.value,
credentialIdentifiers = credentialIdentifiers.map(CredentialIdentifier::value),
)
private val internal = serializer<List<AuthorizationDetailJson>>()
override val descriptor: SerialDescriptor = SerialDescriptor("GrantedAuthorizationDetails", internal.descriptor)
override fun deserialize(decoder: Decoder): Map<CredentialConfigurationIdentifier, List<CredentialIdentifier>> {
val deserialized = internal.deserialize(decoder)
return deserialized.associate { authDetails ->
val credentialConfigurationId = CredentialConfigurationIdentifier(authDetails.credentialConfigurationId)
val credentialIdentifiers = authDetails.credentialIdentifiers.map { CredentialIdentifier(it) }
credentialConfigurationId to credentialIdentifiers
}
}
override fun serialize(
encoder: Encoder,
value: Map<CredentialConfigurationIdentifier, List<CredentialIdentifier>>,
) {
val authorizationDetailsList = value.entries.map { (cfgId, credIds) -> authDetails(cfgId, credIds) }
internal.serialize(encoder, authorizationDetailsList)
}
}
/**
* Serializer for [ClaimPath]
*/
internal object ClaimPathSerializer : KSerializer<ClaimPath> {
private fun ClaimPath.toJson(): JsonArray = JsonArray(value.map { it.toJson() })
private fun ClaimPathElement.toJson(): JsonPrimitive = when (this) {
is ClaimPathElement.Claim -> JsonPrimitive(name)
is ArrayElement -> JsonPrimitive(index)
AllArrayElements -> JsonNull
}
private val arraySerializer = serializer<JsonArray>()
override val descriptor: SerialDescriptor = arraySerializer.descriptor
override fun serialize(encoder: Encoder, value: ClaimPath) {
val array = value.toJson()
arraySerializer.serialize(encoder, array)
}
override fun deserialize(decoder: Decoder): ClaimPath {
val array = arraySerializer.deserialize(decoder)
return array.asClaimPath()
}
}
object NumericInstantSerializer : KSerializer<Instant> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("NumericInstant", PrimitiveKind.LONG)
override fun serialize(encoder: Encoder, value: Instant) {
encoder.encodeLong(value.epochSecond)
}
override fun deserialize(decoder: Decoder): Instant {
return Instant.ofEpochSecond(decoder.decodeLong())
}
}
object JWTClaimsSetSerializer : KSerializer<JWTClaimsSet> {
private val objectSerializer = serializer<JsonObject>()
override val descriptor: SerialDescriptor = objectSerializer.descriptor
override fun serialize(encoder: Encoder, value: JWTClaimsSet) {
val claimsJsonObject = JsonSupport.decodeFromString<JsonObject>(JSONObjectUtils.toJSONString(value.toJSONObject()))
objectSerializer.serialize(encoder, claimsJsonObject)
}
override fun deserialize(decoder: Decoder): JWTClaimsSet {
val deserialized = objectSerializer.deserialize(decoder)
return JWTClaimsSet.parse(JsonSupport.encodeToString(deserialized))
}
}
fun JWK.asJsonElement(): JsonElement = Json.parseToJsonElement(this.toPublicJWK().toJSONString())
fun List<X509Certificate>.asJsonElement(): JsonArray = JsonArray(
this.map { Json.encodeToJsonElement(Base64.getEncoder().encodeToString(it.encoded)) },
)
object URLSerializer : KSerializer<URL> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URL", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: URL) {
encoder.encodeString(value.toExternalForm())
}
override fun deserialize(decoder: Decoder): URL = URI.create(decoder.decodeString()).toURL()
}