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

FIWARE / VCVerifier / 22628817567

03 Mar 2026 02:59PM UTC coverage: 44.11% (+0.2%) from 43.895%
22628817567

Pull #80

github

wistefan
Merge remote-tracking branch 'origin/authenticon-2' into authenticon-2
Pull Request #80: make nonce optional and improve jwt mapping

12 of 39 new or added lines in 3 files covered. (30.77%)

79 existing lines in 1 file now uncovered.

1685 of 3820 relevant lines covered (44.11%)

0.5 hits per line

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

50.26
/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
        "errors"
16
        "fmt"
17
        "net/http"
18
        "slices"
19
        "strings"
20

21
        "github.com/fiware/VCVerifier/common"
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
        vdr_jwk "github.com/trustbloc/did-go/method/jwk"
28
        vdr_key "github.com/trustbloc/did-go/method/key"
29
        vdr_web "github.com/trustbloc/did-go/method/web"
30
        "github.com/trustbloc/did-go/vdr/api"
31
        "github.com/trustbloc/vc-go/verifiable"
32

33
        "github.com/gin-gonic/gin"
34
)
35

36
const DEEPLINK = "DEEPLINK"
37
const FRONTEND_V1 = "FRONTEND_V1"
38
const FRONTEND_V2 = "FRONTEND_V2"
39

40
var apiVerifier verifier.Verifier
41
var presentationParser verifier.PresentationParser
42
var sdJwtParser verifier.SdJwtParser
43
var keyResolver verifier.KeyResolver
44

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

73
func getApiVerifier() verifier.Verifier {
1✔
74
        if apiVerifier == nil {
1✔
75
                apiVerifier = verifier.GetVerifier()
×
76
        }
×
77
        return apiVerifier
1✔
78
}
79

80
func getPresentationParser() verifier.PresentationParser {
1✔
81
        if presentationParser == nil {
1✔
82
                presentationParser = verifier.GetPresentationParser()
×
83
        }
×
84
        return presentationParser
1✔
85
}
86

87
func getSdJwtParser() verifier.SdJwtParser {
1✔
88
        if sdJwtParser == nil {
1✔
89
                sdJwtParser = verifier.GetSdJwtParser()
×
90
        }
×
91
        return sdJwtParser
1✔
92
}
93

94
func getKeyResolver() verifier.KeyResolver {
×
95
        if keyResolver == nil {
×
96
                keyResolver = &verifier.VdrKeyResolver{Vdr: []api.VDR{vdr_key.New(), vdr_jwk.New(), vdr_web.New()}}
×
97
        }
×
98
        return keyResolver
×
99
}
100

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

237
func buildFrontendV2Address(protocol, host, state, clientId, redirectUri, scope, nonce string) string {
×
NEW
238
        logging.Log().Warn(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
        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)
×
240
}
×
241

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

322
        logging.Log().Debug("Was able to extract presentation")
1✔
323
        // Subject is empty since multiple VCs with different subjects can be provided
1✔
324
        expiration, signedToken, err := getApiVerifier().GenerateToken(clientId, "", clientId, scopes, presentation)
1✔
325
        if err != nil {
1✔
326
                logging.Log().Error("Failure during generating M2M token: ", err)
×
327
                c.AbortWithStatusJSON(http.StatusBadRequest, err)
×
328
                return
×
329
        }
×
330
        response := TokenResponse{TokenType: "Bearer", IssuedTokenType: common.TYPE_ACCESS_TOKEN, ExpiresIn: float32(expiration), AccessToken: signedToken, Scope: strings.Join(scopes, ",")}
1✔
331
        logging.Log().Infof("Generated and signed token: %v", response)
1✔
332
        c.JSON(http.StatusOK, response)
1✔
333
}
334

335
func handleTokenTypeCode(c *gin.Context) {
1✔
336

1✔
337
        code, codeExists := c.GetPostForm("code")
1✔
338
        if !codeExists {
2✔
339
                logging.Log().Debug("No code present in the request.")
1✔
340
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoCode)
1✔
341
                return
1✔
342
        }
1✔
343

