• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

FIWARE / VCVerifier / 25166281377

30 Apr 2026 12:23PM UTC coverage: 59.991% (+0.7%) from 59.25%
25166281377

Pull #96

github

wistefan
Merge pull request 'Ticket #34 - Step 5: Comprehensive tests for refresh token flows' (#6) from ticket-34/step-5 into ticket-34/work

Reviewed-on: http://localhost:3001/general-agent-4/VCVerifier/pulls/6
Reviewed-by: wistefan <wistefan@dev-env.local>
Pull Request #96: Add refresh token support

195 of 248 new or added lines in 5 files covered. (78.63%)

568 existing lines in 10 files now uncovered.

3870 of 6451 relevant lines covered (59.99%)

0.69 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

51.97
/openapi/api_api.go
1
/*
2
 * vcverifier
3
 *
4
 * Backend component to verify credentials
5
 *
6
 * API version: 0.0.1
7
 * Generated by: OpenAPI Generator (https://openapi-generator.tech)
8
 */
9

10
package openapi
11

12
import (
13
        "encoding/base64"
14
        "encoding/json"
15
        "fmt"
16
        "net/http"
17
        "slices"
18
        "strings"
19

20
        "github.com/fiware/VCVerifier/common"
21
        "github.com/fiware/VCVerifier/did"
22
        "github.com/fiware/VCVerifier/logging"
23
        "github.com/fiware/VCVerifier/verifier"
24
        "github.com/google/uuid"
25
        "github.com/lestrrat-go/jwx/v3/jwa"
26
        "github.com/lestrrat-go/jwx/v3/jwt"
27

28
        "github.com/gin-gonic/gin"
29
)
30

31
const DEEPLINK = "DEEPLINK"
32
const FRONTEND_V1 = "FRONTEND_V1"
33
const FRONTEND_V2 = "FRONTEND_V2"
34

35
var apiVerifier verifier.Verifier
36
var presentationParser verifier.PresentationParser
37
var sdJwtParser verifier.SdJwtParser
38
var keyResolver verifier.KeyResolver
39

40
var ErrorMessagNoGrantType = ErrorMessage{"no_grant_type_provided", "Token requests require a grant_type."}
41
var ErrorMessageUnsupportedGrantType = ErrorMessage{"unsupported_grant_type", "Provided grant_type is not supported by the implementation."}
42
var ErrorMessageNoCode = ErrorMessage{"no_code_provided", "Token requests require a code."}
43
var ErrorMessageNoRedircetUri = ErrorMessage{"no_redirect_uri_provided", "Token requests require a redirect_uri."}
44
var ErrorMessageNoResource = ErrorMessage{"no_resource_provided", "When using token-exchange, resource is required to provide the client_id."}
45
var ErrorMessageNoState = ErrorMessage{"no_state_provided", "Authentication requires a state provided as query parameter."}
46
var ErrorMessageNoScope = ErrorMessage{"no_scope_provided", "Authentication requires a scope provided as a parameter."}
47
var ErrorMessageInvalidResponseType = ErrorMessage{"invalid_response_type", "Authentication requires the response_type to be `code`."}
48
var ErrorMessageFailedSameDevice = ErrorMessage{"failed_same_device", "Was not able to start a same-device flow."}
49
var ErrorMessageNoClientId = ErrorMessage{"no_client_id_provided", "Authentication requires a client-id provided as a parameter."}
50
var ErrorMessageNoNonce = ErrorMessage{"no_nonce_provided", "Authentication requires a nonce provided as a query parameter."}
51
var ErrorMessageNoToken = ErrorMessage{"no_token_provided", "Authentication requires a token provided as a form parameter."}
52
var ErrorMessageNoPresentationSubmission = ErrorMessage{"no_presentation_submission_provided", "Authentication requires a presentation submission provided as a form parameter."}
53
var ErrorMessageNoCallback = ErrorMessage{"NoCallbackProvided", "A callback address has to be provided as query-parameter."}
54
var ErrorMessageUnableToDecodeToken = ErrorMessage{"invalid_token", "Token could not be decoded."}
55
var ErrorMessageUnableToDecodeCredential = ErrorMessage{"invalid_token", "Could not read the credential(s) inside the token."}
56
var ErrorMessageUnableToDecodeHolder = ErrorMessage{"invalid_token", "Could not read the holder inside the token."}
57
var ErrorMessageNoSuchSession = ErrorMessage{"no_session", "Session with the requested id is not available."}
58
var ErrorMessageInvalidSdJwt = ErrorMessage{"invalid_sdjwt", "SdJwt does not contain all required fields."}
59
var ErrorMessageNoWebsocketConnection = ErrorMessage{"invalid_connection", "No Websocket connection available for the authenticated session."}
60
var ErrorMessageUnresolvableRequestObject = ErrorMessage{"unresolvable_request_object", "Was not able to get the request object from the client."}
61
var ErrorMessageInvalidAudience = ErrorMessage{"invalid_audience", "Audience of the request object was invalid."}
62
var ErrorMessageUnsupportedAssertionType = ErrorMessage{"unsupported_assertion_type", "Assertion type is not supported."}
63
var ErrorMessageInvalidClientAssertion = ErrorMessage{"invalid_client_assertion", "Provided client assertion is invalid."}
64
var ErrorMessageInvalidTokenRequest = ErrorMessage{"invalid_token_request", "Token request has no redirect_uri and no valid client assertion."}
65
var ErrorMessageInvalidSubjectTokenType = ErrorMessage{"invalid_subject_token_type", "Token exchange is only supported for token type urn:eu:oidf:vp_token."}
66
var ErrorMessageInvalidRequestedTokenType = ErrorMessage{"invalid_requested_token_type", "Token exchange is only supported for requesting tokens of type urn:ietf:params:oauth:token-type:access_token."}
67
var ErrorMessageNoRefreshToken = ErrorMessage{"no_refresh_token_provided", "Refresh token requests require a refresh_token."}
68
var ErrorMessageInvalidRefreshToken = ErrorMessage{"invalid_refresh_token", "The provided refresh token is invalid or expired."}
69

70
func getApiVerifier() verifier.Verifier {
1✔
71
        if apiVerifier == nil {
1✔
UNCOV
72
                apiVerifier = verifier.GetVerifier()
×
73
        }
×
74
        return apiVerifier
1✔
75
}
76

77
func getPresentationParser() verifier.PresentationParser {
1✔
78
        if presentationParser == nil {
1✔
UNCOV
79
                presentationParser = verifier.GetPresentationParser()
×
80
        }
×
81
        return presentationParser
1✔
82
}
83

84
func getSdJwtParser() verifier.SdJwtParser {
1✔
85
        if sdJwtParser == nil {
1✔
UNCOV
86
                sdJwtParser = verifier.GetSdJwtParser()
×
87
        }
×
88
        return sdJwtParser
1✔
89
}
90

UNCOV
91
func getKeyResolver() verifier.KeyResolver {
×
92
        if keyResolver == nil {
×
93
                keyResolver = &verifier.VdrKeyResolver{Vdr: []did.VDR{did.NewKeyVDR(), did.NewJWKVDR(), did.NewWebVDR()}}
×
94
        }
×
95
        return keyResolver
×
96
}
97

98
// GetToken - Token endpoint to exchange the authorization code with the actual JWT.
99
func GetToken(c *gin.Context) {
1✔
100

1✔
101
        logging.Log().Debugf("%v", c.Request)
1✔
102
        grantType, grantTypeExists := c.GetPostForm("grant_type")
1✔
103
        if !grantTypeExists {
2✔
104
                logging.Log().Debug("No grant_type present in the request.")
1✔
105
                c.AbortWithStatusJSON(400, ErrorMessagNoGrantType)
1✔
106
                return
1✔
107
        }
1✔
108

109
        switch grantType {
1✔
110
        case common.TYPE_CODE:
1✔
111
                handleTokenTypeCode(c)
1✔
112
        case common.TYPE_VP_TOKEN:
1✔
113
                handleTokenTypeVPToken(c, c.GetHeader("client_id"))
1✔
114
        case common.TYPE_TOKEN_EXCHANGE:
1✔
115
                resource, resourceExists := c.GetPostForm("resource")
1✔
116
                if !resourceExists {
2✔
117
                        c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoResource)
1✔
118
                        return
1✔
119
                }
1✔
120
                handleTokenTypeTokenExchange(c, resource)
1✔
121
        case common.TYPE_REFRESH_TOKEN:
1✔
122
                handleTokenTypeRefreshToken(c)
1✔
123
        default:
1✔
124
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageUnsupportedGrantType)
1✔
125
        }
