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

FIWARE / VCVerifier / 18774193082

24 Oct 2025 08:27AM UTC coverage: 42.954% (-0.3%) from 43.214%
18774193082

push

github

web-flow
Merge pull request #68 from FIWARE/default-scope

use defautl scope

7 of 22 new or added lines in 3 files covered. (31.82%)

2 existing lines in 1 file now uncovered.

1588 of 3697 relevant lines covered (42.95%)

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
var apiVerifier verifier.Verifier
40
var presentationParser verifier.PresentationParser
41
var sdJwtParser verifier.SdJwtParser
42
var keyResolver verifier.KeyResolver
43

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

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

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

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

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

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

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

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

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

×
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)
×
185
                return
×
186
        }
×
187
        if !scopeExists {
×
188
                logging.Log().Info("Received an authorization request without a scope.")
×
189
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoScope)
×
190
                return
×
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
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageNoNonce)
×
200
                return
×
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 {
×
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.
242
func GetTokenForService(c *gin.Context) {
×
243

×
244
        logging.Log().Debugf("%v", c.Request)
×
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
×
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"))
×
259
        default:
×
260
                c.AbortWithStatusJSON(http.StatusBadRequest, ErrorMessageUnsupportedGrantType)
×
261
        }
262
}
263

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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