344
        assertionType, assertionTypeExists := c.GetPostForm("client_assertion_type")
1✔
345
        redirectUri, redirectUriExists := c.GetPostForm("redirect_uri")
1✔
346
        if redirectUriExists {
2✔
347
                jwt, expiration, err := getApiVerifier().GetToken(code, redirectUri, false)
1✔
348
                if err != nil {
2✔
349
                        c.AbortWithStatusJSON(http.StatusForbidden, ErrorMessage{Summary: err.Error()})
1✔
350
                        return
1✔
351
                }
1✔
352
                c.JSON(http.StatusOK, TokenResponse{TokenType: "Bearer", ExpiresIn: float32(expiration), AccessToken: jwt})
1✔
353
                return
1✔
354
        }
355
        if assertionTypeExists {
1✔
356
                handleWithClientAssertion(c, assertionType, code)
×
357
                return
×
358
        }
×
359
        c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidTokenRequest)
1✔
360
}
361

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

1✔
364
        scope, scopeExists := c.GetPostForm("scope")
1✔
365
        if !scopeExists {
2✔
366
                defaultScope, err := getApiVerifier().GetDefaultScope(clientId)
1✔
367
                if err != nil {
1✔
368
                        c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoScope)
×
369
                        return scopes
×
370
                }
×
371
                logging.Log().Debugf("No scope present in the request, use the default scope %s", defaultScope)
1✔
372
                return []string{defaultScope}
1✔
373
        }
374

375
        return strings.Split(scope, ",")
1✔
376

377
}
378

379
func handleWithClientAssertion(c *gin.Context, assertionType string, code string) {
×
380
        if assertionType != "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" {
×
381
                logging.Log().Warnf("Assertion type %s is not supported.", assertionType)
×
382
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageUnsupportedAssertionType)
×
383
                return
×
384
        }
×
385

386
        clientAssertion, clientAssertionExists := c.GetPostForm("client_assertion")
×
387
        clientId, clientIdExists := c.GetPostForm("client_id")
×
388
        if !clientAssertionExists || !clientIdExists {
×
389
                logging.Log().Warnf("Client Id (%s) or assertion (%s) not provided.", clientId, clientAssertion)
×
390
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageUnsupportedAssertionType)
×
391
                return
×
392
        }
×
393

394
        kid, err := getKeyResolver().ExtractKIDFromJWT(clientAssertion)
×
395
        if err != nil {
×
396
                logging.Log().Warnf("Was not able to retrive kid from token %s. Err: %v.", clientAssertion, err)
×
397
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
398
                return
×
399
        }
×
400
        pubKey, err := getKeyResolver().ResolvePublicKeyFromDID(kid)
×
401
        if err != nil {
×
402
                logging.Log().Warnf("Was not able to retrive key from kid %s. Err: %v.", kid, err)
×
403
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
404
                return
×
405
        }
×
406

407
        alg, algExists := pubKey.Algorithm()
×
408
        if !algExists {
×
409
                // fallback to default
×
410
                alg = jwa.ES256()
×
411
        }
×
412

413
        parsed, err := jwt.Parse([]byte(clientAssertion), jwt.WithKey(alg, pubKey))
×
414
        if err != nil {
×
415
                logging.Log().Warnf("Was not able to parse and verify the token %s. Err: %v", clientAssertion, err)
×
416
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
417
                return
×
418
        }
×
419

420
        // Serialize token to JSON
421
        jsonBytes, err := json.Marshal(parsed)
×
422
        if err != nil {
×
423
                logging.Log().Warnf("Was not able to marshal the token %s. Err: %v", clientAssertion, err)
×
424
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
425
                return
×
426
        }
×
427

428
        // Unmarshal to your struct
429
        var clientAssertionObject ClientAssertion
×
430
        if err := json.Unmarshal(jsonBytes, &clientAssertionObject); err != nil {
×
431
                logging.Log().Warnf("Was not able to unmarshal the token: %s, Err: %v", string(jsonBytes), err)
×
432
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
433
                return
×
434
        }
×
435