126
}
127

UNCOV
128
func AuthorizationEndpoint(c *gin.Context) {
×
UNCOV
129
        logging.Log().Debug("Receive authorization request.")
×
UNCOV
130
        clientId, clientIdExists := c.GetQuery("client_id")
×
131
        responseType, responseTypeExists := c.GetQuery("response_type")
×
132
        scope, scopeExists := c.GetQuery("scope")
×
UNCOV
133
        redirectUri, redirectUriExists := c.GetQuery("redirect_uri")
×
UNCOV
134
        nonce, nonceExists := c.GetQuery("nonce")
×
UNCOV
135
        state, stateExists := c.GetQuery("state")
×
UNCOV
136

×
UNCOV
137
        requestUri, requestUriExists := c.GetQuery("request_uri")
×
138
        if requestUriExists {
×
139
                logging.Log().Debug("Requesting the client for its request object.")
×
140
                cro, err := getRequestObjectClient().GetClientRequestObject(requestUri)
×
141
                if err != nil {
×
142
                        logging.Log().Warnf("Was not able to get request object. Err: %v", err)
×
143
                        c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorMessageUnresolvableRequestObject)
×
144
                        return
×
145
                }
×
146
                if !slices.Contains(cro.Aud, getFrontendVerifier().GetHost()) {
×
147
                        c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorMessageInvalidAudience)
×
148
                        return
×
149
                }
×
150

151
                if cro.ClientId != "" {
×
152
                        clientId = cro.ClientId
×
153
                        clientIdExists = true
×
154
                }
×
155

156
                if cro.Scope != "" {
×
157
                        scope = cro.Scope
×
158
                        scopeExists = true
×
159
                }
×
160

161
                if cro.RedirectUri != "" {
×
162
                        redirectUri = cro.RedirectUri
×
163
                        redirectUriExists = true
×
164
                }
×
165

166
                if cro.Nonce != "" {
×
167
                        nonce = cro.Nonce
×
168
                        nonceExists = true
×
169
                }
×
170

171
                if cro.State != "" {
×
172
                        state = cro.State
×
173
                        stateExists = true
×
174
                }
