forked from openwallet-foundation/multipaz
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenid4VpVerifierModel.kt
More file actions
300 lines (283 loc) · 11.8 KB
/
Copy pathOpenid4VpVerifierModel.kt
File metadata and controls
300 lines (283 loc) · 11.8 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package org.multipaz.verifier
import kotlin.time.Clock
import kotlinx.datetime.DateTimePeriod
import kotlinx.datetime.TimeZone
import kotlinx.datetime.plus
import kotlinx.io.bytestring.ByteString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.add
import kotlinx.serialization.json.addJsonObject
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray
import kotlinx.serialization.json.putJsonObject
import org.multipaz.asn1.ASN1Integer
import org.multipaz.cbor.Cbor
import org.multipaz.cbor.CborArray
import org.multipaz.cbor.Simple
import org.multipaz.cbor.annotation.CborSerializable
import org.multipaz.cbor.buildCborArray
import org.multipaz.crypto.Algorithm
import org.multipaz.crypto.Crypto
import org.multipaz.crypto.EcCurve
import org.multipaz.crypto.EcPrivateKey
import org.multipaz.crypto.JsonWebEncryption
import org.multipaz.crypto.SigningKey
import org.multipaz.crypto.X500Name
import org.multipaz.crypto.X509CertChain
import org.multipaz.documenttype.DocumentCannedRequest
import org.multipaz.jwt.buildJwt
import org.multipaz.mdoc.response.DeviceResponseParser
import org.multipaz.mdoc.util.MdocUtil
import org.multipaz.util.fromBase64Url
import org.multipaz.util.toBase64Url
import kotlin.random.Random
/**
* Object that holds data necessary to verify Openid4VP credential presentation.
*
* This class is designed to work in the environment where its state may need to be serialized
* between the time that the presentation request is generated (see [makeRequest]) and the
* device response is verified (see [processResponse]), as is typically the case on the
* server.
*
* This class creates requests for and parses only encrypted presentations (using either
* "dc_api.jwt" or "direst_post.jwt" response mode) and it requires compliance with draft 28
* of the Openid4VP spec.
*/
@CborSerializable
class Openid4VpVerifierModel(
val clientId: String,
val nonce: ByteString = ByteString(Random.nextBytes(15)),
val ephemeralPrivateKey: EcPrivateKey = Crypto.createEcPrivateKey(EcCurve.P256),
val requestedFormats: MutableMap<String, String> = mutableMapOf()
) {
/**
* Creates an Openid4VP presentation request for credentials (typically just one) in
* [requests] parameter.
*/
suspend fun makeRequest(
state: String,
responseMode: String,
requests: Map<String, DocumentCannedRequest>,
readerIdentity: ReaderIdentity,
expectedOrigins: List<String> = listOf(),
responseUri: String? = null,
): String = buildJwt(
type = "oauth-authz-req+jwt",
key = SigningKey.X509CertifiedExplicit(
privateKey = ephemeralPrivateKey,
certChain = createCertificateChain(readerIdentity)
)
) {
put("client_id", clientId)
if (responseUri != null) {
put("response_uri", responseUri)
}
put("response_type", "vp_token")
put("response_mode", responseMode)
put("nonce", nonce.toByteArray().toBase64Url())
put("client_metadata", buildClientMetadata())
put("state", state)
if (expectedOrigins.isNotEmpty()) {
putJsonArray("expected_origins") {
expectedOrigins.forEach { add(it) }
}
}
putJsonObject("dcql_query") {
putJsonArray("credentials") {
for ((id, request) in requests) {
addJsonObject {
put("id", id)
if (request.mdocRequest == null) {
requestedFormats[id] = "dc+sd-jwt"
put("format", JsonPrimitive("dc+sd-jwt"))
putJsonObject("meta") {
put("vct_values",
buildJsonArray {
add(JsonPrimitive(request.jsonRequest!!.vct))
}
)
}
putJsonArray("claims") {
for (claim in request.jsonRequest!!.claimsToRequest) {
addJsonObject {
putJsonArray("path") {
add(JsonPrimitive(claim.identifier))
}
}
}
}
} else {
requestedFormats[id] = "mso_mdoc"
put("format", JsonPrimitive("mso_mdoc"))
putJsonObject("meta") {
put(
"doctype_value",
JsonPrimitive(request.mdocRequest!!.docType)
)
}
putJsonArray("claims") {
for (ns in request.mdocRequest!!.namespacesToRequest) {
for ((de, intentToRetain) in ns.dataElementsToRequest) {
addJsonObject {
putJsonArray("path") {
add(JsonPrimitive(ns.namespace))
add(JsonPrimitive(de.attribute.identifier))
}
put(
"intent_to_retain",
JsonPrimitive(intentToRetain)
)
}
}
}
}
}
}
}
}
}
}
/**
* Parses and validates credential presentation for the request that was previously created
* using [makeRequest].
*/
fun processResponse(
responseUri: String,
response: String
): Map<String, Presentation> {
val decrypted = JsonWebEncryption.decrypt(response, ephemeralPrivateKey)
val header = Json.parseToJsonElement(
response.substring(0, response.indexOf('.')).fromBase64Url().decodeToString()
).jsonObject
val sessionTranscript = createSessionTranscript(
clientId = clientId,
responseUri = responseUri,
authorizationRequestNonce = header["apv"]!!.jsonPrimitive.content,
mdocGeneratedNonce = header["apu"]!!.jsonPrimitive.content,
)
val vpToken = decrypted["vp_token"]!!.jsonObject
return vpToken.mapValues { (id, encoded) ->
val presentationText = encoded.jsonPrimitive.content
when (requestedFormats[id]) {
"mso_mdoc" -> {
val parser = DeviceResponseParser(
presentationText.fromBase64Url(),
sessionTranscript
)
MdocPresentation(parser.parse())
}
"dc+sd-jwt" -> {
SdJwtPresentation(presentationText)
}
else -> throw IllegalStateException("Unknown format for id '$id'")
}
}
}
private suspend fun createCertificateChain(readerIdentity: ReaderIdentity): X509CertChain {
val now = Clock.System.now()
val validFrom = now.plus(DateTimePeriod(minutes = -10), TimeZone.currentSystemDefault())
val validUntil = now.plus(DateTimePeriod(minutes = 10), TimeZone.currentSystemDefault())
val readerKey = ephemeralPrivateKey
val readerKeySubject = "CN=OWF IC Online Verifier Single-Use Reader Key"
val readerKeyCertificate = MdocUtil.generateReaderCertificate(
readerRootKey = SigningKey.X509CertifiedExplicit(
privateKey = readerIdentity.privateKey,
certChain = readerIdentity.certificateChain
),
readerKey = readerKey.publicKey,
subject = X500Name.fromName(readerKeySubject),
serial = ASN1Integer(1L),
validFrom = validFrom,
validUntil = validUntil
)
return X509CertChain(
buildList {
add(readerKeyCertificate)
addAll(readerIdentity.certificateChain.certificates)
}
)
}
private fun buildClientMetadata(): JsonObject {
val vpFormats = buildJsonObject {
putJsonObject("mso_mdoc") {
putJsonArray("alg") {
// TODO: should we list other algorithms here?
add(Algorithm.ESP256.joseAlgorithmIdentifier)
}
}
putJsonObject("dc+sd-jwt") {
putJsonArray("sd-jwt_alg_values") {
add(Algorithm.ESP256.joseAlgorithmIdentifier)
}
putJsonArray("kb-jwt_alg_values") {
add(Algorithm.ESP256.joseAlgorithmIdentifier)
}
}
}
return buildJsonObject {
putJsonArray("encrypted_response_enc_values_supported") {
add(Algorithm.A128GCM.joseAlgorithmIdentifier)
}
put("vp_formats_supported", vpFormats)
put("jwks", buildJsonObject {
put("keys", buildJsonArray {
add(ephemeralPrivateKey.publicKey.toJwk(additionalClaims = buildJsonObject {
put("use", "enc")
put("kid", "default")
put("alg", "ECDH-ES")
}))
})
})
}
}
// defined in ISO 18013-7 Annex B
private fun createSessionTranscript(
clientId: String,
responseUri: String,
authorizationRequestNonce: String,
mdocGeneratedNonce: String
): ByteArray {
val clientIdToHash = Cbor.encode(
CborArray.builder()
.add(clientId)
.add(mdocGeneratedNonce)
.end()
.build())
val clientIdHash = Crypto.digest(Algorithm.SHA256, clientIdToHash)
val responseUriToHash = Cbor.encode(
buildCborArray {
add(responseUri)
add(mdocGeneratedNonce)
}
)
val responseUriHash = Crypto.digest(Algorithm.SHA256, responseUriToHash)
val oid4vpHandover = buildCborArray {
add(clientIdHash)
add(responseUriHash)
add(authorizationRequestNonce)
}
return Cbor.encode(
buildCborArray {
add(Simple.NULL)
add(Simple.NULL)
add(oid4vpHandover)
}
)
}
sealed class Presentation
class MdocPresentation(val deviceResponse: DeviceResponseParser.DeviceResponse): Presentation()
class SdJwtPresentation(val compactSerialization: String): Presentation()
@CborSerializable
data class ReaderIdentity(
val privateKey: EcPrivateKey,
val certificateChain: X509CertChain
) {
companion object
}
}