-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestIssuanceImpl.kt
More file actions
406 lines (369 loc) · 17.2 KB
/
RequestIssuanceImpl.kt
File metadata and controls
406 lines (369 loc) · 17.2 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
* 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.JWSAlgorithm
import com.nimbusds.jose.JWSVerifier
import com.nimbusds.jose.crypto.ECDSAVerifier
import com.nimbusds.jose.crypto.RSASSAVerifier
import com.nimbusds.jose.jwk.ECKey
import com.nimbusds.jose.jwk.JWK
import com.nimbusds.jose.jwk.RSAKey
import com.nimbusds.jwt.SignedJWT
import eu.europa.ec.eudi.openid4vci.*
import eu.europa.ec.eudi.openid4vci.internal.http.CNonceAndDPoPNonce
import eu.europa.ec.eudi.openid4vci.internal.http.CredentialEndpointClient
import eu.europa.ec.eudi.openid4vci.internal.http.NonceEndpointClient
import java.time.Instant
import kotlin.time.Duration
internal class RequestIssuanceImpl(
private val credentialOffer: CredentialOffer,
private val config: OpenId4VCIConfig,
private val credentialEndpointClient: CredentialEndpointClient,
private val nonceEndpointClient: NonceEndpointClient?,
private val batchCredentialIssuance: BatchCredentialIssuance,
private val exchangeEncryptionSpecification: ExchangeEncryptionSpecification,
) : RequestIssuance {
init {
val nonceEndpoint = credentialOffer.credentialIssuerMetadata.nonceEndpoint
if (nonceEndpoint != null) {
check(nonceEndpointClient != null) {
" A nonce endpoint client needs to be configured if issuer advertises a nonce endpoint"
}
}
if (nonceEndpointClient != null) {
check(nonceEndpoint != null) {
"A nonce endpoint client is configured although issuer does not advertises a nonce endpoint"
}
}
}
override suspend fun AuthorizedRequest.request(
requestPayload: IssuanceRequestPayload,
proofsSpecification: ProofsSpecification,
): Result<AuthorizedRequestAnd<SubmissionOutcome>> = runCatchingCancellable {
validateRequestPayload(requestPayload, credentialIdentifiers.orEmpty())
val (proofs, proofsDpopNonce) = buildProofs(proofsSpecification, requestPayload.credentialConfigurationIdentifier, grant)
val credentialRequest = buildRequest(requestPayload, proofs, credentialIdentifiers.orEmpty())
// Place the request
val proofsOrAuthRequestDpopNonce = proofsDpopNonce ?: resourceServerDpopNonce
val (outcome, newResourceServerDpopNonce) =
credentialEndpointClient.placeIssuanceRequest(
accessToken,
proofsOrAuthRequestDpopNonce,
credentialRequest,
).getOrThrow()
// Update state (maybe) with new Dpop Nonce from resource server
val updatedAuthorizedRequest =
this.withResourceServerDpopNonce(newResourceServerDpopNonce ?: proofsOrAuthRequestDpopNonce)
updatedAuthorizedRequest to outcome.toPub()
}
private fun validateRequestPayload(
requestPayload: IssuanceRequestPayload,
authorizationDetails: Map<CredentialConfigurationIdentifier, List<CredentialIdentifier>>,
) {
if (authorizationDetails.isNotEmpty()) {
val authorizedIdentifiers = authorizationDetails[requestPayload.credentialConfigurationIdentifier]
check(!authorizedIdentifiers.isNullOrEmpty()) {
"No credential identifiers authorized for ${requestPayload.credentialConfigurationIdentifier}"
}
require(requestPayload is IssuanceRequestPayload.IdentifierBased) {
"Authorization detail type of openid_credential require usage of credential identifiers in credential request"
}
require(requestPayload.credentialIdentifier in authorizedIdentifiers) {
"Credential identifier ${requestPayload.credentialIdentifier.value} is not in authorized identifiers $authorizedIdentifiers"
}
} else {
require(requestPayload is IssuanceRequestPayload.ConfigurationBased) {
"Issuance request payload must be of type ConfigurationBased when no credential identifiers are authorized"
}
}
}
private suspend fun buildProofs(
proofsSpecification: ProofsSpecification,
credentialConfigId: CredentialConfigurationIdentifier,
grant: Grant,
): Pair<List<Proof>, Nonce?> {
proofsSpecification.ensureCompatibleWith(credentialConfigId)
return when (proofsSpecification) {
is ProofsSpecification.NoProofs -> emptyList<Proof>() to null
is ProofsSpecification.JwtProofs.WithKeyAttestation -> {
val cNonceAndDPoPNonce = cNonce()
val proofs = listOf(
jwtProofWithKeyAttestation(
proofsSpecification,
credentialConfigId,
grant,
cNonceAndDPoPNonce?.cnonce,
),
)
proofs to cNonceAndDPoPNonce?.dpopNonce
}
is ProofsSpecification.JwtProofs.NoKeyAttestation -> {
val cNonceAndDPoPNonce = cNonce()
val proofs = jwtProofsWithoutKeyAttestation(
proofsSpecification,
credentialConfigId,
grant,
cNonceAndDPoPNonce?.cnonce,
)
proofs to cNonceAndDPoPNonce?.dpopNonce
}
is ProofsSpecification.AttestationProof -> {
val cNonceAndDPoPNonce = cNonce()
val proofs = listOf(
attestationProof(
proofsSpecification,
credentialConfigId,
cNonceAndDPoPNonce?.cnonce,
),
)
proofs to cNonceAndDPoPNonce?.dpopNonce
}
}
}
private fun ProofsSpecification.ensureCompatibleWith(credentialConfigId: CredentialConfigurationIdentifier) {
val credentialConfiguration = credentialSupportedById(credentialConfigId)
val proofTypesSupported = credentialConfiguration.proofTypesSupported
when (this) {
is ProofsSpecification.NoProofs -> {
require(proofTypesSupported == ProofTypesSupported.Empty) {
"Credential configuration requires proofs."
}
}
is ProofsSpecification.JwtProofs -> {
val proofRequirement = proofTypesSupported[ProofType.JWT]
requireNotNull(proofRequirement) {
"Credential configuration doesn't support JWT proofs."
}
check(proofRequirement is ProofTypeMeta.Jwt)
val keyAttestationRequirement = proofRequirement.keyAttestationRequirement
when (this) {
is ProofsSpecification.JwtProofs.NoKeyAttestation -> {
require(keyAttestationRequirement is KeyAttestationRequirement.NotRequired) {
"Credential configuration requires key attestation."
}
}
is ProofsSpecification.JwtProofs.WithKeyAttestation -> {
require(keyAttestationRequirement !is KeyAttestationRequirement.NotRequired) {
"Credential configuration does not support key attestation."
}
}
}
}
is ProofsSpecification.AttestationProof -> {
requireNotNull(proofTypesSupported[ProofType.ATTESTATION]) {
"Credential configuration doesn't support attestation proofs."
}
}
}
}
private fun credentialSupportedById(credentialId: CredentialConfigurationIdentifier): CredentialConfiguration {
val credentialSupported =
credentialOffer.credentialIssuerMetadata.credentialConfigurationsSupported[credentialId]
return requireNotNull(credentialSupported) {
"$credentialId was not found within issuer metadata"
}
}
private suspend fun jwtProofWithKeyAttestation(
proofsSpecification: ProofsSpecification.JwtProofs.WithKeyAttestation,
credentialConfigId: CredentialConfigurationIdentifier,
grant: Grant,
cNonce: Nonce?,
): Proof.Jwt {
val (proofSignerProvider, keyIndex) = proofsSpecification
val proofSigner = proofSignerProvider(cNonce)
val joseAlg = run {
val javaSigningAlgorithm = proofSigner.javaAlgorithm
javaSigningAlgorithm.toSupportedJoseAlgorithm(credentialConfigId)
}
val claims = jwtProofClaims(cNonce = cNonce, grant = grant)
val jwtProof = proofSigner.use { operation ->
operation.publicMaterial.ensureKeyAttestationJwtAlgIsSupported(credentialConfigId, ProofType.JWT)
val signer = KeyAttestationJwtProofSigner(joseAlg, operation, keyIndex)
val signedJwt = signer.sign(claims)
SignedJWT.parse(signedJwt)
}
verifyKeyAttestationJwtProofSignature(jwtProof)
return Proof.Jwt(jwtProof)
}
private fun KeyAttestationJWT.ensureKeyAttestationJwtAlgIsSupported(
credentialConfigId: CredentialConfigurationIdentifier,
proofType: ProofType,
) {
val attestationJwtAlg = SignedJWT.parse(value).header.algorithm
val proofTypesSupported = credentialSupportedById(credentialConfigId).proofTypesSupported
val spec = proofTypesSupported.values.firstOrNull { it.type() == proofType }
ensure(spec != null && attestationJwtAlg in spec.algorithms()) {
CredentialIssuanceError.ProofGenerationError.ProofTypeSigningAlgorithmNotSupported()
}
}
private suspend fun jwtProofsWithoutKeyAttestation(
proofsSpecification: ProofsSpecification.JwtProofs.NoKeyAttestation,
credentialConfigId: CredentialConfigurationIdentifier,
grant: Grant,
cNonce: Nonce?,
): List<Proof.Jwt> {
val joseAlg = run {
val javaSigningAlgorithm = proofsSpecification.proofsSigner.javaAlgorithm
javaSigningAlgorithm.toSupportedJoseAlgorithm(credentialConfigId)
}
return proofsSpecification.proofsSigner.use { operation ->
operation.assertMatchesBatchIssuanceBatchSize()
val proofsSigner = JwtProofsSigner(joseAlg, operation)
val claims = jwtProofClaims(cNonce = cNonce, grant = grant)
proofsSigner.sign(claims).map {
Proof.Jwt(SignedJWT.parse(it.second))
}
}
}
private suspend fun attestationProof(
proofsSpecification: ProofsSpecification.AttestationProof,
credentialConfigId: CredentialConfigurationIdentifier,
cNonce: Nonce?,
): Proof.Attestation {
val keyAttestationJwt = proofsSpecification.attestationProvider(cNonce)
keyAttestationJwt.ensureKeyAttestationJwtAlgIsSupported(credentialConfigId, ProofType.ATTESTATION)
return Proof.Attestation(keyAttestationJwt)
}
private fun BatchSignOperation<JwtBindingKey>.assertMatchesBatchIssuanceBatchSize() =
when (val popSignersNo = operations.size) {
0 -> error("At least one PopSigner is required in Authorized.ProofRequired")
1 -> Unit
else -> {
when (batchCredentialIssuance) {
BatchCredentialIssuance.NotSupported -> CredentialIssuanceError.IssuerDoesNotSupportBatchIssuance()
is BatchCredentialIssuance.Supported -> {
val maxBatchSize = batchCredentialIssuance.batchSize
ensure(popSignersNo <= maxBatchSize) {
CredentialIssuanceError.IssuerBatchSizeLimitExceeded(maxBatchSize)
}
}
}
}
}
private fun String.toSupportedJoseAlgorithm(credentialConfigId: CredentialConfigurationIdentifier): JWSAlgorithm {
val proofTypesSupported = credentialSupportedById(credentialConfigId).proofTypesSupported
val spec = proofTypesSupported.values.filterIsInstance<ProofTypeMeta.Jwt>().firstOrNull()
ensureNotNull(spec) {
CredentialIssuanceError.ProofGenerationError.ProofTypeNotSupported()
}
return spec.let {
val joseSigningAlgorithm = this.toJoseAlg()
val proofTypeSigningAlgorithmsSupported = spec.algorithms
ensure(joseSigningAlgorithm in proofTypeSigningAlgorithmsSupported) {
CredentialIssuanceError.ProofGenerationError.ProofTypeSigningAlgorithmNotSupported()
}
joseSigningAlgorithm
}
}
private suspend fun cNonce(): CNonceAndDPoPNonce? = nonceEndpointClient?.getNonce()?.getOrThrow()
private fun jwtProofClaims(
cNonce: Nonce?,
grant: Grant,
): JwtProofClaims {
fun iss(clientAuthentication: ClientAuthentication, grant: Grant): ClientId? {
val useIss = when (grant) {
Grant.AuthorizationCode -> true
Grant.PreAuthorizedCodeGrant -> when (clientAuthentication) {
is ClientAuthentication.AttestationBased -> true
is ClientAuthentication.None -> false
}
}
return clientAuthentication.id.takeIf { useIss }
}
return JwtProofClaims(
audience = credentialOffer.credentialIssuerMetadata.credentialIssuerIdentifier.toString(),
issuedAt = Instant.now(),
issuer = iss(config.clientAuthentication, grant),
nonce = cNonce?.value,
)
}
private fun verifyKeyAttestationJwtProofSignature(jwtProof: SignedJWT) {
val keyAttestationJwt = jwtProof.header.getCustomParam("key_attestation") as? String
?: throw IllegalArgumentException("Missing 'key_attestation' in JWT header")
val keyAttestation = KeyAttestationJWT(keyAttestationJwt)
val attestedKeys = keyAttestation.attestedKeys
val jwk = attestedKeys.firstOrNull { jwk: JWK ->
try {
val verifier: JWSVerifier? = when (jwk) {
is RSAKey -> RSASSAVerifier(jwk)
is ECKey -> ECDSAVerifier(jwk)
else -> null
}
verifier != null && jwtProof.verify(verifier)
} catch (_: Exception) {
false
}
}
requireNotNull(jwk) {
"Signed JWT is not signed by any of the attested keys in key_attestation."
}
}
private fun buildRequest(
requestPayload: IssuanceRequestPayload,
proofs: List<Proof>,
authorizationDetails: Map<CredentialConfigurationIdentifier, List<CredentialIdentifier>>,
): CredentialIssuanceRequest = when (requestPayload) {
is IssuanceRequestPayload.ConfigurationBased -> {
CredentialIssuanceRequest.byCredentialConfigurationId(
requestPayload.credentialConfigurationIdentifier,
proofs,
exchangeEncryptionSpecification,
)
}
is IssuanceRequestPayload.IdentifierBased -> {
requestPayload.ensureAuthorized(authorizationDetails)
CredentialIssuanceRequest.byCredentialId(
requestPayload.credentialIdentifier,
proofs,
exchangeEncryptionSpecification,
)
}
}
}
private fun IssuanceRequestPayload.IdentifierBased.ensureAuthorized(
authorizationDetails: Map<CredentialConfigurationIdentifier, List<CredentialIdentifier>>,
) {
val credentialId = credentialIdentifier
val authorizedCredIds = checkNotNull(authorizationDetails[credentialConfigurationIdentifier]) {
"No credential identifiers authorized for $credentialConfigurationIdentifier"
}
check(credentialId in authorizedCredIds) {
"The credential identifier ${credentialId.value} is not authorized"
}
}
internal sealed interface SubmissionOutcomeInternal {
data class Success(
val credentials: List<IssuedCredential>,
val notificationId: NotificationId?,
) : SubmissionOutcomeInternal
data class Deferred(
val transactionId: TransactionId,
val interval: Duration,
) : SubmissionOutcomeInternal {
init {
require(interval.isPositive()) { "interval must be positive" }
}
}
data class Failed(
val error: CredentialIssuanceError,
) : SubmissionOutcomeInternal
fun toPub(): SubmissionOutcome =
when (this) {
is Success -> SubmissionOutcome.Success(credentials, notificationId)
is Deferred -> SubmissionOutcome.Deferred(transactionId, interval)
is Failed -> SubmissionOutcome.Failed(error)
}
}