×
175

176
                if cro.ResponseType != "" {
×
177
                        responseType = cro.ResponseType
×
178
                        responseTypeExists = true
×
179
                }
×
180
        }
181

182
        if !clientIdExists {
×
183
                logging.Log().Info("Received an authorization request without a client_id.")
×
184
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoClientId)
×
UNCOV
185
                return
×
186
        }
×
187
        if !scopeExists {
×
188
                logging.Log().Info("Received an authorization request without a scope.")
×
189
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoScope)
×
UNCOV
190
                return
×
UNCOV
191
        }
×
192
        if !redirectUriExists {
×
193
                logging.Log().Info("Received an authorization request without a redirect_uri.")
×
194
                //c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoRedircetUri)
×
195
                //return
×
196
        }
×
197
        if !nonceExists {
×
198
                logging.Log().Info("Received an authorization request without a nonce.")
×
199
                nonce = uuid.NewString()
×
200
        }
×
201
        if !stateExists {
×
202
                logging.Log().Info("Received an authorization request without a state.")
×
203
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoState)
×
204
                return
×
205
        }
×
206
        if !responseTypeExists && responseType != "code" {
×
207
                logging.Log().Infof("Received an authorization request with an invalid response type. Was %s.", responseType)
×
208
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidResponseType)
×
209
                return
×
210
        }
×
211

212
        logging.Log().Debugf("Received request: clientID - %s, scope - %s, redirect_uri - %s, nonce - %s, state - %s.", clientId, scope, redirectUri, nonce, state)
×
213

×
214
        protocol := "https"
×
215
        if c.Request.TLS == nil {
×
216
                protocol = "http"
×
217
        }
×
218

219
        authorizationType := getApiVerifier().GetAuthorizationType(clientId)
×
220
        var redirect string
×
UNCOV
221
        var err error
×
222
        switch authorizationType {
×
223
        case DEEPLINK:
×
224
                redirect, err = getApiVerifier().StartSameDeviceFlow(c.Request.Host, protocol, state, "", clientId, nonce, verifier.REQUEST_MODE_BY_REFERENCE, scope, verifier.OPENID4VP_PROTOCOL)
×
225
                if err != nil {
×
226
                        logging.Log().Warnf("Was not able start a same device flow. Err: %v", err)
×
227
                        c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorMessageFailedSameDevice)
×
UNCOV
228
                        return
×
229
                }
×
230
        case FRONTEND_V2:
×
231
                redirect = buildFrontendV2Address(protocol, c.Request.Host, state, clientId, redirectUri, scope, nonce)
×
232
        }
233
        c.Redirect(http.StatusFound, redirect)
×
234
}
235

236
func buildFrontendV2Address(protocol, host, state, clientId, redirectUri, scope, nonce string) string {
×
237
        logging.Log().Debugf("%s://%s/api/v2/loginQR?state=%s&client_id=%s&redirect_uri=%s&scope=%s&nonce=%s&request_mode=byReference", protocol, host, state, clientId, redirectUri, scope, nonce)
×
238
        return fmt.Sprintf("%s://%s/api/v2/loginQR?state=%s&client_id=%s&redirect_uri=%s&scope=%s&nonce=%s&request_mode=byReference", protocol, host, state, clientId, redirectUri, scope, nonce)
×
239
}
×
240

241
// GetToken - Token endpoint to exchange the authorization code with the actual JWT.
UNCOV
242
func GetTokenForService(c *gin.Context) {
×
243

×
UNCOV
244
        logging.Log().Debugf("%v", c.Request)
×
UNCOV
245
        grantType, grantTypeExists := c.GetPostForm("grant_type")
×
246
        if !grantTypeExists {
×
247
                logging.Log().Debug("No grant_type present in the request.")
×
248
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessagNoGrantType)
×
249
                return
×
UNCOV
250
        }
×
251

252
        switch grantType {
×
253
        case common.TYPE_CODE:
×
254
                handleTokenTypeCode(c)
×
255
        case common.TYPE_VP_TOKEN:
×
256
                handleTokenTypeVPToken(c, c.Param("service_id"))
×
257
        case common.TYPE_TOKEN_EXCHANGE:
×
258
                handleTokenTypeTokenExchange(c, c.Param("service_id"))
×
NEW
259
        case common.TYPE_REFRESH_TOKEN:
×
NEW
260
                handleTokenTypeRefreshToken(c)
×
UNCOV
261
        default:
×
262
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageUnsupportedGrantType)
×
263
        }
264
}
265

266
func handleTokenTypeTokenExchange(c *gin.Context, clientId string) {
1✔
267
        subjectTokenType, subjectTokenTypeExists := c.GetPostForm("subject_token_type")
1✔
268
        if !subjectTokenTypeExists || subjectTokenType != common.TYPE_VP_TOKEN_SUBJECT {
2✔
269
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidSubjectTokenType)
1✔
270
                return
1✔
271
        }
1✔
272
        requestedTokenType, requestedTokenTypeExists := c.GetPostForm("requested_token_type")
1✔
273
        if requestedTokenTypeExists && requestedTokenType != common.TYPE_ACCESS_TOKEN {
2✔
274
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidRequestedTokenType)
1✔
275
                return
1✔
276
        }
1✔
277

278
        scopes := getScopesFromRequest(c, clientId)
1✔
279