436
        if clientAssertionObject.Sub != clientId || clientAssertionObject.Iss != clientId || !slices.Contains(clientAssertionObject.Aud, getFrontendVerifier().GetHost()) {
×
437
                logging.Log().Warnf("Invalid assertion: %s. Client Id: %s, Host: %s", logging.PrettyPrintObject(clientAssertionObject), clientId, getApiVerifier().GetHost())
×
438
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidClientAssertion)
×
439
                return
×
440
        }
×
441

442
        jwt, expiration, err := getApiVerifier().GetToken(code, "", true)
×
443
        if err != nil {
×
444
                c.AbortWithStatusJSON(http.StatusForbidden, ErrorMessage{Summary: err.Error()})
×
445
                return
×
446
        }
×
447
        c.JSON(http.StatusOK, TokenResponse{TokenType: "Bearer", ExpiresIn: float32(expiration), AccessToken: jwt})
×
448
}
449

450
// StartSIOPSameDevice - Starts the siop flow for credentials hold by the same device
451
func StartSIOPSameDevice(c *gin.Context) {
1✔
452
        state, stateExists := c.GetQuery("state")
1✔
453
        if !stateExists {
2✔
454
                logging.Log().Debugf("No state was provided.")
1✔
455
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessage{"no_state_provided", "Authentication requires a state provided as query parameter."})
1✔
456
                return
1✔
457
        }
1✔
458
        redirectPath, redirectPathExists := c.GetQuery("redirect_path")
1✔
459
        requestProtocol := verifier.REDIRECT_PROTOCOL
1✔
460
        if !redirectPathExists {
2✔
461
                requestProtocol = verifier.OPENID4VP_PROTOCOL
1✔
462
        }
1✔
463

464
        protocol := "https"
1✔
465
        if c.Request.TLS == nil {
2✔
466
                protocol = "http"
1✔
467
        }
1✔
468

469
        clientId, clientIdExists := c.GetQuery("client_id")
1✔
470
        logging.Log().Debugf("The client id %s", clientId)
1✔
471
        if !clientIdExists {
2✔
472
                logging.Log().Infof("Start a login flow for a not specified client.")
1✔
473
        }
1✔
474

475
        requestMode, requestModeExists := c.GetQuery("request_mode")
1✔
476
        if !requestModeExists {
2✔
477
                logging.Log().Infof("Using default request mode %s.", DEFAULT_REQUEST_MODE)
1✔
478
                requestMode = DEFAULT_REQUEST_MODE
1✔
479
        }
1✔
480

481
        scope, scopeExists := c.GetQuery("scope")
1✔
482
        if !scopeExists {
2✔
483
                logging.Log().Infof("Start a login flow with default scope.")
1✔
484
                scope = ""
1✔
485
        }
1✔
486

487
        authenticationRequest, err := getApiVerifier().StartSameDeviceFlow(c.Request.Host, protocol, state, redirectPath, clientId, "", requestMode, scope, requestProtocol)
1✔
488
        if err != nil {
2✔
489
                logging.Log().Warnf("Error starting the same-device flow. Err: %v", err)
1✔
490
                c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorMessage{err.Error(), "Was not able to start the same device flow."})
1✔
491
                return
1✔
492
        }
1✔
493

494
        c.Redirect(http.StatusFound, authenticationRequest)
1✔
495
}
496

497
// VerifierAPIAuthenticationResponse - Stores the credential for the given session
498
func VerifierAPIAuthenticationResponse(c *gin.Context) {
1✔
499

1✔
500
        var state string
1✔
501
        stateForm, stateFormExists := c.GetPostForm("state")
1✔
502
        stateQuery, stateQueryExists := c.GetQuery("state")
1✔
503
        if !stateFormExists && !stateQueryExists {
2✔
504
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoState)
1✔
505
                return
1✔
506
        }
1✔
507
        if stateFormExists {
2✔
508
                state = stateForm
1✔
509
        } else {
1✔
510
                // allow the state submitted through a query parameter for backwards-compatibility
×
511
                state = stateQuery
×
512
        }
×
513

