-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIssuance.kt
More file actions
479 lines (411 loc) · 19 KB
/
Issuance.kt
File metadata and controls
479 lines (411 loc) · 19 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
/*
* 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
import eu.europa.ec.eudi.openid4vci.internal.KeyGenerator
import kotlinx.serialization.json.JsonObject
import kotlin.time.Duration
/**
* Represents the credential as it is serialized by the credential issuer
* within a credential or deferred response.
*
* The choice is format-specific, and it can be either a string or a JSON object
*/
sealed interface Credential {
@JvmInline
value class Str(val value: String) : Credential {
override fun toString(): String = value
}
@JvmInline
value class Json(val value: JsonObject) : Credential {
override fun toString(): String = value.toString()
}
}
/**
* Credential was issued from server and the result is returned inline.
*
* @param credential The issued credential.
* @param additionalInfo Optional, information returned by the issuer for the [credential]
*/
data class IssuedCredential(
val credential: Credential,
val additionalInfo: JsonObject?,
) : java.io.Serializable {
companion object {
fun string(credential: String, additionalInfo: JsonObject? = null): IssuedCredential =
IssuedCredential(Credential.Str(credential), additionalInfo)
fun json(credential: JsonObject, additionalInfo: JsonObject? = null): IssuedCredential =
IssuedCredential(Credential.Json(credential), additionalInfo)
}
}
/**
* Sealed hierarchy of states describing the state of an issuance request submitted to a credential issuer.
*/
sealed interface SubmissionOutcome : java.io.Serializable {
/**
* State that denotes the successful submission of an issuance request
* @param credentials The outcome of the issuance request.
* If the issuance request was a batch request, it will contain the results of each issuance request.
* If it was a single issuance request list will contain only one result.
*
* @param credentials The credentials issued
* @param notificationId The identifier to be used in issuer's notification endpoint.
*/
data class Success(
val credentials: List<IssuedCredential>,
val notificationId: NotificationId?,
) : SubmissionOutcome {
init {
require(credentials.isNotEmpty()) { "credentials must not be empty" }
}
}
/**
* Credential could not be issued immediately. An identifier is returned from server to be used later on
* to request the credential from issuer's Deferred Credential Endpoint.
*
* @param transactionId A string identifying a Deferred Issuance transaction.
* @param interval Represents the minimum amount of time before sending a new deferred issuance request.
*/
data class Deferred(val transactionId: TransactionId, val interval: Duration) : SubmissionOutcome {
init {
require(interval.isPositive()) { "interval must be positive" }
}
}
/**
* State that denotes that the credential issuance request has failed
*
* @param error The error that caused the failure of the request
*/
data class Failed(val error: CredentialIssuanceError) : SubmissionOutcome
}
/**
* Sealed interface to model the payload of an issuance request. Issuance can be requested by providing the credential configuration
* identifier and a claim set ot by providing a credential identifier retrieved from token endpoint while authorizing an issuance request.
*/
sealed interface IssuanceRequestPayload {
val credentialConfigurationIdentifier: CredentialConfigurationIdentifier
/**
* Credential identifier based request payload.
*
* @param credentialConfigurationIdentifier The credential configuration identifier
* @param credentialIdentifier The credential identifier
*/
data class IdentifierBased(
override val credentialConfigurationIdentifier: CredentialConfigurationIdentifier,
val credentialIdentifier: CredentialIdentifier,
) : IssuanceRequestPayload
/**
* Credential configuration based request payload.
*
* @param credentialConfigurationIdentifier The credential configuration identifier
*/
data class ConfigurationBased(
override val credentialConfigurationIdentifier: CredentialConfigurationIdentifier,
) : IssuanceRequestPayload
}
typealias AuthorizedRequestAnd<T> = Pair<AuthorizedRequest, T>
sealed interface ProofsSpecification {
data object NoProofs : ProofsSpecification
sealed interface JwtProofs : ProofsSpecification {
data class NoKeyAttestation(
val proofsSigner: BatchSigner<JwtBindingKey>,
) : JwtProofs
data class WithKeyAttestation(
val proofSignerProvider: suspend (Nonce?) -> Signer<KeyAttestationJWT>,
val keyIndex: Int,
) : JwtProofs
}
data class AttestationProof(
val attestationProvider: suspend (Nonce?) -> KeyAttestationJWT,
) : ProofsSpecification
}
/**
* An interface for submitting a credential issuance request.
*/
fun interface RequestIssuance {
/**
* Places a request to the credential issuance endpoint.
*
* If the [AuthorizedRequest] contains authorization details for the requested
* [IssuanceRequestPayload.credentialConfigurationIdentifier], then the [requestPayload] must be
* [IssuanceRequestPayload.IdentifierBased] and the credential identifier must be one of the authorized identifiers.
*
* @param requestPayload the payload of the request
* @param proofsSpecification the specification of proofs to be included in the request
* @return the possibly updated [AuthorizedRequest] (if updated it will contain a fresh updated Resource-Server DPoP Nonce)
* and the [SubmissionOutcome]
*/
suspend fun AuthorizedRequest.request(
requestPayload: IssuanceRequestPayload,
proofsSpecification: ProofsSpecification,
): Result<AuthorizedRequestAnd<SubmissionOutcome>>
}
/**
* A factory method that based on the issuer's supported encryption and the wallet's configuration creates the encryption specification
* that the wallet expects in the response of its issuance request.
*/
fun interface ResponseEncryptionSpecFactory {
fun make(
issuerSupportedResponseEncryptedParameters: SupportedResponseEncryptionParameters,
walletEncryptionSupportConfig: EncryptionSupportConfig,
): EncryptionSpec?
companion object {
val DEFAULT: ResponseEncryptionSpecFactory =
ResponseEncryptionSpecFactory { issuerSupportedResponseEncryptedParameters, walletEncryptionSupportConfig ->
val issuerSupportedPayloadCompression = issuerSupportedResponseEncryptedParameters.payloadCompression
val compressionAlg = when (issuerSupportedPayloadCompression) {
PayloadCompression.NotSupported -> null
is PayloadCompression.Supported ->
walletEncryptionSupportConfig.compressionAlgorithms?.intersect(
issuerSupportedPayloadCompression.algorithms,
)?.firstOrNull()
}
val encryptionMethod = issuerSupportedResponseEncryptedParameters.encryptionMethods
.intersect(walletEncryptionSupportConfig.supportedEncryptionMethods).firstOrNull()
encryptionMethod?.let { method ->
issuerSupportedResponseEncryptedParameters.algorithms.firstNotNullOfOrNull { algorithm ->
KeyGenerator.genKeyIfSupported(walletEncryptionSupportConfig, algorithm)
?.let { jwk -> EncryptionSpec(jwk, method, compressionAlg) }
}
}
}
}
}
fun interface RequestEncryptionSpecFactory {
fun make(
issuerSupportedRequestEncryptionParameters: SupportedRequestEncryptionParameters,
walletEncryptionSupportConfig: EncryptionSupportConfig,
): EncryptionSpec?
companion object {
val DEFAULT: RequestEncryptionSpecFactory =
RequestEncryptionSpecFactory { issuerSupportedRequestEncryptionParameters, walletEncryptionSupportConfig ->
val issuerSupportedPayloadCompression = issuerSupportedRequestEncryptionParameters.payloadCompression
val walletSupportedCompressionAlgs = walletEncryptionSupportConfig.compressionAlgorithms
val compressionAlg = when (issuerSupportedPayloadCompression) {
PayloadCompression.NotSupported -> null
is PayloadCompression.Supported ->
walletSupportedCompressionAlgs?.intersect(issuerSupportedPayloadCompression.algorithms)?.firstOrNull()
}
val walletSupportedEncryptionAlgorithms = walletEncryptionSupportConfig.supportedEncryptionAlgorithms
val walletSupportedEncryptionMethods = walletEncryptionSupportConfig.supportedEncryptionMethods
val encryptionMethod =
issuerSupportedRequestEncryptionParameters.encryptionMethods.intersect(walletSupportedEncryptionMethods).firstOrNull()
encryptionMethod?.let { method ->
issuerSupportedRequestEncryptionParameters.encryptionKeys.keys
.filter { it.algorithm in walletSupportedEncryptionAlgorithms }
.firstNotNullOfOrNull { key -> EncryptionSpec(key, method, compressionAlg) }
}
}
}
}
/**
* Errors that can happen in the process of issuance process
*/
sealed class CredentialIssuanceError(message: String) : Throwable(message) {
/**
* Indicates that the state returned by the authorization server doesn't match the state
* included which was included in the authorization request, during authorization code flow
*/
class InvalidAuthorizationState : CredentialIssuanceError("InvalidAuthorizationState")
/**
* Failure when placing Pushed Authorization Request to Authorization Server
*/
data class PushedAuthorizationRequestFailed(
val error: String,
val errorDescription: String?,
) : CredentialIssuanceError("$error+${errorDescription?.let { " description=$it" }}")
/**
* Failure when requesting access token from Authorization Server
*/
data class AccessTokenRequestFailed(
val error: String,
val errorDescription: String?,
) : CredentialIssuanceError("$error+${errorDescription?.let { " description=$it" }}")
/**
* Failure when creating an issuance request
*/
class InvalidIssuanceRequest(
message: String,
) : CredentialIssuanceError(message)
/**
* Issuer rejected the issuance request because no or invalid proof(s) were provided or at least one of the key proofs does
* not contain a c_nonce value.
*/
data class InvalidProof(
val errorDescription: String? = null,
) : CredentialIssuanceError("Invalid Proof")
/**
* Issuer rejected the issuance request because considered the proof erroneous.
* It is marked as irrecoverable because it is raised only after the library
* has automatically retried to recover from an [InvalidProof] error and failed
*/
data class IrrecoverableInvalidProof(val errorDescription: String? = null) :
CredentialIssuanceError("Irrecoverable invalid proof ")
/**
* Invalid access token passed to issuance server
*/
class InvalidToken : CredentialIssuanceError("InvalidToken")
/**
* Invalid transaction id passed to issuance server in the context of deferred credential requests
*/
class InvalidTransactionId : CredentialIssuanceError("InvalidTransactionId")
/**
* Unexpected Transaction Id returned by Issuance Server in the context of a Deferred Credential Request.
*/
data class UnexpectedTransactionId(
val expected: TransactionId,
val actual: TransactionId,
) : CredentialIssuanceError("UnexpectedTransactionId")
/**
* Requested Credential Configuration is unknown to issuance server
*/
class UnknownCredentialConfiguration : CredentialIssuanceError("UnknownCredentialConfiguration")
/**
* Requested Credential identifier is unknown to issuance server
*/
class UnknownCredentialIdentifier : CredentialIssuanceError("UnknownCredentialIdentifier")
/**
* Invalid encryption parameters passed to issuance server
*/
class InvalidEncryptionParameters : CredentialIssuanceError("InvalidEncryptionParameters")
/**
* Issuance server does not support batch credential requests
*/
class IssuerDoesNotSupportBatchIssuance : CredentialIssuanceError("IssuerDoesNotSupportBatchIssuance")
/**
* Issuance server provides supports batch_size which is
* smaller than the number of proofs the caller provided.
*/
class IssuerBatchSizeLimitExceeded(val batchSize: Int) :
CredentialIssuanceError("IssuerBatchSizeLimitExceeded $batchSize")
/**
* Issuance server does not support deferred credential issuance
*/
class IssuerDoesNotSupportDeferredIssuance : CredentialIssuanceError("IssuerDoesNotSupportDeferredIssuance")
/**
* Generic failure during issuance request
*/
data class IssuanceRequestFailed(
val error: String,
val errorDescription: String? = null,
) : CredentialIssuanceError("$error+${errorDescription?.let { " description=$it" }}")
/**
* Generic failure during notification
*/
data class NotificationFailed(
val error: String,
) : CredentialIssuanceError(error)
/**
* Issuance server response is un-parsable
*/
data class ResponseUnparsable(val error: String) : CredentialIssuanceError("ResponseUnparsable")
/**
* Request to nonce endpoint of issuer failed
*/
data class CNonceRequestFailed(val error: String) : CredentialIssuanceError("CNonceRequestFailed")
/**
* Sealed hierarchy of errors related to proof generation
*/
sealed class ProofGenerationError(message: String) : CredentialIssuanceError(message) {
/**
* Proof type provided for specific credential is not supported from issuance server
*/
class ProofTypeNotSupported : ProofGenerationError("ProofTypeNotSupported")
/**
* Proof type signing algorithm provided for specific credential is not supported from issuance server
*/
class ProofTypeSigningAlgorithmNotSupported :
ProofGenerationError("ProofTypeSigningAlgorithmNotSupported")
}
/**
* Sealed hierarchy of errors related to validation of request encryption parameters.
*/
sealed class RequestEncryptionError(message: String) : CredentialIssuanceError(message) {
/**
* Request encryption JWK is not of the ones advertised by issuer.
*/
class RequestEncryptionKeyNotAnIssuerKey :
RequestEncryptionError("RequestEncryptionKeyNotAnIssuerKey")
/**
* Request encryption method specified is not supported from issuance server.
*/
class RequestEncryptionMethodNotSupportedByIssuer :
RequestEncryptionError("RequestEncryptionMethodNotSupportedByIssuer")
/**
* Issuer enforces encrypted requests but request encryption parameters cannot be formulated.
*/
class IssuerRequiresEncryptedRequestButEncryptionSpecCannotBeFormulated :
RequestEncryptionError("IssuerRequiresEncryptedRequestButEncryptionSpecCannotBeFormulated")
}
/**
* Sealed hierarchy of errors related to validation of encryption parameters passed along with the issuance request.
*/
sealed class ResponseEncryptionError(message: String) : CredentialIssuanceError(message) {
/**
* Wallet requires Credential Response encryption, but it is not supported by the issuance server.
*/
class ResponseEncryptionRequiredByWalletButNotSupportedByIssuer :
ResponseEncryptionError("ResponseEncryptionRequiredByWalletButNotSupportedByIssuer")
/**
* Response encryption key does not specify 'alg' attribute
*/
class ResponseEncryptionKeyDoesNotSpecifyAlgorithm :
ResponseEncryptionError("ResponseEncryptionKeyDoesNotSpecifyAlgorithm")
/**
* Response encryption algorithm specified in request is not supported from issuance server
*/
class ResponseEncryptionAlgorithmNotSupportedByIssuer :
ResponseEncryptionError("ResponseEncryptionAlgorithmNotSupportedByIssuer")
/**
* Response encryption method specified in request is not supported from issuance server
*/
class ResponseEncryptionMethodNotSupportedByIssuer :
ResponseEncryptionError("ResponseEncryptionMethodNotSupportedByIssuer")
/**
* Issuer enforces encrypted responses but encryption parameters not provided in request
*/
class IssuerExpectsResponseEncryptionCryptoMaterialButNotProvided :
ResponseEncryptionError("IssuerExpectsResponseEncryptionCryptoMaterialButNotProvided")
/**
* Wallet requires Credential Response encryption, but no crypto material can be generated for the issuance server.
*/
class WalletRequiresCredentialResponseEncryptionButNoCryptoMaterialCanBeGenerated :
ResponseEncryptionError("WalletRequiresCredentialResponseEncryptionButNoCryptoMaterialCanBeGenerated")
/**
* Issuer does not support ecrypted payload compression
*/
class IssuerDoesNotSupportEncryptedPayloadCompression :
ResponseEncryptionError("IssuerDoesNotSupportEncryptedPayloadCompression")
/**
* Issuer does not support ecrypted payload compression.
*/
class IssuerDoesNotSupportEncryptedPayloadCompressionAlgorithm :
ResponseEncryptionError("IssuerDoesNotSupportEncryptedPayloadCompressionAlgorithm")
/**
* Response encryption specification is available but no request specification could be created.
*/
class MissingRequiredRequestEncryptionSpecification :
ResponseEncryptionError("MissingRequiredRequestEncryptionSpecification")
}
/**
* Wrong content-type of encrypted response. Content-type of encrypted responses must be application/jwt
*/
data class InvalidResponseContentType(
val expectedContentType: String,
val invalidContentType: String,
) : CredentialIssuanceError(
"Encrypted response content-type expected to be $expectedContentType but instead was $invalidContentType",
)
}