1✔
280
        audience, audienceExists := c.GetPostForm("audience")
1✔
281
        if !audienceExists {
2✔
282
                audience = clientId
1✔
283
        }
1✔
284

285
        subjectToken, subjectTokenExists := c.GetPostForm("subject_token")
1✔
286
        if !subjectTokenExists {
2✔
287
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoToken)
1✔
288
                return
1✔
289
        }
1✔
290

291
        logging.Log().Debugf("Got token %s", subjectToken)
1✔
292

1✔
293
        verifiyVPToken(c, subjectToken, clientId, scopes, audience)
1✔
294
}
295

296
func handleTokenTypeVPToken(c *gin.Context, clientId string) {
1✔
297

1✔
298
        vpToken, vpTokenExists := c.GetPostForm("vp_token")
1✔
299
        if !vpTokenExists {
2✔
300
                logging.Log().Debug("No vp token present in the request.")
1✔
301
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoToken)
1✔
302
                return
1✔
303
        }
1✔
304

305
        logging.Log().Warnf("Got token %s", vpToken)
1✔
306

1✔
307
        scopes := getScopesFromRequest(c, clientId)
1✔
308
        if len(scopes) == 0 {
1✔
UNCOV
309
                return
×
UNCOV
310
        }
×
311

312
        verifiyVPToken(c, vpToken, clientId, scopes, clientId)
1✔
313
}
314

315
func verifiyVPToken(c *gin.Context, vpToken string, clientId string, scopes []string, audience string) {
1✔
316

1✔
317
        presentation, err := extractVpFromToken(c, vpToken)
1✔
318
        if err != nil {
1✔
319
                logging.Log().Warnf("Was not able to extract the credentials from the vp_token. E: %v", err)
×
320
                return
×
UNCOV
321
        }
×
322

323
        logging.Log().Debug("Was able to extract presentation")
1✔
324
        // Subject is empty since multiple VCs with different subjects can be provided
1✔
325
        expiration, signedToken, err := getApiVerifier().GenerateToken(clientId, "", clientId, scopes, presentation)
1✔
326
        if err != nil {
1✔
UNCOV
327
                logging.Log().Error("Failure during generating M2M token: ", err)
×
UNCOV
328
                c.AbortWithStatusJSON(http.StatusBadRequest, err)
×
329
                return
×
330
        }
×
331

332
        var refreshToken string
1✔
333
        if getApiVerifier().IsRefreshTokenEnabled() {
2✔
334
                refreshToken, err = getApiVerifier().CreateRefreshToken(clientId, signedToken)
1✔
335
                if err != nil {
2✔
336
                        logging.Log().Warnf("Failed to create refresh token: %v", err)
1✔
337
                        // Non-fatal: return the access token without a refresh token.
1✔
338
                }
1✔
339
        }
340

341
        response := TokenResponse{TokenType: "Bearer", IssuedTokenType: common.TYPE_ACCESS_TOKEN, ExpiresIn: float32(expiration), IdToken: signedToken, AccessToken: signedToken, Scope: strings.Join(scopes, ","), RefreshToken: refreshToken}
1✔
342
        logging.Log().Infof("Generated and signed token: %v", response)
1✔
343
        c.JSON(http.StatusOK, response)
1✔
344
}
345

346
// handleTokenTypeRefreshToken handles the grant_type=refresh_token flow.
347
// It exchanges a valid refresh token for a new access token and a rotated
348
// refresh token.
349
func handleTokenTypeRefreshToken(c *gin.Context) {
1✔
350
        refreshToken, refreshTokenExists := c.GetPostForm("refresh_token")
1✔
351
        if !refreshTokenExists {
2✔
352
                logging.Log().Debug("No refresh_token present in the request.")
1✔
353
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoRefreshToken)
1✔
354
                return
1✔
355
        }
1✔
356

357
        jwtString, expiration, newRefreshToken, err := getApiVerifier().ExchangeRefreshToken(refreshToken)
1✔
358
        if err != nil {
2✔
359
                logging.Log().Warnf("Failed to exchange refresh token: %v", err)
1✔
360
                c.AbortWithStatusJSON(http.StatusForbidden, ErrorMessageInvalidRefreshToken)
1✔
361
                return
1✔
362
        }
1✔
363

364
        c.JSON(http.StatusOK, TokenResponse{
1✔
365
                TokenType:    "Bearer",
1✔
366
                ExpiresIn:    float32(expiration),
1✔
367
                AccessToken:  jwtString,
1✔
368
                IdToken:      jwtString,
1✔
369
                RefreshToken: newRefreshToken,
1✔
370
        })
1✔
371
}
372

373
func handleTokenTypeCode(c *gin.Context) {
1✔
374

1✔
375
        code, codeExists := c.GetPostForm("code")
1✔
376
        if !codeExists {
2✔
377
                logging.Log().Debug("No code present in the request.")
1✔
378
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoCode)
1✔
379
                return
1✔
380
        }
1✔
381

382
        assertionType, assertionTypeExists := c.GetPostForm("client_assertion_type")
1✔
383
        redirectUri, redirectUriExists := c.GetPostForm("redirect_uri")
