-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathapi.go
More file actions
1046 lines (957 loc) · 40.4 KB
/
api.go
File metadata and controls
1046 lines (957 loc) · 40.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2023 Nuts community
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
package iam
import (
"bytes"
"context"
"crypto"
"crypto/sha256"
"embed"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"html/template"
"net/http"
"net/url"
"slices"
"strings"
"time"
"github.com/nuts-foundation/nuts-node/core/to"
"github.com/labstack/echo/v4"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/lestrrat-go/jwx/v2/jwt"
"github.com/nuts-foundation/go-did/did"
"github.com/nuts-foundation/nuts-node/audit"
"github.com/nuts-foundation/nuts-node/auth"
"github.com/nuts-foundation/nuts-node/auth/api/iam/assets"
iamclient "github.com/nuts-foundation/nuts-node/auth/client/iam"
"github.com/nuts-foundation/nuts-node/auth/log"
"github.com/nuts-foundation/nuts-node/auth/oauth"
"github.com/nuts-foundation/nuts-node/core"
nutsCrypto "github.com/nuts-foundation/nuts-node/crypto"
nutsHttp "github.com/nuts-foundation/nuts-node/http"
"github.com/nuts-foundation/nuts-node/http/cache"
"github.com/nuts-foundation/nuts-node/http/user"
"github.com/nuts-foundation/nuts-node/jsonld"
"github.com/nuts-foundation/nuts-node/policy"
"github.com/nuts-foundation/nuts-node/storage"
"github.com/nuts-foundation/nuts-node/vcr"
"github.com/nuts-foundation/nuts-node/vcr/pe"
"github.com/nuts-foundation/nuts-node/vdr/didsubject"
"github.com/nuts-foundation/nuts-node/vdr/resolver"
)
var _ core.Routable = &Wrapper{}
var _ StrictServerInterface = &Wrapper{}
var oauthRequestObjectKey = []string{"oauth", "requestobject"}
const apiPath = "iam"
const apiModuleName = auth.ModuleName + "/" + apiPath
type httpRequestContextKey struct{}
// accessTokenValidity defines how long access tokens are valid.
// TODO: Might want to make this configurable at some point
const accessTokenValidity = 15 * time.Minute
// accessTokenCacheOffset is used to reduce the ttl of the access token to ensure it is still valid when the client receives it.
// this to offset clock skew and roundtrip times
const accessTokenCacheOffset = 30 * time.Second
// cacheControlMaxAgeURLs holds API endpoints that should have a max-age cache control header set.
var cacheControlMaxAgeURLs = []string{
"/oauth2/:subjectID/presentation_definition",
"/.well-known/oauth-authorization-server/oauth2/:subjectID",
"/.well-known/openid-configuration/oauth2/:subjectID",
"/oauth2/:subjectID/oauth-client",
"/statuslist/:did/:page",
}
// cacheControlNoCacheURLs holds API endpoints that should have a no-cache cache control header set.
var cacheControlNoCacheURLs = []string{
"/oauth2/:subjectID/token",
}
type TokenIntrospectionResponse = ExtendedTokenIntrospectionResponse
//go:embed assets
var assetsFS embed.FS
// Wrapper handles OAuth2 flows.
type Wrapper struct {
auth auth.AuthenticationServices
policyBackend policy.PDPBackend
storageEngine storage.Engine
jsonldManager jsonld.JSONLD
vcr vcr.VCR
jwtSigner nutsCrypto.JWTSigner
keyResolver resolver.KeyResolver
subjectManager didsubject.Manager
jar JAR
}
func New(
authInstance auth.AuthenticationServices, vcrInstance vcr.VCR, didKeyResolver resolver.DIDKeyResolver, subjectManager didsubject.Manager, storageEngine storage.Engine,
policyBackend policy.PDPBackend, jwtSigner nutsCrypto.JWTSigner, jsonldManager jsonld.JSONLD) *Wrapper {
templates := template.New("oauth2 templates")
_, err := templates.ParseFS(assetsFS, "assets/*.html")
if err != nil {
panic(err)
}
return &Wrapper{
auth: authInstance,
policyBackend: policyBackend,
storageEngine: storageEngine,
vcr: vcrInstance,
subjectManager: subjectManager,
jsonldManager: jsonldManager,
jwtSigner: jwtSigner,
keyResolver: didKeyResolver,
jar: jar{
auth: authInstance,
jwtSigner: jwtSigner,
keyResolver: didKeyResolver,
},
}
}
func (r Wrapper) Routes(router core.EchoRouter) {
RegisterHandlers(router, NewStrictHandler(r, []StrictMiddlewareFunc{
func(f StrictHandlerFunc, operationID string) StrictHandlerFunc {
return func(ctx echo.Context, request interface{}) (response interface{}, err error) {
return r.strictMiddleware(ctx, request, operationID, f)
}
},
func(f StrictHandlerFunc, operationID string) StrictHandlerFunc {
return audit.StrictMiddleware(f, apiModuleName, operationID)
},
}))
// The following handlers are used for the user facing OAuth2 flows.
router.GET("/oauth2/:subjectID/user", r.handleUserLanding, func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
middleware(c, "handleUserLanding")
return next(c)
}
}, audit.Middleware(apiModuleName))
router.Use(cache.MaxAge(5*time.Minute, cacheControlMaxAgeURLs...).Handle)
router.Use(cache.NoCache(cacheControlNoCacheURLs...).Handle)
router.Use(user.SessionMiddleware{
Skipper: func(c echo.Context) bool {
// The following URLs require a user session:
paths := []string{
"/oauth2/:subjectID/user",
"/oauth2/:subjectID/authorize",
"/oauth2/:subjectID/callback",
}
for _, path := range paths {
if c.Path() == path {
return false
}
}
return true
},
TimeOut: time.Hour,
Store: r.storageEngine.GetSessionDatabase().GetStore(time.Hour, "user", "session"),
CookiePath: func(subjectID string) string {
baseURL := r.subjectToBaseURL(subjectID)
return baseURL.Path
},
}.Handle)
}
func (r Wrapper) strictMiddleware(ctx echo.Context, request interface{}, operationID string, f StrictHandlerFunc) (interface{}, error) {
middleware(ctx, operationID)
ctx.Set(core.StatusCodeResolverContextKey, r)
return f(ctx, request)
}
func middleware(ctx echo.Context, operationID string) {
ctx.Set(core.OperationIDContextKey, operationID)
ctx.Set(core.ModuleNameContextKey, apiModuleName)
// Add http.Request to context, to allow reading URL query parameters
requestCtx := context.WithValue(ctx.Request().Context(), httpRequestContextKey{}, ctx.Request())
ctx.SetRequest(ctx.Request().WithContext(requestCtx))
if strings.HasPrefix(ctx.Request().URL.Path, "/oauth2/") {
ctx.Set(core.ErrorWriterContextKey, &oauth.Oauth2ErrorWriter{
HtmlPageTemplate: assets.ErrorTemplate,
})
}
}
// ResolveStatusCode maps errors returned by this API to specific HTTP status codes.
func (r Wrapper) ResolveStatusCode(err error) int {
return core.ResolveStatusCode(err, map[error]int{
resolver.ErrDIDNotManagedByThisNode: http.StatusBadRequest,
pe.ErrNoCredentials: http.StatusPreconditionFailed,
didsubject.ErrSubjectNotFound: http.StatusNotFound,
iamclient.ErrInvalidClientCall: http.StatusBadRequest,
iamclient.ErrBadGateway: http.StatusBadGateway,
iamclient.ErrPreconditionFailed: http.StatusPreconditionFailed,
})
}
// HandleTokenRequest handles calls to the token endpoint for exchanging a grant (e.g authorization code or pre-authorized code) for an access token.
func (r Wrapper) HandleTokenRequest(ctx context.Context, request HandleTokenRequestRequestObject) (HandleTokenRequestResponseObject, error) {
err := r.subjectExists(ctx, request.SubjectID)
if err != nil {
return nil, err
}
switch request.Body.GrantType {
case oauth.AuthorizationCodeGrantType:
// Options:
// - OpenID4VCI
// - OpenID4VP
// verifier DID is taken from code->oauthSession storage
return r.handleAccessTokenRequest(ctx, *request.Body)
case oauth.PreAuthorizedCodeGrantType:
// Options:
// - OpenID4VCI
// todo: add to grantTypesSupported in AS metadata once supported
return nil, oauth.OAuth2Error{
Code: oauth.UnsupportedGrantType,
Description: "not implemented yet",
}
case oauth.JWTBearerGrantType:
// Twinn TA NP & LSPxNuts flow
// TODO: support client_assertion
if request.Body.Assertion == nil || request.Body.Scope == nil || request.Body.ClientId == nil {
return nil, oauth.OAuth2Error{
Code: oauth.InvalidRequest,
Description: "missing required parameters",
}
}
return r.handleJWTBearerTokenRequest(ctx, *request.Body.ClientId, request.SubjectID, *request.Body.Scope, *request.Body.Assertion)
case oauth.VpTokenGrantType:
// Nuts RFC021 vp_token bearer flow
if request.Body.PresentationSubmission == nil || request.Body.Scope == nil || request.Body.Assertion == nil || request.Body.ClientId == nil {
return nil, oauth.OAuth2Error{
Code: oauth.InvalidRequest,
Description: "missing required parameters",
}
}
return r.handleS2SAccessTokenRequest(ctx, *request.Body.ClientId, request.SubjectID, *request.Body.Scope, *request.Body.PresentationSubmission, *request.Body.Assertion)
default:
return nil, oauth.OAuth2Error{
Code: oauth.UnsupportedGrantType,
Description: fmt.Sprintf("grant_type '%s' is not supported", request.Body.GrantType),
}
}
}
func (r Wrapper) Callback(ctx context.Context, request CallbackRequestObject) (CallbackResponseObject, error) {
if !r.auth.AuthorizationEndpointEnabled() {
// Callback endpoint is only used by flows initiated through the authorization endpoint.
return nil, oauth.OAuth2Error{
Code: oauth.InvalidRequest,
Description: "callback endpoint is disabled",
}
}
// validate request
// check did in path
err := r.subjectExists(ctx, request.SubjectID)
if err != nil {
return nil, err
}
// check if state is present and resolves to a client state
if request.Params.State == nil || *request.Params.State == "" {
// without state it is an invalid request, but try to provide as much useful information as possible
if request.Params.Error != nil && *request.Params.Error != "" {
callbackError := callbackRequestToError(request, nil)
callbackError.InternalError = errors.New("missing state parameter")
return nil, callbackError
}
return nil, oauthError(oauth.InvalidRequest, "missing state parameter")
}
oauthSession := new(OAuthSession)
if err = r.oauthClientStateStore().Get(*request.Params.State, oauthSession); err != nil {
return nil, oauthError(oauth.InvalidRequest, "invalid or expired state", err)
}
if request.SubjectID != *oauthSession.OwnSubject {
// TODO: this is a manipulated request, add error logging?
return nil, withCallbackURI(oauthError(oauth.InvalidRequest, "session subject does not match request"), oauthSession.redirectURI())
}
// if error is present, redirect error back to application initiating the flow
if request.Params.Error != nil && *request.Params.Error != "" {
return nil, callbackRequestToError(request, oauthSession.redirectURI())
}
// check if code is present
if request.Params.Code == nil || *request.Params.Code == "" {
return nil, withCallbackURI(oauthError(oauth.InvalidRequest, "missing code parameter"), oauthSession.redirectURI())
}
// continue flow
switch oauthSession.ClientFlow {
case credentialRequestClientFlow:
return r.handleOpenID4VCICallback(ctx, *request.Params.Code, oauthSession)
case accessTokenRequestClientFlow:
return r.handleCallback(ctx, *request.Params.Code, oauthSession)
default:
// programming error, should never happen
return nil, withCallbackURI(oauthError(oauth.ServerError, "unknown client flow for callback: '"+oauthSession.ClientFlow+"'"), oauthSession.redirectURI())
}
}
// callbackRequestToError should only be used if request.params.Error is present
func callbackRequestToError(request CallbackRequestObject, redirectURI *url.URL) oauth.OAuth2Error {
requestErr := oauth.OAuth2Error{
Code: oauth.ErrorCode(*request.Params.Error),
RedirectURI: redirectURI,
}
if request.Params.ErrorDescription != nil {
requestErr.Description = *request.Params.ErrorDescription
}
return requestErr
}
func (r Wrapper) RetrieveAccessToken(ctx context.Context, request RetrieveAccessTokenRequestObject) (RetrieveAccessTokenResponseObject, error) {
// get access token from store
var token TokenResponse
err := r.accessTokenClientStore().Get(request.SessionID, &token)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return nil, core.NotFoundError("session not found")
}
return nil, err
}
if token.Get("status") == oauth.AccessTokenRequestStatusPending {
// return pending status
return RetrieveAccessToken200JSONResponse(token), nil
}
// access token is active, return to caller and delete access token from store
// change this when tokens can be cached
err = r.accessTokenClientStore().Delete(request.SessionID)
if err != nil {
log.Logger().WithContext(ctx).WithError(err).Warn("Failed to delete access token")
}
// return access token
return RetrieveAccessToken200JSONResponse(token), nil
}
// IntrospectAccessToken allows the resource server (XIS/EHR) to introspect details of an access token issued by this node
func (r Wrapper) IntrospectAccessToken(ctx context.Context, request IntrospectAccessTokenRequestObject) (IntrospectAccessTokenResponseObject, error) {
headers := ctx.Value(httpRequestContextKey{}).(*http.Request).Header
if !slices.Contains(headers["Content-Type"], "application/x-www-form-urlencoded") {
return nil, core.Error(http.StatusUnsupportedMediaType, "Content-Type MUST be set to application/x-www-form-urlencoded")
}
input := request.Body.Token
response, err := r.introspectAccessToken(input)
if err != nil {
return nil, err
} else if response == nil {
return IntrospectAccessToken200JSONResponse{}, nil
}
response.Vps = nil
response.PresentationDefinitions = nil
response.PresentationSubmissions = nil
return IntrospectAccessToken200JSONResponse(*response), nil
}
// IntrospectAccessTokenExtended allows the resource server (XIS/EHR) to introspect details of an access token issued by this node.
// It returns the same information as IntrospectAccessToken, but with additional information.
func (r Wrapper) IntrospectAccessTokenExtended(ctx context.Context, request IntrospectAccessTokenExtendedRequestObject) (IntrospectAccessTokenExtendedResponseObject, error) {
headers := ctx.Value(httpRequestContextKey{}).(*http.Request).Header
if !slices.Contains(headers["Content-Type"], "application/x-www-form-urlencoded") {
return nil, core.Error(http.StatusUnsupportedMediaType, "Content-Type MUST be set to application/x-www-form-urlencoded")
}
input := request.Body.Token
response, err := r.introspectAccessToken(input)
if err != nil {
return nil, err
} else if response == nil {
return IntrospectAccessTokenExtended200JSONResponse{}, nil
}
return IntrospectAccessTokenExtended200JSONResponse(*response), nil
}
func (r Wrapper) introspectAccessToken(input string) (*ExtendedTokenIntrospectionResponse, error) {
// Validate token
if input == "" {
// Return 200 + 'Active = false' when token is invalid or malformed
log.Logger().Warn("IntrospectAccessToken: missing token")
return nil, nil
}
token := AccessToken{}
if err := r.accessTokenServerStore().Get(input, &token); err != nil {
// Return 200 + 'Active = false' when token is invalid or malformed
if errors.Is(err, storage.ErrNotFound) {
log.Logger().Debug("IntrospectAccessToken: token not found (unknown or expired)")
return nil, nil
}
log.Logger().WithError(err).Error("IntrospectAccessToken: failed to retrieve token")
return nil, err
}
if token.Expiration.Before(time.Now()) {
// Return 200 + 'Active = false' when token is invalid or malformed
// can happen between token expiration and pruning of database
log.Logger().Debug("IntrospectAccessToken: token is expired")
return nil, nil
}
// Optional:
// Use DPoP from token to generate JWK thumbprint for public key
// deserialization of the DPoP struct from the accessTokenServerStore triggers validation of the DPoP header
// SHA256 hashing won't fail.
var cnf *Cnf
if token.DPoP != nil {
hash, _ := token.DPoP.Headers.JWK().Thumbprint(crypto.SHA256)
base64Hash := base64.RawURLEncoding.EncodeToString(hash)
cnf = &Cnf{Jkt: base64Hash}
}
// Create and return introspection response
iat := int(token.IssuedAt.Unix())
exp := int(token.Expiration.Unix())
response := ExtendedTokenIntrospectionResponse{
Active: true,
Cnf: cnf,
Iat: &iat,
Exp: &exp,
Iss: &token.Issuer,
ClientId: &token.ClientId,
Scope: &token.Scope,
Vps: &token.VPToken,
}
if token.PresentationDefinitions != nil {
response.PresentationDefinitions = &token.PresentationDefinitions
}
if token.PresentationSubmissions != nil {
response.PresentationSubmissions = &token.PresentationSubmissions
}
if token.InputDescriptorConstraintIdMap != nil {
for _, reserved := range []string{"iss", "sub", "exp", "iat", "active", "client_id", "scope"} {
if _, isReserved := token.InputDescriptorConstraintIdMap[reserved]; isReserved {
return nil, fmt.Errorf("IntrospectAccessToken: InputDescriptorConstraintIdMap contains reserved claim name: %s", reserved)
}
}
response.AdditionalProperties = token.InputDescriptorConstraintIdMap
}
return &response, nil
}
// HandleAuthorizeRequest handles calls to the authorization endpoint for starting an authorization code flow.
func (r Wrapper) HandleAuthorizeRequest(ctx context.Context, request HandleAuthorizeRequestRequestObject) (HandleAuthorizeRequestResponseObject, error) {
if !r.auth.AuthorizationEndpointEnabled() {
return nil, oauth.OAuth2Error{
Code: oauth.InvalidRequest,
Description: "authorization endpoint is disabled",
}
}
err := r.subjectExists(ctx, request.SubjectID)
if err != nil {
return nil, err
}
authServerURL := r.subjectToBaseURL(request.SubjectID)
metadata, err := r.oauthAuthorizationServerMetadata(authServerURL)
if err != nil {
return nil, err
}
// Workaround: deepmap codegen doesn't support dynamic query parameters.
// See https://github.com/deepmap/oapi-codegen/issues/1129
httpRequest := ctx.Value(httpRequestContextKey{}).(*http.Request)
return r.handleAuthorizeRequest(ctx, request.SubjectID, *metadata, *httpRequest.URL)
}
// handleAuthorizeRequest handles calls to the authorization endpoint for starting an authorization code flow.
// The caller must ensure ownDID is actually owned by this node.
func (r Wrapper) handleAuthorizeRequest(ctx context.Context, subject string, ownMetadata oauth.AuthorizationServerMetadata, request url.URL) (HandleAuthorizeRequestResponseObject, error) {
// parse and validate as JAR (RFC9101, JWT Authorization Request)
requestObject, err := r.jar.Parse(ctx, ownMetadata, request.Query())
if err != nil {
// already an oauth.OAuth2Error
return nil, err
}
switch requestObject.get(oauth.ResponseTypeParam) {
case oauth.CodeResponseType:
// Options:
// - Regular authorization code flow for EHR data access through access token, authentication of end-user using OpenID4VP.
// - OpenID4VCI; authorization code flow for credential issuance to (end-user) wallet
// TODO: officially flow switching has to be determined by the client_id
// registered client_ids should list which flow they support
// client registration could be done via rfc7591....
// if client_id is a url, we can use OpenID federation for automatic client registration
return r.handleAuthorizeRequestFromHolder(ctx, subject, requestObject)
case oauth.VPTokenResponseType:
// Options:
// - OpenID4VP flow, vp_token is sent in Authorization Response
// non-spec: if the scheme is openid4vp (URL starts with openid4vp:), the OpenID4VP request should be handled by a user wallet, rather than an organization wallet.
// Requests to user wallets can then be rendered as QR-code (or use a cloud wallet).
// Note that it can't be called from the outside, but only by internal dispatch (since Echo doesn't handle openid4vp:, obviously).
walletOwnerType := pe.WalletOwnerOrganization
if strings.HasPrefix(request.String(), "openid4vp:") {
walletOwnerType = pe.WalletOwnerUser
}
return r.handleAuthorizeRequestFromVerifier(ctx, subject, requestObject, walletOwnerType)
default:
// TODO: This should be a redirect?
redirectURI, _ := url.Parse(requestObject.get(oauth.RedirectURIParam))
return nil, oauth.OAuth2Error{
Code: oauth.UnsupportedResponseType,
RedirectURI: redirectURI,
}
}
}
// RequestJWTByGet returns the Request Object referenced as 'request_uri' in an authorization request.
// RFC9101: The OAuth 2.0 Authorization Framework: JWT-Secured Authorization Request (JAR).
func (r Wrapper) RequestJWTByGet(ctx context.Context, request RequestJWTByGetRequestObject) (RequestJWTByGetResponseObject, error) {
ro := new(jarRequest)
err := r.authzRequestObjectStore().GetAndDelete(request.Id, ro)
if err != nil {
return nil, oauth.OAuth2Error{
Code: oauth.InvalidRequest,
Description: "request object not found",
}
}
expected := r.subjectToBaseURL(request.SubjectID)
if ro.Client != expected.String() {
return nil, oauth.OAuth2Error{
Code: oauth.InvalidRequest,
Description: "client_id does not match request",
}
}
if ro.RequestURIMethod != "get" { // case sensitive
// TODO: wallet does not support `request_uri_method=post`. Spec is unclear if this should fail, or fallback to using staticAuthorizationServerMetadata().
return nil, oauth.OAuth2Error{
Code: oauth.InvalidRequest,
Description: "used request_uri_method 'get' on a 'post' request_uri",
InternalError: errors.New("wrong 'request_uri_method' authorization server or wallet probably does not support 'request_uri_method'"),
}
}
// TODO: supported signature types should be checked
token, err := r.jar.Sign(ctx, ro.Claims)
if err != nil {
return nil, oauth.OAuth2Error{
Code: oauth.ServerError,
Description: "unable to create Request Object",
InternalError: fmt.Errorf("failed to sign authorization Request Object: %w", err),
}
}
return RequestJWTByGet200ApplicationoauthAuthzReqJwtResponse{
Body: bytes.NewReader([]byte(token)),
ContentLength: int64(len(token)),
}, nil
}
// RequestJWTByPost returns the Request Object referenced as 'request_uri' in an authorization request.
// Extension of OpenID 4 Verifiable Presentations (OpenID4VP) on
// RFC9101: The OAuth 2.0 Authorization Framework: JWT-Secured Authorization Request (JAR).
func (r Wrapper) RequestJWTByPost(ctx context.Context, request RequestJWTByPostRequestObject) (RequestJWTByPostResponseObject, error) {
ro := new(jarRequest)
err := r.authzRequestObjectStore().GetAndDelete(request.Id, ro)
if err != nil {
return nil, oauth.OAuth2Error{
Code: oauth.InvalidRequest,
Description: "request object not found",
}
}
expected := r.subjectToBaseURL(request.SubjectID)
if ro.Client != expected.String() {
return nil, oauth.OAuth2Error{
Code: oauth.InvalidRequest,
Description: "client_id does not match request",
}
}
if ro.RequestURIMethod != "post" { // case sensitive
return nil, oauth.OAuth2Error{
Code: oauth.InvalidRequest,
Description: "used request_uri_method 'post' on a 'get' request_uri",
}
}
walletMetadata := staticAuthorizationServerMetadata()
if request.Body != nil {
if request.Body.WalletMetadata != nil {
walletMetadata = *request.Body.WalletMetadata
}
if request.Body.WalletNonce != nil {
ro.Claims[oauth.WalletNonceParam] = *request.Body.WalletNonce
}
}
if walletMetadata.Issuer != "https://self-issued.me/v2" {
ro.Claims[jwt.AudienceKey] = walletMetadata.Issuer
}
// TODO: supported signature types should be checked
token, err := r.jar.Sign(ctx, ro.Claims)
if err != nil {
return nil, oauth.OAuth2Error{
Code: oauth.ServerError,
Description: "unable to create Request Object",
InternalError: fmt.Errorf("failed to sign authorization Request Object: %w", err),
}
}
return RequestJWTByPost200ApplicationoauthAuthzReqJwtResponse{
Body: bytes.NewReader([]byte(token)),
ContentLength: int64(len(token)),
}, nil
}
// OAuthAuthorizationServerMetadata returns the Authorization Server's metadata
func (r Wrapper) OAuthAuthorizationServerMetadata(_ context.Context, request OAuthAuthorizationServerMetadataRequestObject) (OAuthAuthorizationServerMetadataResponseObject, error) {
clientID := r.subjectToBaseURL(request.SubjectID)
md, err := r.oauthAuthorizationServerMetadata(clientID)
if err != nil {
return nil, err
}
return OAuthAuthorizationServerMetadata200JSONResponse(*md), nil
}
func (r Wrapper) oauthAuthorizationServerMetadata(clientID url.URL) (*oauth.AuthorizationServerMetadata, error) {
md := authorizationServerMetadata(&clientID, r.auth.SupportedDIDMethods(), r.auth.SupportedDIDMethods())
if !r.auth.AuthorizationEndpointEnabled() {
md.AuthorizationEndpoint = ""
}
return &md, nil
}
// OAuthClientMetadata returns the OAuth2 Client metadata for the request.Id if it is managed by this node.
func (r Wrapper) OAuthClientMetadata(ctx context.Context, request OAuthClientMetadataRequestObject) (OAuthClientMetadataResponseObject, error) {
err := r.subjectExists(ctx, request.SubjectID)
if err != nil {
return nil, err
}
identityURL := r.subjectToBaseURL(request.SubjectID)
return OAuthClientMetadata200JSONResponse(clientMetadata(identityURL)), nil
}
func (r Wrapper) OpenIDConfiguration(ctx context.Context, request OpenIDConfigurationRequestObject) (OpenIDConfigurationResponseObject, error) {
// find DIDs for subject
dids, err := r.subjectManager.ListDIDs(ctx, request.SubjectID)
if err != nil {
if errors.Is(err, didsubject.ErrSubjectNotFound) {
return nil, oauth.OAuth2Error{
Code: oauth.InvalidRequest,
Description: err.Error(),
}
}
return nil, oauth.OAuth2Error{
Code: oauth.ServerError,
InternalError: err,
}
}
// resolve DID key
set := jwk.NewSet()
var signingKey string
for _, currentDID := range dids {
kid, key, err := r.keyResolver.ResolveKey(currentDID, nil, resolver.AssertionMethod)
if err != nil {
return nil, oauth.OAuth2Error{
Code: oauth.ServerError,
InternalError: err,
}
}
// create JWK and add to set
jwkKey, err := jwk.FromRaw(key)
if err != nil {
return nil, oauth.OAuth2Error{
Code: oauth.ServerError,
InternalError: err,
}
}
_ = jwkKey.Set(jwk.KeyIDKey, kid)
_ = set.AddKey(jwkKey)
// The DID is the preferred DID method (as configured), so take a key of the first DID as signing key
if signingKey == "" {
signingKey = kid
}
}
// we sign with a JWK, the receiving party can verify with the signature but not if the key corresponds to the DID since the DID method might not be supported.
// this is a shortcoming of the openID federation vs OpenID4VP/DID worlds
// issuer URL equals server baseURL + :/oauth2/:subject
issuerURL := r.subjectToBaseURL(request.SubjectID)
configuration := openIDConfiguration(issuerURL, set, r.auth.SupportedDIDMethods(), r.auth.GrantTypes())
claims := make(map[string]interface{})
asJson, _ := json.Marshal(configuration)
_ = json.Unmarshal(asJson, &claims)
// create jwt
token, err := r.jwtSigner.SignJWT(ctx, claims, nil, signingKey)
if err != nil {
return nil, oauth.OAuth2Error{
Code: oauth.ServerError,
InternalError: err,
}
}
return OpenIDConfiguration200ApplicationentityStatementJwtResponse{
Body: strings.NewReader(token),
ContentLength: int64(len(token)),
}, nil
}
func (r Wrapper) PresentationDefinition(ctx context.Context, request PresentationDefinitionRequestObject) (PresentationDefinitionResponseObject, error) {
if len(request.Params.Scope) == 0 {
return PresentationDefinition200JSONResponse(PresentationDefinition{}), nil
}
mapping, err := r.policyBackend.PresentationDefinitions(ctx, request.Params.Scope)
if err != nil {
return nil, oauth.OAuth2Error{
Code: oauth.InvalidScope,
Description: err.Error(),
}
}
walletOwnerType := pe.WalletOwnerOrganization
if request.Params.WalletOwnerType != nil {
walletOwnerType = *request.Params.WalletOwnerType
}
result, exists := mapping[walletOwnerType]
if !exists {
return nil, oauthError(oauth.InvalidRequest, fmt.Sprintf("no presentation definition found for '%s' wallet", walletOwnerType))
}
return PresentationDefinition200JSONResponse(result), nil
}
func (r Wrapper) RequestServiceAccessToken(ctx context.Context, request RequestServiceAccessTokenRequestObject) (RequestServiceAccessTokenResponseObject, error) {
err := r.subjectExists(ctx, request.SubjectID)
if err != nil {
return nil, err
}
tokenCache := r.accessTokenCache()
cacheKey := accessTokenRequestCacheKey(request)
if request.Params.CacheControl == nil || *request.Params.CacheControl != "no-cache" {
// try to retrieve token from cache
tokenCacheResult := new(TokenResponse)
err = tokenCache.Get(cacheKey, tokenCacheResult)
if err == nil {
// adjust tokenCacheResult.ExpiresIn to the remaining time
expiresAt := time.Unix(int64(*tokenCacheResult.ExpiresAt), 0)
tokenCacheResult.ExpiresIn = to.Ptr(int(time.Until(expiresAt).Seconds()))
return RequestServiceAccessToken200JSONResponse(*tokenCacheResult), nil
} else if !errors.Is(err, storage.ErrNotFound) {
// only log error, don't fail
log.Logger().WithError(err).Warnf("Failed to retrieve access token from cache: %s", err.Error())
}
}
var credentials []VerifiableCredential
if request.Body.Credentials != nil {
credentials = *request.Body.Credentials
}
// assert that self-asserted credentials do not contain an issuer or credentialSubject.id. These values must be set
// by the nuts-node to build the correct wallet for a DID. See https://github.com/nuts-foundation/nuts-node/issues/3696
// As a sideeffect it is no longer possible to pass signed credentials to this API.
for _, cred := range credentials {
var credentialSubject []map[string]interface{}
if err := cred.UnmarshalCredentialSubject(&credentialSubject); err != nil {
// extremely unlikely
return nil, core.InvalidInputError("failed to parse credentialSubject.id: %w", err)
}
for _, credSub := range credentialSubject {
if _, ok := credSub["id"]; ok {
return nil, core.InvalidInputError("self-asserted credentials MUST NOT contain a 'credentialSubject.id'")
}
}
if cred.Issuer.String() != "" {
return nil, core.InvalidInputError("self-asserted credentials MUST NOT contain an 'issuer'")
}
}
useDPoP := true
if request.Body.TokenType != nil && strings.EqualFold(string(*request.Body.TokenType), AccessTokenTypeBearer) {
useDPoP = false
}
// Extract credential_selection from request.
// nil is safe here: downstream code only reads via len() and range.
var credentialSelection map[string]string
if request.Body.CredentialSelection != nil {
credentialSelection = *request.Body.CredentialSelection
}
clientID := r.subjectToBaseURL(request.SubjectID)
var policyId string
if request.Body.PolicyId != nil {
policyId = *request.Body.PolicyId
}
tokenResult, err := r.auth.IAMClient().RequestRFC021AccessToken(ctx, clientID.String(), request.SubjectID, request.Body.AuthorizationServer, request.Body.Scope, policyId, useDPoP, credentials, credentialSelection)
if err != nil {
// this can be an internal server error, a 400 oauth error or a 412 precondition failed if the wallet does not contain the required credentials
return nil, err
}
ttl := accessTokenValidity
if tokenResult.ExpiresIn != nil {
ttl = time.Second * time.Duration(*tokenResult.ExpiresIn)
}
tokenResult.ExpiresAt = to.Ptr(int(time.Now().Add(ttl).Unix()))
// we reduce the ttl by accessTokenCacheOffset to make sure the token is expired when the cache expires
ttl -= accessTokenCacheOffset
err = tokenCache.Put(cacheKey, tokenResult, storage.WithTTL(ttl))
if err != nil {
// only log error, don't fail
log.Logger().WithError(err).Warnf("Failed to cache access token: %s", err.Error())
}
return RequestServiceAccessToken200JSONResponse(*tokenResult), nil
}
func (r Wrapper) RequestUserAccessToken(ctx context.Context, request RequestUserAccessTokenRequestObject) (RequestUserAccessTokenResponseObject, error) {
err := r.subjectExists(ctx, request.SubjectID)
if err != nil {
return nil, err
}
// Note: When we support authentication at an external IdP,
// the properties below become conditionally required.
if request.Body.PreauthorizedUser == nil {
return nil, core.InvalidInputError("missing preauthorized_user")
}
if request.Body.PreauthorizedUser.Id == "" {
return nil, core.InvalidInputError("missing preauthorized_user.id")
}
if request.Body.PreauthorizedUser.Name == "" {
return nil, core.InvalidInputError("missing preauthorized_user.name")
}
if request.Body.PreauthorizedUser.Role == "" {
return nil, core.InvalidInputError("missing preauthorized_user.role")
}
if request.Body.RedirectUri == "" {
return nil, core.InvalidInputError("missing redirect_uri")
}
// session ID for calling app (supports polling for token)
sessionID := nutsCrypto.GenerateNonce()
// generate a redirect token valid for 5 seconds
token := nutsCrypto.GenerateNonce()
err = r.userRedirectStore().Put(token, RedirectSession{
AccessTokenRequest: request,
SessionID: sessionID,
SubjectID: request.SubjectID,
})
if err != nil {
return nil, err
}
tokenResponse := (&TokenResponse{}).With("status", oauth.AccessTokenRequestStatusPending)
if err = r.accessTokenClientStore().Put(sessionID, tokenResponse); err != nil {
return nil, err
}
// redirect to generic user page, context of token will render correct page
redirectURL := nutsHttp.AddQueryParams(*r.auth.PublicURL().JoinPath("oauth2", request.SubjectID, "user"), map[string]string{
"token": token,
})
return RequestUserAccessToken200JSONResponse{
RedirectUri: redirectURL.String(),
SessionId: sessionID,
}, nil
}
func (r Wrapper) StatusList(ctx context.Context, request StatusListRequestObject) (StatusListResponseObject, error) {
requestDID, err := did.ParseDID(request.Did)
if err != nil {
return nil, err
}
cred, err := r.vcr.Issuer().StatusList(ctx, *requestDID, request.Page)
if err != nil {
return nil, err
}
return StatusList200JSONResponse(*cred), nil
}
func (r Wrapper) openid4vciMetadata(ctx context.Context, issuer string) (*oauth.OpenIDCredentialIssuerMetadata, *oauth.AuthorizationServerMetadata, error) {
credentialIssuerMetadata, err := r.auth.IAMClient().OpenIdCredentialIssuerMetadata(ctx, issuer)
if err != nil {
return nil, nil, err
}
// OpenID4VCI allows multiple AuthorizationServers in credentialIssuerMetadata for a single issuer. (allows delegating issuance per VC type)
// TODO: smart select the correct authorization server based on the metadata
// https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html#name-credential-issuer-metadata-p
// For now we just accept the first successful result, and lookup the metadata.
var ASMetadata *oauth.AuthorizationServerMetadata
for _, serverURL := range credentialIssuerMetadata.AuthorizationServers {
ASMetadata, err = r.auth.IAMClient().AuthorizationServerMetadata(ctx, serverURL)
if err == nil {
break
}
}
if ASMetadata == nil {
// authorization_servers is an optional field. When no authorization servers are listed, the oauth Issuer is the authorization server.
// also try issuer in case all others fail
ASMetadata, err = r.auth.IAMClient().AuthorizationServerMetadata(ctx, issuer)
if err != nil {
return nil, nil, err
}
}
return credentialIssuerMetadata, ASMetadata, nil
}
// createAuthorizationRequest creates an OAuth2.0 authorizationRequest redirect URL that redirects to the authorization server.
// It can create both regular OAuth2 requests and OpenID4VP requests due to the requestObjectModifier.
// This modifier is used by JAR.Create to generate a (JAR) request object that is added as 'request_uri' parameter.
// It's able to create an unsigned request and a signed request (JAR) based on the OAuth Server Metadata.
func (r Wrapper) createAuthorizationRequest(ctx context.Context, subject string, metadata oauth.AuthorizationServerMetadata, modifier requestObjectModifier) (*url.URL, error) {
if len(metadata.AuthorizationEndpoint) == 0 {
return nil, fmt.Errorf("no authorization endpoint found in metadata for %s", metadata.Issuer)
}
endpoint, err := url.Parse(metadata.AuthorizationEndpoint)
if err != nil {
return nil, fmt.Errorf("failed to parse authorization endpoint URL: %w", err)
}
clientID := r.subjectToBaseURL(subject)
signerDID, err := r.determineClientDID(ctx, metadata, subject)
if err != nil {
return nil, err
}
audience := metadata.Issuer
if metadata.Issuer == "https://self-issued.me/v2" {
audience = ""
}
// request_uri
requestURIID := nutsCrypto.GenerateNonce()
requestObj := r.jar.Create(*signerDID, clientID.String(), audience, modifier)
if err := r.authzRequestObjectStore().Put(requestURIID, requestObj); err != nil {
return nil, err
}
requestURI := clientID.JoinPath("request.jwt", requestURIID)
// JAR request
params := map[string]string{
oauth.ClientIDParam: clientID.String(),
oauth.RequestURIMethodParam: requestObj.RequestURIMethod,
oauth.RequestURIParam: requestURI.String(),
}
if metadata.RequireSignedRequestObject {
redirectURL := nutsHttp.AddQueryParams(*endpoint, params)
return &redirectURL, nil
}
// else; unclear if AS has support for RFC9101, so also add all modifiers to the query itself
// left here for completeness, node 2 node interaction always uses JAR since the AS metadata has it hardcoded
// TODO: in the user flow we have no AS metadata, meaning that we add all params to the query.
// This is most likely going to fail on mobile devices due to request url length.
modifier(params)
redirectURL := nutsHttp.AddQueryParams(*endpoint, params)
return &redirectURL, nil
}
// accessTokenClientStore is used by the client to store pending access tokens and return them to the calling app.
func (r Wrapper) accessTokenClientStore() storage.SessionStore {
return r.storageEngine.GetSessionDatabase().GetStore(accessTokenValidity, "clientaccesstoken")
}
// accessTokenServerStore is used by the Auth server to store issued access tokens
func (r Wrapper) accessTokenServerStore() storage.SessionStore {
return r.storageEngine.GetSessionDatabase().GetStore(accessTokenValidity, "serveraccesstoken")
}
// accessTokenClientStore is used by the client to cache access tokens
func (r Wrapper) accessTokenCache() storage.SessionStore {
// we use a slightly reduced validity to prevent the cache from being used after the token has expired
return r.storageEngine.GetSessionDatabase().GetStore(accessTokenValidity-accessTokenCacheOffset, "accesstokencache")
}
// accessTokenServerStore is used by the Auth server to store issued access tokens
func (r Wrapper) authzRequestObjectStore() storage.SessionStore {
return r.storageEngine.GetSessionDatabase().GetStore(accessTokenValidity, oauthRequestObjectKey...)
}
func (r Wrapper) subjectToBaseURL(subject string) url.URL {
return *r.auth.PublicURL().JoinPath("oauth2", subject)
}
// subjectExists checks whether the given subject is known on the local node.
func (r Wrapper) subjectExists(ctx context.Context, subjectID string) error {
exists, err := r.subjectManager.Exists(ctx, subjectID)
if err != nil {
return err
}