514
        vptoken, tokenExists := c.GetPostForm("vp_token")
1✔
515
        if !tokenExists {
2✔
516
                logging.Log().Info("No token was provided.")
1✔
517
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoToken)
1✔
518
                return
1✔
519
        }
1✔
520

521
        presentation, err := extractVpFromToken(c, vptoken)
1✔
522
        if err != nil {
2✔
523
                logging.Log().Warnf("Was not able to extract the presentation from the vp_token.")
1✔
524
                return
1✔
525
        }
1✔
526
        handleAuthenticationResponse(c, state, presentation)
1✔
527
}
528

529
// GetVerifierAPIAuthenticationResponse - Stores the credential for the given session
530
func GetVerifierAPIAuthenticationResponse(c *gin.Context) {
×
531
        state, stateExists := c.GetQuery("state")
×
532
        if !stateExists {
×
533
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoState)
×
534
                return
×
535
        }
×
536

537
        vpToken, tokenExists := c.GetQuery("vp_token")
×
538
        if !tokenExists {
×
539
                logging.Log().Info("No token was provided.")
×
540
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoToken)
×
541
                return
×
542
        }
×
543
        presentation, err := extractVpFromToken(c, vpToken)
×
544
        if err != nil {
×
545
                logging.Log().Warnf("Was not able to extract the presentation from the vp_token.")
×
546
                return
×
547
        }
×
548
        handleAuthenticationResponse(c, state, presentation)
×
549
}
550

551
// GetRequestByReference - Get the request object by reference
552
func GetRequestByReference(c *gin.Context) {
×
553
        sessionId := c.Param("id")
×
554

×
555
        jwt, err := verifier.GetVerifier().GetRequestObject(sessionId)
×
556
        if err != nil {
×
557
                logging.Log().Debugf("No request for  %s. Err: %v", sessionId, err)
×
558
                c.AbortWithStatusJSON(http.StatusNotFound, ErrorMessageNoSuchSession)
×
559
                return
×
560
        }
×
561
        c.String(http.StatusOK, jwt)
×
562
}
563

564
func extractVpFromToken(c *gin.Context, vpToken string) (parsedPresentation *verifiable.Presentation, err error) {
1✔
565

1✔
566
        logging.Log().Debugf("The token %s.", vpToken)
1✔
567

1✔
568
        parsedPresentation, err = getPresentationFromQuery(c, vpToken)
1✔
569

1✔
570
        if err != nil {
1✔
571
                logging.Log().Debugf("Received a vpToken with a query, but was not able to extract the presentation. Token: %s", vpToken)
×
572
                return parsedPresentation, err
×
573
        }
×
574
        if parsedPresentation != nil {
1✔
575
                return parsedPresentation, err
×
576
        }
×
577
        return tokenToPresentation(c, vpToken)
1✔
578

579
}
580

581
func tokenToPresentation(c *gin.Context, vpToken string) (parsedPresentation *verifiable.Presentation, err error) {
1✔
582
        tokenBytes := decodeVpString(vpToken)
1✔
583

1✔
584
        isSdJWT, parsedPresentation, err := isSdJWT(c, vpToken)
1✔
585
        if isSdJWT && err != nil {
1✔
586
                return
×
587
        }
×
588
        if isSdJWT {
2✔
589
                logging.Log().Debugf("Received an sdJwt: %s", logging.PrettyPrintObject(parsedPresentation))
1✔
590
                return
1✔
591
        }
1✔
592

593
        parsedPresentation, err = getSdJwtParser().ParseWithSdJwt(tokenBytes)
1✔
594
        if err == nil {
1✔
595
                logging.Log().Debug("Parsed presentation containing sd-jwt's.")
×
596
                return parsedPresentation, err
×
597
        }
×
598
        if err == verifier.ErrorInvalidProof {
1✔
599
                logging.Log().Infof("Was not able to parse the token %s. Err: %v", vpToken, err)
×
600
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageUnableToDecodeToken)
×
601
                return
×
602
        }
×
603
        logging.Log().Debugf("Parse without SD-Jwt %v", err)
1✔
604