1✔
384
        if redirectUriExists {
2✔
385
                jwt, expiration, refreshToken, err := getApiVerifier().GetToken(code, redirectUri, false)
1✔
386
                if err != nil {
2✔
387
                        c.AbortWithStatusJSON(http.StatusForbidden, ErrorMessage{Summary: err.Error()})
1✔
388
                        return
1✔
389
                }
1✔
390
                c.JSON(http.StatusOK, TokenResponse{TokenType: "Bearer", ExpiresIn: float32(expiration), IdToken: jwt, AccessToken: jwt, RefreshToken: refreshToken})
1✔
391
                return
1✔
392
        }
393
        if assertionTypeExists {
1✔
UNCOV
394
                handleWithClientAssertion(c, assertionType, code)
×
UNCOV
395
                return
×
UNCOV
396
        }
×
397
        c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidTokenRequest)
1✔
398
}
399

400
func getScopesFromRequest(c *gin.Context, clientId string) (scopes []string) {
1✔
401

1✔
402
        scope, scopeExists := c.GetPostForm("scope")
1✔
403
        if !scopeExists {
2✔
404
                defaultScope, err := getApiVerifier().GetDefaultScope(clientId)
1✔
405
                if err != nil {
1✔
406
                        c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoScope)
×
UNCOV
407
                        return scopes
×
UNCOV
408
                }
×
409
                logging.Log().Debugf("No scope present in the request, use the default scope %s", defaultScope)
1✔
410
                return []string{defaultScope}
1✔
411
        }
412

413
        return strings.Split(scope, ",")
1✔
414

415
}
416

UNCOV
417
func handleWithClientAssertion(c *gin.Context, assertionType string, code string) {
×
UNCOV
418
        if assertionType != "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" {
×
UNCOV
419
                logging.Log().Warnf("Assertion type %s is not supported.", assertionType)
×
UNCOV
420
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageUnsupportedAssertionType)
×
UNCOV
421
                return
×
422
        }
×
423

424
        clientAssertion, clientAssertionExists := c.GetPostForm("client_assertion")
×
UNCOV
425
        clientId, clientIdExists := c.GetPostForm("client_id")
×
UNCOV
426
        if !clientAssertionExists || !clientIdExists {
×
UNCOV
427
                logging.Log().Warnf("Client Id (%s) or assertion (%s) not provided.", clientId, clientAssertion)
×
UNCOV
428
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageUnsupportedAssertionType)
×
UNCOV
429
                return
×
UNCOV
430
        }
×
431

UNCOV
432
        kid, err := getKeyResolver().ExtractKIDFromJWT(clientAssertion)
×
433
        if err != nil {
×
434
                logging.Log().Warnf("Was not able to retrive kid from token %s. Err: %v.", clientAssertion, err)
×
435
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
436
                return
×
437
        }
×
438
        pubKey, err := getKeyResolver().ResolvePublicKeyFromDID(kid)
×
UNCOV
439
        if err != nil {
×
440
                logging.Log().Warnf("Was not able to retrive key from kid %s. Err: %v.", kid, err)
×
441
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
442
                return
×
443
        }
×
444

445
        alg, algExists := pubKey.Algorithm()
×
446
        if !algExists {
×
UNCOV
447
                // fallback to default
×
448
                alg = jwa.ES256()
×
449
        }
×
450

451
        parsed, err := jwt.Parse([]byte(clientAssertion), jwt.WithKey(alg, pubKey))
×
452
        if err != nil {
×
453
                logging.Log().Warnf("Was not able to parse and verify the token %s. Err: %v", clientAssertion, err)
×
454
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
455
                return
×
456
        }
×
457

458
        // Serialize token to JSON
459
        jsonBytes, err := json.Marshal(parsed)
×
UNCOV
460
        if err != nil {
×
461
                logging.Log().Warnf("Was not able to marshal the token %s. Err: %v", clientAssertion, err)
×
462
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
463
                return
×
464
        }
×
465

466
        // Unmarshal to your struct
467
        var clientAssertionObject ClientAssertion
×
468
        if err := json.Unmarshal(jsonBytes, &clientAssertionObject); err != nil {
×
469
                logging.Log().Warnf("Was not able to unmarshal the token: %s, Err: %v", string(jsonBytes), err)
×
470
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
471
                return
×
472
        }
×
473

UNCOV
474
        if clientAssertionObject.Sub != clientId || clientAssertionObject.Iss != clientId || !slices.Contains(clientAssertionObject.Aud, getFrontendVerifier().GetHost()) {
×
475
                logging.Log().Warnf("Invalid assertion: %s. Client Id: %s, Host: %s", logging.PrettyPrintObject(clientAssertionObject), clientId, getApiVerifier().GetHost())
×
476
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
477
                return
×
478
        }
×
479

NEW
480
        jwt, expiration, refreshToken, err := getApiVerifier().GetToken(code, "", true)
×
UNCOV
481
        if err != nil {
×
UNCOV
482
                c.AbortWithStatusJSON(http.StatusForbidden, ErrorMessage{Summary: err.Error()})
×
483
                return
×
484
        }
×
NEW
485
        c.JSON(http.StatusOK, TokenResponse{TokenType: "Bearer", ExpiresIn: float32(expiration), IdToken: jwt, AccessToken: jwt, RefreshToken: refreshToken})
×
486
}
487

488
// StartSIOPSameDevice - Starts the siop flow for credentials hold by the same device
489
func StartSIOPSameDevice(c *gin.Context) {
1✔
490
        state, stateExists := c.GetQuery("state")
1✔
491
        if !stateExists {
2✔
492
                logging.Log().Debugf("No state was provided.")
1✔
493
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessage{"no_state_provided", "Authentication requires a state provided as query parameter."})
1✔
494
                return
1✔
495
        }
