-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDefaultCredentialIssuerMetadataResolver.kt
More file actions
179 lines (161 loc) · 7.58 KB
/
DefaultCredentialIssuerMetadataResolver.kt
File metadata and controls
179 lines (161 loc) · 7.58 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
/*
* 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.JOSEObjectType
import com.nimbusds.jose.jwk.AsymmetricJWK
import com.nimbusds.jose.jwk.JWK
import com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier
import com.nimbusds.jose.proc.JWSKeySelector
import com.nimbusds.jose.proc.SecurityContext
import com.nimbusds.jose.proc.SingleKeyJWSKeySelector
import com.nimbusds.jose.util.JSONObjectUtils
import com.nimbusds.jose.util.X509CertChainUtils
import com.nimbusds.jwt.JWTClaimsSet
import com.nimbusds.jwt.SignedJWT
import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier
import com.nimbusds.jwt.proc.DefaultJWTProcessor
import eu.europa.ec.eudi.openid4vci.*
import eu.europa.ec.eudi.openid4vci.internal.http.CredentialIssuerMetadataJsonParser
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
private val CONTENT_TYPE_APPLICATION_JWT = ContentType.parse("application/jwt")
internal class DefaultCredentialIssuerMetadataResolver(
private val httpClient: HttpClient,
) : CredentialIssuerMetadataResolver {
override suspend fun resolve(
issuer: CredentialIssuerId,
policy: IssuerMetadataPolicy,
): Result<CredentialIssuerMetadata> = runCatchingCancellable {
val wellKnownUrl = issuer.wellKnown()
val json = when (policy) {
IssuerMetadataPolicy.IgnoreSigned -> wellKnownUrl.requestUnsigned()
is IssuerMetadataPolicy.RequireSigned -> wellKnownUrl.requestSigned(policy.issuerTrust, issuer)
is IssuerMetadataPolicy.PreferSigned -> wellKnownUrl.requestPreferringSigned(policy.issuerTrust, issuer)
}
CredentialIssuerMetadataJsonParser.parseMetaData(json, issuer)
}
private suspend fun Url.requestUnsigned(): String {
val response = getAcceptingContentTypes(ContentType.Application.Json)
val contentType = response.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) }
require(contentType?.withoutParameters() == ContentType.Application.Json) {
"Credential issuer responded with invalid content type: " +
"expected ${ContentType.Application.Json} but was $contentType"
}
return response.body<String>()
}
private suspend fun Url.requestSigned(issuerTrust: IssuerTrust, issuer: CredentialIssuerId): String {
val response = getAcceptingContentTypes(CONTENT_TYPE_APPLICATION_JWT)
val contentType = response.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) }
ensure(contentType?.withoutParameters() == CONTENT_TYPE_APPLICATION_JWT) {
CredentialIssuerMetadataError.MissingSignedMetadata()
}
return parseAndVerifySignedMetadata(response.body<String>(), issuerTrust, issuer)
.getOrElse {
throw CredentialIssuerMetadataError.InvalidSignedMetadata(it)
}
}
private suspend fun Url.requestPreferringSigned(issuerTrust: IssuerTrust, issuer: CredentialIssuerId): String {
val response = getAcceptingContentTypes(CONTENT_TYPE_APPLICATION_JWT, ContentType.Application.Json)
val contentType = response.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) }
requireNotNull(contentType) { "Credential issuer did not respond with a content type header" }
return when (contentType.withoutParameters()) {
CONTENT_TYPE_APPLICATION_JWT -> parseAndVerifySignedMetadata(
jwt = response.body<String>(),
issuerTrust = issuerTrust,
issuer = issuer,
).getOrElse {
throw CredentialIssuerMetadataError.InvalidSignedMetadata(it)
}
ContentType.Application.Json -> response.body<String>()
else -> "Unexpected content type $contentType when retrieving issuer metadata."
}
}
/**
* Parses and verifies the signature of a Signed JWT that contains Credential Issuer Metadata.
*
* @param jwt the Signed JWT to parse and verify
* @param issuerTrust trust anchor for the issuer of the signed metadata
* @param issuer the id of the Credential Issuer whose signed metadata to parse
*/
private suspend fun parseAndVerifySignedMetadata(
jwt: String,
issuerTrust: IssuerTrust,
issuer: CredentialIssuerId,
): Result<String> = runCatchingCancellable {
val signedJwt = SignedJWT.parse(jwt)
val processor = DefaultJWTProcessor<SecurityContext>()
.apply {
jwsTypeVerifier = DefaultJOSEObjectTypeVerifier(JOSEObjectType(OpenId4VCISpec.SIGNED_METADATA_JWT_TYPE))
jwsKeySelector = issuerTrust.keySelector(signedJwt)
jwtClaimsSetVerifier =
DefaultJWTClaimsVerifier(
null,
JWTClaimsSet.Builder()
.subject(issuer.value.value.toExternalForm())
.build(),
setOf("iat", "sub"),
)
}
val claimsSet = processor.process(signedJwt, null)
JSONObjectUtils.toJSONString(claimsSet.toJSONObject())
}
private suspend fun IssuerTrust.keySelector(signedJwt: SignedJWT): JWSKeySelector<SecurityContext> {
val jwk = when (this) {
is IssuerTrust.ByPublicKey -> jwk.toPublicJWK()
is IssuerTrust.ByCertificateChain -> {
val certChain = requireNotNull(signedJwt.header.x509CertChain) {
"missing 'x5c' header claim"
}.let { X509CertChainUtils.parse(it) }
require(certificateChainTrust.isTrusted(certChain)) {
"certificate chain in 'x5c' header claim is not trusted"
}
JWK.parse(certChain.first())
}
}
require(jwk is AsymmetricJWK) {
"Metadata signing key should be asymmetric."
}
val algorithm = signedJwt.header.algorithm
return SingleKeyJWSKeySelector(algorithm, jwk.toPublicKey())
}
private suspend fun Url.getAcceptingContentTypes(vararg contentTypes: ContentType): HttpResponse =
try {
val response = httpClient.get(this) {
contentTypes.forEach { accept(it) }
}
require(response.status.isSuccess()) {
"Credential issuer responded with status code: ${response.status}"
}
response
} catch (t: Throwable) {
throw CredentialIssuerMetadataError.UnableToFetchCredentialIssuerMetadata(t)
}
}
internal fun CredentialIssuerId.wellKnown(): Url {
val issuer = Url(this.value.toString())
val pathSegment = buildString {
append(OpenId4VCISpec.CREDENTIAL_ISSUER_WELL_KNOWN_PATH)
val joinedSegments = issuer.segments.joinToString(separator = "/")
if (joinedSegments.isNotBlank()) {
append("/")
}
append(joinedSegments)
}
return URLBuilder(issuer).apply { path(pathSegment) }.build()
}