1✔
605
        logging.Log().Debug("Parse presentation.")
1✔
606

1✔
607
        parsedPresentation, err = getPresentationParser().ParsePresentation(tokenBytes)
1✔
608

1✔
609
        if err != nil {
2✔
610
                logging.Log().Infof("Was not able to parse the token %s. Err: %v", vpToken, err)
1✔
611
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageUnableToDecodeToken)
1✔
612
                return
1✔
613
        }
1✔
614

615
        return
1✔
616
}
617

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

1✔
621
        var queryMap map[string]string
1✔
622
        //unmarshal
1✔
623
        err = json.Unmarshal(tokenBytes, &queryMap)
1✔
624
        if err != nil {
2✔
625
                logging.Log().Debug("VP Token does not contain query map. Checking the other options.", err)
1✔
626
                return nil, nil
1✔
627
        }
1✔
628

629
        for _, v := range queryMap {
×
630
                p, err := tokenToPresentation(c, v)
×
631
                if err != nil {
×
632
                        return nil, err
×
633
                }
×
634
                if parsedPresentation == nil {
×
635
                        parsedPresentation = p
×
636
                } else {
×
637
                        parsedPresentation.AddCredentials(p.Credentials()...)
×
638
                }
×
639
        }
640
        return parsedPresentation, err
×
641
}
642

643
// checks if the presented token contains a single sd-jwt credential. Will be repackage to a presentation for further validation
644
func isSdJWT(c *gin.Context, vpToken string) (isSdJwt bool, presentation *verifiable.Presentation, err error) {
1✔
645
        claims, err := getSdJwtParser().Parse(vpToken)
1✔
646
        if err != nil {
2✔
647
                logging.Log().Debugf("Was not a sdjwt. Err: %v", err)
1✔
648
                return false, presentation, err
1✔
649
        }
1✔
650
        issuer, i_ok := claims["iss"]
1✔
651
        vct, vct_ok := claims["vct"]
1✔
652
        if !i_ok || !vct_ok {
1✔
653
                logging.Log().Infof("Token does not contain issuer(%v) or vct(%v).", i_ok, vct_ok)
×
654
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidSdJwt)
×
655
                return true, presentation, errors.New(ErrorMessageInvalidSdJwt.Summary)
×
656
        }
×
657
        customFields := verifiable.CustomFields{}
1✔
658
        for k, v := range claims {
2✔
659
                if k != "iss" && k != "vct" {
2✔
660
                        customFields[k] = v
1✔
661
                }
1✔
662
        }
663
        subject := verifiable.Subject{CustomFields: customFields}
1✔
664
        contents := verifiable.CredentialContents{Issuer: &verifiable.Issuer{ID: issuer.(string)}, Types: []string{vct.(string)}, Subject: []verifiable.Subject{subject}}
1✔
665
        credential, err := verifiable.CreateCredential(contents, verifiable.CustomFields{})
1✔
666
        if err != nil {
1✔
667
                logging.Log().Infof("Was not able to create credential from sdJwt. E: %v", err)
×
668
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidSdJwt)
×
669
                return true, presentation, err
×
670
        }
×
671
        presentation, err = verifiable.NewPresentation()
1✔
672
        if err != nil {
1✔
673
                logging.Log().Infof("Was not able to create credpresentation from sdJwt. E: %v", err)
×
674
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageInvalidSdJwt)
×
675
                return true, presentation, err
×
676
        }
×
677
        presentation.AddCredentials(credential)
1✔
678
        presentation.Holder = issuer.(string)
1✔
679
        return true, presentation, nil
1✔
680
}
681

682
// 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
683
func decodeVpString(vpToken string) (tokenBytes []byte) {
1✔
684
        tokenBytes, err := base64.RawURLEncoding.DecodeString(vpToken)
1✔
685
        if err != nil {
2✔
686
                return []byte(vpToken)
1✔
687
        }
1✔
688
        return tokenBytes
1✔
689
}
690

691
func handleAuthenticationResponse(c *gin.Context, state string, presentation *verifiable.Presentation) {
1✔
692

1✔
693
        response, err := getApiVerifier().AuthenticationResponse(state, presentation)
1✔
694
        if err != nil {
2✔
695
                logging.Log().Warnf("Was not able to fullfil the authentication response. Err: %v", err)
1✔
696
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessage{Summary: err.Error()})
1✔
697
                return
1✔
698
        }
1✔
699
        if response != (verifier.Response{}) && response.FlowVersion == verifier.SAME_DEVICE {
2✔
700
                if response.Nonce != "" {
1✔
701
                        c.Redirect(302, fmt.Sprintf("%s?state=%s&code=%s&nonce=%s", response.RedirectTarget, response.SessionId, response.Code, response.Nonce))
×
702
                } else {
1✔
703
                        c.Redirect(302, fmt.Sprintf("%s?state=%s&code=%s", response.RedirectTarget, response.SessionId, response.Code))
1✔
704
                }
1✔
705
                return
1✔
706
        } else if response != (verifier.Response{}) && response.FlowVersion == verifier.CROSS_DEVICE_V2 {
×
707
                sendRedirect(c, response.SessionId, response.Code, response.RedirectTarget)
×
708
        }
×
709
        logging.Log().Debugf("Successfully authenticated %s.", state)
×
710
        c.JSON(http.StatusOK, gin.H{})
×
711
}
712

713
// VerifierAPIJWKS - Provides the public keys for the given verifier, to be used for verifing the JWTs
714
func VerifierAPIJWKS(c *gin.Context) {
×
715
        c.JSON(http.StatusOK, getApiVerifier().GetJWKS())
×
716
}
×
717

718
// VerifierAPIOpenID
719
func VerifierAPIOpenIDConfiguration(c *gin.Context) {
×
720

×
721
        metadata, err := getApiVerifier().GetOpenIDConfiguration(c.Param("service_id"))
×
722
        if err != nil {
×
723
                c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorMessage{err.Error(), "Was not able to generate the OpenID metadata."})
×
724
                return
×
725
        }
×
726
        c.JSON(http.StatusOK, metadata)
×
727
}
728

729
// VerifierAPIStartSIOP - Initiates the siop flow and returns the 'openid://...' connection string
730
func VerifierAPIStartSIOP(c *gin.Context) {
1✔
731
        state, stateExists := c.GetQuery("state")
1✔
732
        if !stateExists {
2✔
733
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoState)
1✔
734
                // early exit
1✔
735
                return
1✔
736
        }
1✔
737

738
        callback, callbackExists := c.GetQuery("client_callback")
1✔
739
        if !callbackExists {
2✔
740
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoCallback)
1✔
741
                // early exit
1✔
742
                return
1✔
743
        }
1✔
744
        protocol := "https"
1✔
745
        if c.Request.TLS == nil {
2✔
746
                protocol = "http"
1✔
747
        }
1✔
748
        clientId, clientIdExists := c.GetQuery("client_id")
1✔
749
        if !clientIdExists {
2✔
750
                logging.Log().Infof("Start a login flow for a not specified client.")
1✔
751
        }
1✔
752

753
        requestMode, requestModeExists := c.GetQuery("request_mode")
1✔
754
        if !requestModeExists {
2✔
755
                logging.Log().Infof("Using default request mode %s.", DEFAULT_REQUEST_MODE)
1✔
756
                requestMode = DEFAULT_REQUEST_MODE
1✔
757
        }
1✔
758

759
        connectionString, err := getApiVerifier().StartSiopFlow(c.Request.Host, protocol, callback, state, clientId, "", requestMode)
1✔
760
        if err != nil {
2✔
761
                c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorMessage{err.Error(), "Was not able to generate the connection string."})
1✔
762
                return
1✔
763
        }
1✔
764
        c.String(http.StatusOK, connectionString)
1✔
765
}
766

767
type ClientAssertion struct {
768
        Iss string   `json:"iss"`
769
        Aud []string `json:"aud"`
770
        Sub string   `json:"sub"`
771
        Exp int      `json:"exp"`
772
        Iat int      `json:"iat"`
773
}
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