1✔
496
        redirectPath, redirectPathExists := c.GetQuery("redirect_path")
1✔
497
        requestProtocol := verifier.REDIRECT_PROTOCOL
1✔
498
        if !redirectPathExists {
2✔
499
                requestProtocol = verifier.OPENID4VP_PROTOCOL
1✔
500
        }
1✔
501

502
        protocol := "https"
1✔
503
        if c.Request.TLS == nil {
2✔
504
                protocol = "http"
1✔
505
        }
1✔
506

507
        clientId, clientIdExists := c.GetQuery("client_id")
1✔
508
        logging.Log().Debugf("The client id %s", clientId)
1✔
509
        if !clientIdExists {
2✔
510
                logging.Log().Infof("Start a login flow for a not specified client.")
1✔
511
        }
1✔
512

513
        requestMode, requestModeExists := c.GetQuery("request_mode")
1✔
514
        if !requestModeExists {
2✔
515
                logging.Log().Infof("Using default request mode %s.", DEFAULT_REQUEST_MODE)
1✔
516
                requestMode = DEFAULT_REQUEST_MODE
1✔
517
        }
1✔
518

519
        scope, scopeExists := c.GetQuery("scope")
1✔
520
        if !scopeExists {
2✔
521
                logging.Log().Infof("Start a login flow with default scope.")
1✔
522
                scope = ""
1✔
523
        }
1✔
524

525
        authenticationRequest, err := getApiVerifier().StartSameDeviceFlow(c.Request.Host, protocol, state, redirectPath, clientId, "", requestMode, scope, requestProtocol)
1✔
526
        if err != nil {
2✔
527
                logging.Log().Warnf("Error starting the same-device flow. Err: %v", err)
1✔
528
                c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorMessage{err.Error(), "Was not able to start the same device flow."})
1✔
529
                return
1✔
530
        }
1✔
531

532
        c.Redirect(http.StatusFound, authenticationRequest)
1✔
533
}
534

535
// VerifierAPIAuthenticationResponse - Stores the credential for the given session
536
func VerifierAPIAuthenticationResponse(c *gin.Context) {
1✔
537

1✔
538
        var state string
1✔
539
        stateForm, stateFormExists := c.GetPostForm("state")
1✔
540
        stateQuery, stateQueryExists := c.GetQuery("state")
1✔
541
        if !stateFormExists && !stateQueryExists {
2✔
542
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoState)
1✔
543
                return
1✔
544
        }
1✔
545
        if stateFormExists {
2✔
546
                state = stateForm
1✔
547
        } else {
1✔
UNCOV
548
                // allow the state submitted through a query parameter for backwards-compatibility
×
UNCOV
549
                state = stateQuery
×
UNCOV
550
        }
×
551

552
        vptoken, tokenExists := c.GetPostForm("vp_token")
1✔
553
        if !tokenExists {
2✔
554
                logging.Log().Info("No token was provided.")
1✔
555
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoToken)
1✔
556
                return
1✔
557
        }
1✔
558

559
        presentation, err := extractVpFromToken(c, vptoken)
1✔
560
        if err != nil {
1✔
UNCOV
561
                logging.Log().Warnf("Was not able to extract the presentation from the vp_token.")
×
UNCOV
562
                return
×
UNCOV
563
        }
×
564
        handleAuthenticationResponse(c, state, presentation)
1✔
565
}
566

567
// GetVerifierAPIAuthenticationResponse - Stores the credential for the given session
UNCOV
568
func GetVerifierAPIAuthenticationResponse(c *gin.Context) {
×
UNCOV
569
        state, stateExists := c.GetQuery("state")
×
UNCOV
570
        if !stateExists {
×
UNCOV
571
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoState)
×
UNCOV
572
                return
×
UNCOV
573
        }
×
574

UNCOV
575
        vpToken, tokenExists := c.GetQuery("vp_token")
×
UNCOV
576
        if !tokenExists {
×
577
                logging.Log().Info("No token was provided.")
×
578
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoToken)
×
579
                return
×
UNCOV
580
        }
×
UNCOV
581
        presentation, err := extractVpFromToken(c, vpToken)
×
UNCOV
582
        if err != nil {
×
UNCOV
583
                logging.Log().Warnf("Was not able to extract the presentation from the vp_token.")
×
584
                return
×
585
        }
×
586
        handleAuthenticationResponse(c, state, presentation)
×
587
}
588

589
// GetRequestByReference - Get the request object by reference
UNCOV
590
func GetRequestByReference(c *gin.Context) {
×
591
        sessionId := c.Param("id")
×
592

×
593
        jwt, err := verifier.GetVerifier().GetRequestObject(sessionId)
×
594
        if err != nil {
×
595
                logging.Log().Debugf("No request for  %s. Err: %v", sessionId, err)
×
596
                c.AbortWithStatusJSON(http.StatusNotFound, ErrorMessageNoSuchSession)
×
597
                return
×
598
        }
×
599
        c.String(http.StatusOK, jwt)
×
600
}
601

