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

FIWARE / VCVerifier / 18773408824

24 Oct 2025 07:54AM UTC coverage: 43.09% (-0.1%) from 43.214%
18773408824

Pull #68

github

wistefan
use defautl scope
Pull Request #68: use defautl scope

11 of 22 new or added lines in 3 files covered. (50.0%)

4 existing lines in 1 file now uncovered.

1587 of 3683 relevant lines covered (43.09%)

0.49 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/lestrrat-go/jwx/v3/jwa"
25
        "github.com/lestrrat-go/jwx/v3/jwt"
26
        vdr_jwk "github.com/trustbloc/did-go/method/jwk"
27
        vdr_key "github.com/trustbloc/did-go/method/key"
28
        vdr_web "github.com/trustbloc/did-go/method/web"
29
        "github.com/trustbloc/did-go/vdr/api"
30
        "github.com/trustbloc/vc-go/verifiable"
31

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

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

39
const DEFAULT_SCOPE = "openid"
40

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

239
func buildFrontendV2Address(protocol, host, state, clientId, redirectUri, scope, nonce string) string {
×
240
        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)
×
241
}
×
242

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

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

254
        switch grantType {
×
255
        case common.TYPE_CODE:
×
256
                handleTokenTypeCode(c)
×
257
        case common.TYPE_VP_TOKEN:
×
258
                handleTokenTypeVPToken(c, c.Param("service_id"))
×
259
        case common.TYPE_TOKEN_EXCHANGE:
×
260
                handleTokenTypeTokenExchange(c, c.Param("service_id"))
×
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)
1✔
279
        if len(scopes) == 0 {
1✔
UNCOV
280
                return
×
UNCOV
281
        }
×
282

283
        audience, audienceExists := c.GetPostForm("audience")
1✔
284
        if !audienceExists {
2✔
285
                audience = clientId
1✔
286
        }
1✔
287

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

294
        logging.Log().Debugf("Got token %s", subjectToken)
1✔
295

1✔
296
        verifiyVPToken(c, subjectToken, clientId, scopes, audience)
1✔
297
}
298

299
func handleTokenTypeVPToken(c *gin.Context, clientId string) {
1✔
300

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

308
        logging.Log().Warnf("Got token %s", vpToken)
1✔
309

1✔
310
        scopes := getScopesFromRequest(c)
1✔
311
        if len(scopes) == 0 {
1✔
UNCOV
312
                return
×
UNCOV
313
        }
×
314

315
        verifiyVPToken(c, vpToken, clientId, scopes, clientId)
1✔
316
}
317

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

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

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

339
func handleTokenTypeCode(c *gin.Context) {
1✔
340

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

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

366
func getScopesFromRequest(c *gin.Context) (scopes []string) {
1✔
367

1✔
368
        scope, scopeExists := c.GetPostForm("scope")
1✔
369
        if !scopeExists {
2✔
370
                logging.Log().Debugf("No scope present in the request, use the default scope %s", DEFAULT_SCOPE)
1✔
371
                return []string{DEFAULT_SCOPE}
1✔
372
        }
1✔
373

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

376
}
377

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

578
}
579

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

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

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

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

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

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

614
        return
1✔
615
}
616

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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