602
func extractVpFromToken(c *gin.Context, vpToken string) (parsedPresentation *common.Presentation, err error) {
1✔
603

1✔
604
        logging.Log().Debugf("The token %s.", vpToken)
1✔
605

1✔
606
        parsedPresentation, err = getPresentationFromQuery(c, vpToken)
1✔
607

1✔
608
        if err != nil {
1✔
609
                logging.Log().Debugf("Received a vpToken with a query, but was not able to extract the presentation. Token: %s", vpToken)
×
610
                return parsedPresentation, err
×
611
        }
×
612
        if parsedPresentation != nil {
1✔
613
                return parsedPresentation, err
×
614
        }
×
615
        return tokenToPresentation(c, vpToken)
1✔
616

617
}
618

619
func tokenToPresentation(c *gin.Context, vpToken string) (parsedPresentation *common.Presentation, err error) {
1✔
620
        tokenBytes := decodeVpString(vpToken)
1✔
621

1✔
622
        isSdJWT, parsedPresentation, err := isSdJWT(c, vpToken)
1✔
623
        if isSdJWT && err != nil {
1✔
UNCOV
624
                return
×
625
        }
×
626
        if isSdJWT {
2✔
627
                logging.Log().Debugf("Received an sdJwt: %s", logging.PrettyPrintObject(parsedPresentation))
1✔
628
                return
1✔
629
        }
1✔
630

631
        parsedPresentation, err = getSdJwtParser().ParseWithSdJwt(tokenBytes)
1✔
632
        if err == nil {
1✔
UNCOV
633
                logging.Log().Debug("Parsed presentation containing sd-jwt's.")
×
UNCOV
634
                return parsedPresentation, err
×
UNCOV
635
        }
×
636
        if err == verifier.ErrorInvalidProof {
1✔
UNCOV
637
                logging.Log().Infof("Was not able to parse the token %s. Err: %v", vpToken, err)
×
UNCOV
638
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageUnableToDecodeToken)
×
UNCOV
639
                return
×
640
        }
×
641
        logging.Log().Debugf("Parse without SD-Jwt %v", err)
1✔
642

1✔
643
        logging.Log().Debug("Parse presentation.")
1✔
644

1✔
645
        parsedPresentation, err = getPresentationParser().ParsePresentation(tokenBytes)
1✔
646

1✔
647
        if err != nil {
1✔
UNCOV
648
                logging.Log().Infof("Was not able to parse the token %s. Err: %v", vpToken, err)
×
649
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageUnableToDecodeToken)
×
650
                return
×
651
        }
×
652

653
        return
1✔
654
}
655

656
func getPresentationFromQuery(c *gin.Context, vpToken string) (parsedPresentation *common.Presentation, err error) {
1✔
657
        tokenBytes := decodeVpString(vpToken)
1✔
658

1✔
659
        var queryMap map[string]string
1✔
660
        //unmarshal
1✔
661
        err = json.Unmarshal(tokenBytes, &queryMap)
1✔
662
        if err != nil {
2✔
663
                logging.Log().Debug("VP Token does not contain query map. Checking the other options.", err)
1✔
664
                return nil, nil
1✔
665
        }
1✔
666

667
        for _, v := range queryMap {
×
UNCOV
668
                p, err := tokenToPresentation(c, v)
×
UNCOV
669
                if err != nil {
×
UNCOV
670
                        return nil, err
×
UNCOV
671
                }
×
UNCOV
672
                if parsedPresentation == nil {
×
UNCOV
673
                        parsedPresentation = p
×
UNCOV
674
                } else {
×
UNCOV
675
                        parsedPresentation.AddCredentials(p.Credentials()...)
×
UNCOV
676
                }
×
677
        }
UNCOV
678
        return parsedPresentation, err
×
679
}
680

681
// checks if the presented token contains a single sd-jwt credential. Will be repackage to a presentation for further validation
682
func isSdJWT(c *gin.Context, vpToken string) (isSdJwt bool, presentation *common.Presentation, err error) {
1✔
683
        claims, err := getSdJwtParser().Parse(vpToken)
1✔
684
        if err != nil {
2✔
685
                logging.Log().Debugf("Was not a sdjwt. Err: %v", err)
1✔
686
                return false, presentation, err
1✔
687
        }
1✔
688
        issuer, i_ok := claims[common.JWTClaimIss]
1✔
689
        vct, vct_ok := claims[common.JWTClaimVct]
1✔
690
        if !i_ok || !vct_ok {
2✔
691
                // Not an SD-JWT VC (missing iss or vct) — let other parsers handle it
1✔
692
                logging.Log().Debugf("Token does not contain issuer(%v) or vct(%v), not an SD-JWT VC.", i_ok, vct_ok)
1✔
693
                return false, presentation, nil
1✔
694
        }
1✔
695
        customFields := common.CustomFields{}
1✔
696
        for k, v := range claims {
2✔
697
                if k != common.JWTClaimIss && k != common.JWTClaimVct {
2✔
698
                        customFields[k] = v
1✔
699
                }
1✔
700
        }
701
        subject := common.Subject{CustomFields: customFields}
1✔
702
        contents := common.CredentialContents{Issuer: &common.Issuer{ID: issuer.(string)}, Types: []string{vct.(string)}, Subject: []common.Subject{subject}}
1✔
703
        credential, err := common.CreateCredential(contents, common.CustomFields{})
1✔
704
        if err != nil {
1✔
UNCOV
705
                logging.Log().Infof("Was not able to create credential from sdJwt. E: %v", err)
×
UNCOV
706
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidSdJwt)
×
UNCOV
707
                return true, presentation, err
×
UNCOV
708
        }
×
709
        presentation, err = common.NewPresentation()
1✔
710
        if err != nil {
1✔
UNCOV
711
                logging.Log().Infof("Was not able to create credpresentation from sdJwt. E: %v", err)
×
UNCOV
712
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidSdJwt)
×
UNCOV
713
                return true, presentation, err
×
UNCOV
714
        }
×
715
        presentation.AddCredentials(credential)
1✔
716
        presentation.Holder = issuer.(string)
1✔
717
        return true, presentation, nil
1✔
718
}
719

720
// decodeVpString - In newer versions of OID4VP the token is not encoded as a whole but only its segments separately. This function covers the older and newer versions
721
func decodeVpString(vpToken string) (tokenBytes []byte) {
1✔
722
        tokenBytes, err := base64.RawURLEncoding.DecodeString(vpToken)
1✔
723
        if err != nil {
2✔
724
                return []byte(vpToken)
1✔
725
        }
1✔
726
        return tokenBytes
1✔
727
}
728

729
func handleAuthenticationResponse(c *gin.Context, state string, presentation *common.Presentation) {
1✔
730

1✔
731
        response, err := getApiVerifier().AuthenticationResponse(state, presentation)
1✔
732
        if err != nil {
2✔
733
                logging.Log().Warnf("Was not able to fullfil the authentication response. Err: %v", err)
1✔
734
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessage{Summary: err.Error()})
1✔
735
                return
1✔
736
        }
1✔
737
        if response != (verifier.Response{}) && response.FlowVersion == verifier.SAME_DEVICE {
2✔
738
                if response.Nonce != "" {
1✔
UNCOV
739
                        c.Redirect(302, fmt.Sprintf("%s?state=%s&code=%s&nonce=%s", response.RedirectTarget, response.SessionId, response.Code, response.Nonce))
×
740
                } else {
1✔
741
                        c.Redirect(302, fmt.Sprintf("%s?state=%s&code=%s", response.RedirectTarget, response.SessionId, response.Code))
1✔
742
                }
1✔
743
                return
1✔
UNCOV
744
        } else if response != (verifier.Response{}) && response.FlowVersion == verifier.CROSS_DEVICE_V2 {
×
UNCOV
745
                sendRedirect(c, response.SessionId, response.Code, response.RedirectTarget)
×
UNCOV
746
        }
×
UNCOV
747
        logging.Log().Debugf("Successfully authenticated %s.", state)
×
UNCOV
748
        c.JSON(http.StatusOK, gin.H{})
×
749
}
750

751
// VerifierAPIJWKS - Provides the public keys for the given verifier, to be used for verifing the JWTs
UNCOV
752
func VerifierAPIJWKS(c *gin.Context) {
×
UNCOV
753
        c.JSON(http.StatusOK, getApiVerifier().GetJWKS())
×
UNCOV
754
}
×
755

756
// VerifierAPIOpenID
UNCOV
757
func VerifierAPIOpenIDConfiguration(c *gin.Context) {
×
UNCOV
758

×
UNCOV
759
        metadata, err := getApiVerifier().GetOpenIDConfiguration(c.Param("service_id"))
×
760
        if err != nil {
×
761
                c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorMessage{err.Error(), "Was not able to generate the OpenID metadata."})
×
762
                return
×
763
        }
×
764
        c.JSON(http.StatusOK, metadata)
×
765
}
766

767
// VerifierAPIStartSIOP - Initiates the siop flow and returns the 'openid://...' connection string
768
func VerifierAPIStartSIOP(c *gin.Context) {
1✔
769
        state, stateExists := c.GetQuery("state")
1✔
770
        if !stateExists {
2✔
771
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoState)
1✔
772
                // early exit
1✔
773
                return
1✔
774
        }
1✔
775

776
        callback, callbackExists := c.GetQuery("client_callback")
1✔
777
        if !callbackExists {
2✔
778
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoCallback)
1✔
779
                // early exit
1✔
780
                return
1✔
781
        }
1✔
782
        protocol := "https"
1✔
783
        if c.Request.TLS == nil {
2✔
784
                protocol = "http"
1✔
785
        }
1✔
786
        clientId, clientIdExists := c.GetQuery("client_id")
1✔
787
        if !clientIdExists {
2✔
788
                logging.Log().Infof("Start a login flow for a not specified client.")
1✔
789
        }
1✔
790

791
        requestMode, requestModeExists := c.GetQuery("request_mode")
1✔
792
        if !requestModeExists {
2✔
793
                logging.Log().Infof("Using default request mode %s.", DEFAULT_REQUEST_MODE)
1✔
794
                requestMode = DEFAULT_REQUEST_MODE
1✔
795
        }
1✔
796

797
        connectionString, err := getApiVerifier().StartSiopFlow(c.Request.Host, protocol, callback, state, clientId, "", requestMode)
1✔
798
        if err != nil {
2✔
799
                c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorMessage{err.Error(), "Was not able to generate the connection string."})
1✔
800
                return
1✔
801
        }
1✔
802
        c.String(http.StatusOK, connectionString)
1✔
803
}
804

805
type ClientAssertion struct {
806
        Iss string   `json:"iss"`
807
        Aud []string `json:"aud"`
808
        Sub string   `json:"sub"`
809
        Exp int      `json:"exp"`
810
        Iat int      `json:"iat"`
811
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc