diff --git a/.gitignore b/.gitignore index 9c779772..8a24a0bc 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ server.config.yaml demo-ehr.db nuts-demo-ehr + diff --git a/Makefile b/Makefile index 4821ff4c..a64ca07b 100644 --- a/Makefile +++ b/Makefile @@ -18,10 +18,6 @@ gen-api: -import-mapping='../common/ssi_types.yaml:github.com/nuts-foundation/nuts-demo-ehr/nuts/client/common' \ -exclude-schemas SearchVCRequest,CredentialSubject \ -o nuts/client/discovery/generated.go https://nuts-node.readthedocs.io/en/latest/_static/discovery/v1.yaml - oapi-codegen -generate client,types -package vcr \ - -import-mapping='../common/ssi_types.yaml:github.com/nuts-foundation/nuts-demo-ehr/nuts/client/common' \ - -exclude-schemas SearchVCRequest,CredentialSubject \ - -o nuts/client/vcr/generated.go https://nuts-node.readthedocs.io/en/latest/_static/vcr/vcr_v2.yaml oapi-codegen -generate client,types -package didman \ -import-mapping='../common/ssi_types.yaml:github.com/nuts-foundation/nuts-demo-ehr/nuts/client/common' \ -o nuts/client/didman/generated.go -exclude-schemas OrganizationSearchResult https://nuts-node.readthedocs.io/en/latest/_static/didman/v1.yaml @@ -34,3 +30,5 @@ gen-api: oapi-codegen -generate client,types -package iam \ -import-mapping='../common/ssi_types.yaml:github.com/nuts-foundation/nuts-demo-ehr/nuts/client/common' \ -o nuts/client/iam/generated.go https://nuts-node.readthedocs.io/en/latest/_static/auth/v2.yaml + oapi-codegen -generate client,types -package pip \ + -o nutspxp/client/pip/generated.go https://raw.githubusercontent.com/nuts-foundation/nuts-pxp/main/oas/pip.yaml diff --git a/config.go b/config.go index fd5a39da..3f16dc54 100644 --- a/config.go +++ b/config.go @@ -61,6 +61,7 @@ type Config struct { Verbosity string `koanf:"verbosity"` HTTPPort int `koanf:"port"` NutsNodeAddress string `koanf:"nutsnodeaddr"` + NutsPIPAddress string `koanf:"nutspipaddr"` FHIR FHIR `koanf:"fhir"` SharedCarePlanning SharedCarePlanning `koanf:"sharedcareplanning"` CustomersFile string `koanf:"customersfile"` diff --git a/docker-compose.yml b/docker-compose.yml index 4896a8b5..648fa5e6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -41,6 +41,30 @@ services: - "./docker-compose/right/config/pep/nginx.conf:/etc/nginx/nginx.conf" - "./docker-compose/lb/socket:/tmp/sockets" - "./docker-compose/right/config/pep/oauth2.js:/etc/nginx/js/oauth2.js" + pip-left: &pip + image: nutsfoundation/nuts-pxp:main + environment: + NUTS_CONFIGFILE: /nuts/config.yaml + ports: + - 8080:8080 + networks: + demo: + ipv4_address: 172.90.10.13 + volumes: + - "./docker-compose/left/data/nutspxp:/nuts/data" + - "./docker-compose/left/config/nutspxp/policies:/nuts/policies" + - "./docker-compose/left/config/nutspxp/config.yaml:/nuts/config.yaml" + pip-right: + <<: *pip + ports: + - 8081:8080 + networks: + demo: + ipv4_address: 172.90.10.14 + volumes: + - "./docker-compose/right/data/nutspxp:/nuts/data" + - "./docker-compose/right/config/nutspxp/policies:/nuts/policies" + - "./docker-compose/left/config/nutspxp/config.yaml:/nuts/config.yaml" node-left: &node image: nutsfoundation/nuts-node:master environment: diff --git a/docker-compose/left/config/nutspxp/config.yaml b/docker-compose/left/config/nutspxp/config.yaml new file mode 100644 index 00000000..ee5cf3c4 --- /dev/null +++ b/docker-compose/left/config/nutspxp/config.yaml @@ -0,0 +1,3 @@ +policy_dir: ./policies +sql: + connection: sqlite:file:./data/sqlite.db?_pragma=foreign_keys(1)&journal_mode(WAL) \ No newline at end of file diff --git a/docker-compose/left/config/nutspxp/policies/eOverdracht-receiver.rego b/docker-compose/left/config/nutspxp/policies/eOverdracht-receiver.rego new file mode 100644 index 00000000..28c9e9f8 --- /dev/null +++ b/docker-compose/left/config/nutspxp/policies/eOverdracht-receiver.rego @@ -0,0 +1,11 @@ +package eOverdracht.receiver + +import rego.v1 + +# Only owner can update the pet's information +# Ownership information is provided as part of OPA's input +default allow := false + +allow if { + input.request.method = "POST" +} \ No newline at end of file diff --git a/docker-compose/left/config/nutspxp/policies/eOverdracht-sender.rego b/docker-compose/left/config/nutspxp/policies/eOverdracht-sender.rego new file mode 100644 index 00000000..023a7fe2 --- /dev/null +++ b/docker-compose/left/config/nutspxp/policies/eOverdracht-sender.rego @@ -0,0 +1,14 @@ +package eOverdracht.sender + +import rego.v1 + +# Only owner can update the pet's information +# Ownership information is provided as part of OPA's input +default allow := false + +# eOVerdracht expects the following data: path to [actions] mapping + +# example when http methods are stored in nuts-pxp +allow if { + input.request.method in input.external[input.request.path] +} \ No newline at end of file diff --git a/docker-compose/left/config/pep/nginx.conf b/docker-compose/left/config/pep/nginx.conf index 55a7db1b..a5399925 100644 --- a/docker-compose/left/config/pep/nginx.conf +++ b/docker-compose/left/config/pep/nginx.conf @@ -65,7 +65,7 @@ http { proxy_pass http://unix:/tmp/authz.sock; } - location = /_oauth2_delegated { + location /_oauth2_delegated { internal; js_content oauth2.introspectAccessToken; } diff --git a/docker-compose/left/config/pep/oauth2.js b/docker-compose/left/config/pep/oauth2.js index 65432eb0..d87b29c4 100644 --- a/docker-compose/left/config/pep/oauth2.js +++ b/docker-compose/left/config/pep/oauth2.js @@ -11,7 +11,7 @@ function introspectAccessToken(r) { r.subrequest("/_oauth2_introspect", { method: "POST", body: token}, function(reply) { - if (reply.status == 200) { + if (reply.status === 200) { var introspection = JSON.parse(reply.responseBody); if (introspection.active) { //dpop(r, introspection.cnf) diff --git a/docker-compose/left/data/node/sqlite.db b/docker-compose/left/data/node/sqlite.db index 69780787..483fea8b 100644 Binary files a/docker-compose/left/data/node/sqlite.db and b/docker-compose/left/data/node/sqlite.db differ diff --git a/docker-compose/right/config/nutspxp/config.yaml b/docker-compose/right/config/nutspxp/config.yaml new file mode 100644 index 00000000..ee5cf3c4 --- /dev/null +++ b/docker-compose/right/config/nutspxp/config.yaml @@ -0,0 +1,3 @@ +policy_dir: ./policies +sql: + connection: sqlite:file:./data/sqlite.db?_pragma=foreign_keys(1)&journal_mode(WAL) \ No newline at end of file diff --git a/docker-compose/right/config/nutspxp/policies/eOverdracht-receiver.rego b/docker-compose/right/config/nutspxp/policies/eOverdracht-receiver.rego new file mode 100644 index 00000000..28c9e9f8 --- /dev/null +++ b/docker-compose/right/config/nutspxp/policies/eOverdracht-receiver.rego @@ -0,0 +1,11 @@ +package eOverdracht.receiver + +import rego.v1 + +# Only owner can update the pet's information +# Ownership information is provided as part of OPA's input +default allow := false + +allow if { + input.request.method = "POST" +} \ No newline at end of file diff --git a/docker-compose/right/config/nutspxp/policies/eOverdracht-sender.rego b/docker-compose/right/config/nutspxp/policies/eOverdracht-sender.rego new file mode 100644 index 00000000..023a7fe2 --- /dev/null +++ b/docker-compose/right/config/nutspxp/policies/eOverdracht-sender.rego @@ -0,0 +1,14 @@ +package eOverdracht.sender + +import rego.v1 + +# Only owner can update the pet's information +# Ownership information is provided as part of OPA's input +default allow := false + +# eOVerdracht expects the following data: path to [actions] mapping + +# example when http methods are stored in nuts-pxp +allow if { + input.request.method in input.external[input.request.path] +} \ No newline at end of file diff --git a/docker-compose/right/data/node/sqlite.db b/docker-compose/right/data/node/sqlite.db index b7841865..41136394 100644 Binary files a/docker-compose/right/data/node/sqlite.db and b/docker-compose/right/data/node/sqlite.db differ diff --git a/domain/episode/service.go b/domain/episode/service.go index 32dba5cb..f170ab9e 100644 --- a/domain/episode/service.go +++ b/domain/episode/service.go @@ -5,18 +5,13 @@ import ( "errors" "fmt" "github.com/nuts-foundation/nuts-demo-ehr/domain/acl" - "github.com/nuts-foundation/nuts-demo-ehr/nuts/client" - "github.com/sirupsen/logrus" - "net/url" - "strings" - - "github.com/monarko/fhirgo/STU3/resources" - "github.com/nuts-foundation/go-did/vc" "github.com/nuts-foundation/nuts-demo-ehr/domain/fhir" "github.com/nuts-foundation/nuts-demo-ehr/domain/fhir/zorginzage" - reports "github.com/nuts-foundation/nuts-demo-ehr/domain/reports" "github.com/nuts-foundation/nuts-demo-ehr/domain/types" + "github.com/nuts-foundation/nuts-demo-ehr/nuts/client" "github.com/nuts-foundation/nuts-demo-ehr/nuts/registry" + "github.com/sirupsen/logrus" + "net/url" ) type Service interface { @@ -31,41 +26,15 @@ func ssnURN(ssn string) string { return fmt.Sprintf("urn:oid:2.16.840.1.113883.2.4.6.3:%s", ssn) } -func parseAuthCredentialSubject(authCredential vc.VerifiableCredential) (*registry.NutsAuthorizationCredentialSubject, error) { - subject := make([]registry.NutsAuthorizationCredentialSubject, 0) - - if err := authCredential.UnmarshalCredentialSubject(&subject); err != nil { - return nil, fmt.Errorf("invalid content for NutsAuthorizationCredential credentialSubject: %w", err) - } - - return &subject[0], nil -} - type service struct { factory fhir.Factory nutsClient *client.HTTPClient aclRepository *acl.Repository registry registry.OrganizationRegistry - vcr registry.VerifiableCredentialRegistry -} - -func NewService(factory fhir.Factory, nutsClient *client.HTTPClient, registry registry.OrganizationRegistry, vcr registry.VerifiableCredentialRegistry, aclRepository *acl.Repository) Service { - return &service{factory: factory, nutsClient: nutsClient, registry: registry, vcr: vcr, aclRepository: aclRepository} } -func parseEpisodeOfCareID(authCredential vc.VerifiableCredential) (string, error) { - subject, err := parseAuthCredentialSubject(authCredential) - if err != nil { - return "", err - } - - for _, resource := range subject.Resources { - if strings.HasPrefix(resource.Path, "/EpisodeOfCare/") { - return resource.Path[len("/EpisodeOfCare/"):], nil - } - } - - return "", errors.New("no episode found in credential") +func NewService(factory fhir.Factory, nutsClient *client.HTTPClient, registry registry.OrganizationRegistry, aclRepository *acl.Repository) Service { + return &service{factory: factory, nutsClient: nutsClient, registry: registry, aclRepository: aclRepository} } func (service *service) Create(ctx context.Context, customerID int, patientID string, request types.CreateEpisodeRequest) (*types.Episode, error) { @@ -186,71 +155,72 @@ func (service *service) GetCollaborations(ctx context.Context, customerDID, doss } func (service *service) GetReports(ctx context.Context, customerDID, patientSSN string) ([]types.Report, error) { - credentials, err := service.vcr.FindAuthorizationCredentials( - ctx, - ®istry.VCRSearchParams{ - PurposeOfUse: zorginzage.ServiceName, - SubjectID: customerDID, - Subject: ssnURN(patientSSN), - }, - ) - if err != nil { - return nil, err - } - - if len(credentials) == 0 { - return []types.Report{}, nil - } - - // TODO: loop over all credentials - issuer := credentials[0].Issuer.String() - - fhirServer, err := service.registry.GetCompoundServiceEndpoint(ctx, issuer, zorginzage.ServiceName, "fhir") - if err != nil { - return nil, fmt.Errorf("error while looking up authorizer's FHIR server (did=%s): %w", issuer, err) - } - - issuerOrg, err := service.registry.Get(ctx, issuer) - if err != nil { - return nil, fmt.Errorf("error while searching organization :%w", err) - } - - // TODO: Should be user access token? - accessToken, err := service.nutsClient.RequestServiceAccessToken(ctx, customerDID, issuer, zorginzage.ServiceName) - if err != nil { - return nil, err - } - - episodeOfCareID, err := parseEpisodeOfCareID(credentials[0]) - if err != nil { - return nil, err - } - - fhirClient := fhir.NewFactory(fhir.WithURL(fhirServer), fhir.WithAuthToken(accessToken))() - - fhirEpisode := &fhir.EpisodeOfCare{} - err = fhirClient.ReadOne(ctx, "/EpisodeOfCare/"+episodeOfCareID, fhirEpisode) - if err != nil { - return nil, fmt.Errorf("could not retrieve episode of care: %w", err) - } - episode := zorginzage.ToEpisode(fhirEpisode) - - observations := []resources.Observation{} - if err := fhirClient.ReadMultiple(ctx, "/Observation", map[string]string{ - "context": fmt.Sprintf("EpisodeOfCare/%s", episodeOfCareID), - //"subject": fmt.Sprintf("Patient/%s", patientSSN), - }, &observations); err != nil { - return nil, err - } - - results := make([]types.Report, len(observations)) - - for _, observation := range observations { - domainObservation := reports.ConvertToDomain(&observation, fhir.FromStringPtr(observation.Subject.ID)) - domainObservation.Source = issuerOrg.Details.Name - domainObservation.EpisodeName = &episode.Diagnosis - results = append(results, domainObservation) - } - - return results, nil + return nil, errors.New("not implemented") + //credentials, err := service.vcr.FindAuthorizationCredentials( + // ctx, + // ®istry.VCRSearchParams{ + // PurposeOfUse: zorginzage.ServiceName, + // SubjectID: customerDID, + // Subject: ssnURN(patientSSN), + // }, + //) + //if err != nil { + // return nil, err + //} + // + //if len(credentials) == 0 { + // return []types.Report{}, nil + //} + // + //// TODO: loop over all credentials + //issuer := credentials[0].Issuer.String() + // + //fhirServer, err := service.registry.GetCompoundServiceEndpoint(ctx, issuer, zorginzage.ServiceName, "fhir") + //if err != nil { + // return nil, fmt.Errorf("error while looking up authorizer's FHIR server (did=%s): %w", issuer, err) + //} + // + //issuerOrg, err := service.registry.Get(ctx, issuer) + //if err != nil { + // return nil, fmt.Errorf("error while searching organization :%w", err) + //} + // + //// TODO: Should be user access token? + //accessToken, err := service.nutsClient.RequestServiceAccessToken(ctx, customerDID, issuer, zorginzage.ServiceName) + //if err != nil { + // return nil, err + //} + // + //episodeOfCareID, err := parseEpisodeOfCareID(credentials[0]) + //if err != nil { + // return nil, err + //} + // + //fhirClient := fhir.NewFactory(fhir.WithURL(fhirServer), fhir.WithAuthToken(accessToken))() + // + //fhirEpisode := &fhir.EpisodeOfCare{} + //err = fhirClient.ReadOne(ctx, "/EpisodeOfCare/"+episodeOfCareID, fhirEpisode) + //if err != nil { + // return nil, fmt.Errorf("could not retrieve episode of care: %w", err) + //} + //episode := zorginzage.ToEpisode(fhirEpisode) + // + //observations := []resources.Observation{} + //if err := fhirClient.ReadMultiple(ctx, "/Observation", map[string]string{ + // "context": fmt.Sprintf("EpisodeOfCare/%s", episodeOfCareID), + // //"subject": fmt.Sprintf("Patient/%s", patientSSN), + //}, &observations); err != nil { + // return nil, err + //} + // + //results := make([]types.Report, len(observations)) + // + //for _, observation := range observations { + // domainObservation := reports.ConvertToDomain(&observation, fhir.FromStringPtr(observation.Subject.ID)) + // domainObservation.Source = issuerOrg.Details.Name + // domainObservation.EpisodeName = &episode.Diagnosis + // results = append(results, domainObservation) + //} + // + //return results, nil } diff --git a/domain/notification/handler.go b/domain/notification/handler.go index 405da608..e4667088 100644 --- a/domain/notification/handler.go +++ b/domain/notification/handler.go @@ -28,7 +28,6 @@ type handler struct { localFHIRClientFactory fhir.Factory transferService receiver.TransferService registry registry.OrganizationRegistry - vcr registry.VerifiableCredentialRegistry } func NewHandler( @@ -36,14 +35,12 @@ func NewHandler( localFHIRClientFactory fhir.Factory, transferReceiverService receiver.TransferService, registry registry.OrganizationRegistry, - vcr registry.VerifiableCredentialRegistry, ) Handler { return &handler{ nutsClient: nutsClient, localFHIRClientFactory: localFHIRClientFactory, transferService: transferReceiverService, registry: registry, - vcr: vcr, } } diff --git a/domain/transfer/receiver/service.go b/domain/transfer/receiver/service.go index a20e4c9f..bfadb9cf 100644 --- a/domain/transfer/receiver/service.go +++ b/domain/transfer/receiver/service.go @@ -26,17 +26,15 @@ type service struct { localFHIRClientFactory fhir.Factory // client for interacting with the local FHIR server customerRepo customers.Repository registry registry.OrganizationRegistry - vcr registry.VerifiableCredentialRegistry } -func NewTransferService(nutsClient *client.HTTPClient, localFHIRClientFactory fhir.Factory, transferRepository TransferRepository, customerRepository customers.Repository, organizationRegistry registry.OrganizationRegistry, vcr registry.VerifiableCredentialRegistry, notifier transfer.Notifier) TransferService { +func NewTransferService(nutsClient *client.HTTPClient, localFHIRClientFactory fhir.Factory, transferRepository TransferRepository, customerRepository customers.Repository, organizationRegistry registry.OrganizationRegistry, notifier transfer.Notifier) TransferService { return &service{ nutsClient: nutsClient, localFHIRClientFactory: localFHIRClientFactory, transferRepo: transferRepository, customerRepo: customerRepository, registry: organizationRegistry, - vcr: vcr, notifier: notifier, } } diff --git a/domain/transfer/sender/service.go b/domain/transfer/sender/service.go index a2326320..d2c76cbd 100644 --- a/domain/transfer/sender/service.go +++ b/domain/transfer/sender/service.go @@ -4,15 +4,10 @@ import ( "context" "errors" "fmt" - nutsClient "github.com/nuts-foundation/nuts-demo-ehr/nuts/client" "strings" "time" "github.com/avast/retry-go/v4" - - sqlUtil "github.com/nuts-foundation/nuts-demo-ehr/sql" - "github.com/sirupsen/logrus" - "github.com/nuts-foundation/nuts-demo-ehr/domain/customers" "github.com/nuts-foundation/nuts-demo-ehr/domain/dossier" "github.com/nuts-foundation/nuts-demo-ehr/domain/fhir" @@ -20,7 +15,11 @@ import ( "github.com/nuts-foundation/nuts-demo-ehr/domain/patients" "github.com/nuts-foundation/nuts-demo-ehr/domain/transfer" "github.com/nuts-foundation/nuts-demo-ehr/domain/types" + nutsClient "github.com/nuts-foundation/nuts-demo-ehr/nuts/client" "github.com/nuts-foundation/nuts-demo-ehr/nuts/registry" + "github.com/nuts-foundation/nuts-demo-ehr/nutspxp/client" + sqlUtil "github.com/nuts-foundation/nuts-demo-ehr/sql" + "github.com/sirupsen/logrus" ) type TransferService interface { @@ -51,25 +50,25 @@ type TransferService interface { type service struct { transferRepo TransferRepository nutsClient *nutsClient.HTTPClient + pipClient nutspxp.Client localFHIRClientFactory fhir.Factory // client for interacting with the local FHIR server customerRepo customers.Repository dossierRepo dossier.Repository patientRepo patients.Repository registry registry.OrganizationRegistry - vcr registry.VerifiableCredentialRegistry notifier transfer.Notifier } -func NewTransferService(nutsClient *nutsClient.HTTPClient, localFHIRClientFactory fhir.Factory, transferRepository TransferRepository, customerRepository customers.Repository, dossierRepo dossier.Repository, patientRepo patients.Repository, organizationRegistry registry.OrganizationRegistry, vcr registry.VerifiableCredentialRegistry, notifier transfer.Notifier) TransferService { +func NewTransferService(nutsClient *nutsClient.HTTPClient, pipClient nutspxp.Client, localFHIRClientFactory fhir.Factory, transferRepository TransferRepository, customerRepository customers.Repository, dossierRepo dossier.Repository, patientRepo patients.Repository, organizationRegistry registry.OrganizationRegistry, notifier transfer.Notifier) TransferService { return &service{ nutsClient: nutsClient, + pipClient: pipClient, localFHIRClientFactory: localFHIRClientFactory, transferRepo: transferRepository, customerRepo: customerRepository, dossierRepo: dossierRepo, patientRepo: patientRepo, registry: organizationRegistry, - vcr: vcr, notifier: notifier, } } @@ -183,17 +182,9 @@ func (s service) CreateNegotiation(ctx context.Context, customerID int, transfer } // Build the list of resources for the authorization credential: - authorizedResources := []registry.Resource{ - { - Path: fmt.Sprintf("/Task/%s", transferTask.ID), - Operations: []string{"read", "update"}, - }, - { - Path: compositionPath, - Operations: []string{"read", "document"}, - UserContext: true, - AssuranceLevel: assuranceLevelLow(), - }, + authorizedResources := map[string]interface{}{ + fmt.Sprintf("/Task/%s", transferTask.ID): []string{"GET"}, + compositionPath: []string{"GET"}, } // A list to store all the paths to FHIR resources associated with this advance notice @@ -202,22 +193,11 @@ func (s service) CreateNegotiation(ctx context.Context, customerID int, transfer // Include subject reference (patient) resourcePaths = append(resourcePaths, fhir.FromStringPtr(composition.Subject.Reference)) for _, path := range resourcePaths { - authorizedResources = append(authorizedResources, registry.Resource{ - Path: path, - Operations: []string{"read", "document"}, - UserContext: true, - AssuranceLevel: assuranceLevelLow(), - }) - } - - // no longer needed - //if err := s.vcr.CreateAuthorizationCredential(ctx, *customer.Did, ®istry.NutsAuthorizationCredentialSubject{ - // ID: organizationDID, - // PurposeOfUse: transfer.SenderServiceName, - // Resources: authorizedResources, - //}); err != nil { - // return nil, err - //} + authorizedResources[path] = []string{"GET"} + } + if err := s.pipClient.AddPIPData(transferTask.ID, organizationDID, transfer.SenderServiceName, *customer.Did, authorizedResources); err != nil { + return nil, fmt.Errorf("could not create PIP data: %w", err) + } negotiation, err = s.transferRepo.CreateNegotiation(ctx, customerID, transferID, organizationDID, dbTransfer.TransferDate.Time, transferTask.ID) if err != nil { @@ -338,15 +318,12 @@ func (s service) ConfirmNegotiation(ctx context.Context, customerID int, transfe } // Revoke the old AuthorizationCredential for the Task and AdvanceNotice - if err = s.vcr.RevokeAuthorizationCredential(ctx, transfer.SenderServiceName, negotiation.OrganizationDID, advanceNoticePath); err != nil { + if err = s.pipClient.DeletePIPData(negotiation.TaskID); err != nil { return nil, fmt.Errorf("unable to confirm negotiation: could not revoke advance notice authorization credential: %w", err) } - authorizedResources := []registry.Resource{ - { - Path: fmt.Sprintf("/Task/%s", negotiation.TaskID), - Operations: []string{"read", "update"}, - }, + authorizedResources := map[string]interface{}{ + fmt.Sprintf("/Task/%s", negotiation.TaskID): []string{"GET"}, } compositionPath := fmt.Sprintf("/Composition/%s", fhir.FromIDPtr(compositionID)) // Add paths of resources of both the advance notice and the nursing handoff @@ -362,24 +339,13 @@ func (s service) ConfirmNegotiation(ctx context.Context, customerID int, transfe if _, exists := processedPaths[path]; exists { continue } - authorizedResources = append(authorizedResources, registry.Resource{ - Path: path, - Operations: []string{"read", "document"}, - UserContext: true, - AssuranceLevel: assuranceLevelLow(), - }) + authorizedResources[path] = []string{"GET"} processedPaths[path] = struct{}{} } - // Create a new AuthorizationCredential for the Task, AdvanceNotice and NursingHandoff - // no longer needed - //if err = s.vcr.CreateAuthorizationCredential(ctx, *customer.Did, ®istry.NutsAuthorizationCredentialSubject{ - // ID: negotiation.OrganizationDID, - // PurposeOfUse: transfer.SenderServiceName, - // Resources: authorizedResources, - //}); err != nil { - // return nil, fmt.Errorf("unable to confirm negotiation: could not create authorization credential: %w", err) - //} + if err := s.pipClient.AddPIPData(negotiation.TaskID, negotiation.OrganizationDID, transfer.SenderServiceName, *customer.Did, authorizedResources); err != nil { + return nil, fmt.Errorf("could not create PIP data: %w", err) + } notifications = append(notifications, ¬ification{ customer: customer, @@ -506,10 +472,8 @@ func (s service) completeTask(ctx context.Context, customer types.Customer, nego return nil, err } - // reconstruct composition path - compositionPath := fmt.Sprintf("/Composition/%s", *transferRecord.FhirNursingHandoffComposition) // revoke authorization credential - if err = s.vcr.RevokeAuthorizationCredential(ctx, transfer.SenderServiceName, negotiation.OrganizationDID, compositionPath); err != nil { + if err = s.pipClient.DeletePIPData(negotiation.TaskID); err != nil { return nil, err } @@ -555,8 +519,7 @@ func (s service) cancelNegotiation(ctx context.Context, customerID int, negotiat return nil, nil, err } - // revoke credential, find by AdvanceNotice - if err = s.vcr.RevokeAuthorizationCredential(ctx, transfer.SenderServiceName, negotiation.OrganizationDID, advanceNoticePath); err != nil { + if err = s.pipClient.DeletePIPData(negotiation.TaskID); err != nil { return nil, nil, err } @@ -678,10 +641,10 @@ func (s service) AssignTransfer(ctx context.Context, customerID int, transferID, return nil, fmt.Errorf("could not create FHIR task: %w", err) } - // no longer needed to create auth creds - //if err := s.createAuthCredentials(ctx, &transferTask, nursingHandoffComposition, *customer.Did, organizationDID); err != nil { - // return nil, err - //} + // store auth in pip + if err := s.createAuthorizations(ctx, &transferTask, nursingHandoffComposition, *customer.Did, organizationDID); err != nil { + return nil, err + } negotiation, err = s.transferRepo.CreateNegotiation(ctx, customerID, transferID, organizationDID, dbTransfer.TransferDate.Time, transferTask.ID) if err != nil { @@ -710,27 +673,13 @@ func (s service) AssignTransfer(ctx context.Context, customerID int, transferID, return negotiation, err } -// createAuthCredentials creates 2 authorization credentials, one for the Task, and one for the nursingHandoffComposition. -func (s service) createAuthCredentials(ctx context.Context, transferTask *eoverdracht.TransferTask, nursingHandoffComposition *fhir.Composition, customerDID, organizationDID string) error { - // Create an Auth Credential for the Task - authorizedTask := s.taskForNursingHandoff(transferTask.ID) - if err := s.vcr.CreateAuthorizationCredential(ctx, customerDID, ®istry.NutsAuthorizationCredentialSubject{ - ID: organizationDID, - PurposeOfUse: transfer.SenderServiceName, - Resources: authorizedTask, - }); err != nil { - return err - } - +// createAuthorizations creates 2 authorization credentials, one for the Task, and one for the nursingHandoffComposition. +func (s service) createAuthorizations(ctx context.Context, transferTask *eoverdracht.TransferTask, nursingHandoffComposition *fhir.Composition, customerDID, organizationDID string) error { // Build the list of resources for the authorization credential: authorizedResources := s.resourcesForNursingHandoff(nursingHandoffComposition) - - if err := s.vcr.CreateAuthorizationCredential(ctx, customerDID, ®istry.NutsAuthorizationCredentialSubject{ - ID: organizationDID, - PurposeOfUse: transfer.SenderServiceName, - Resources: authorizedResources, - }); err != nil { - return err + authorizedResources[fmt.Sprintf("/Task/%s", transferTask.ID)] = []string{"GET", "PUT"} + if err := s.pipClient.AddPIPData(transferTask.ID, organizationDID, transfer.SenderServiceName, customerDID, authorizedResources); err != nil { + return fmt.Errorf("could not create PIP data: %w", err) } return nil } @@ -754,39 +703,15 @@ func (s service) advanceNoticeToNursingHandoff(ctx context.Context, customerID i return &nursingHandoffComposition, err } -func (s service) taskForNursingHandoff(taskID string) []registry.Resource { - return []registry.Resource{ - { - Path: fmt.Sprintf("/Task/%s", taskID), - Operations: []string{"read", "update"}, - }, - } -} - -func (s service) resourcesForNursingHandoff(nursingHandoffComposition *fhir.Composition) []registry.Resource { - authorizedResources := []registry.Resource{ - { - Path: fmt.Sprintf("/Composition/%s", fhir.FromIDPtr(nursingHandoffComposition.ID)), - Operations: []string{"read", "document"}, - UserContext: true, - AssuranceLevel: assuranceLevelLow(), - }, - { - Path: fmt.Sprintf("/%s", fhir.FromStringPtr(nursingHandoffComposition.Subject.Reference)), - Operations: []string{"read"}, - UserContext: true, - AssuranceLevel: assuranceLevelLow(), - }, +func (s service) resourcesForNursingHandoff(nursingHandoffComposition *fhir.Composition) map[string]interface{} { + authorizedResources := map[string]interface{}{ + fmt.Sprintf("/Composition/%s", fhir.FromIDPtr(nursingHandoffComposition.ID)): []string{"GET"}, + fmt.Sprintf("/%s", fhir.FromStringPtr(nursingHandoffComposition.Subject.Reference)): []string{"GET"}, } // Add paths of resources of both the advance notice and the nursing handoff resourcePaths := resourcePathsFromSection(nursingHandoffComposition.Section, []string{}) for _, path := range resourcePaths { - authorizedResources = append(authorizedResources, registry.Resource{ - Path: path, - Operations: []string{"read"}, - UserContext: true, - AssuranceLevel: assuranceLevelLow(), - }) + authorizedResources[path] = []string{"GET"} } return authorizedResources } diff --git a/main.go b/main.go index 510d6521..ec800930 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,7 @@ import ( "github.com/nuts-foundation/nuts-demo-ehr/domain" "github.com/nuts-foundation/nuts-demo-ehr/domain/acl" "github.com/nuts-foundation/nuts-demo-ehr/domain/sharedcareplan" + nutspxp "github.com/nuts-foundation/nuts-demo-ehr/nutspxp/client" openapiTypes "github.com/oapi-codegen/runtime/types" "io" @@ -94,12 +95,12 @@ func main() { // init node API nutsClient nodeClient := nutsClient.HTTPClient{NutsNodeAddress: config.NutsNodeAddress, Authorizer: authorizer} - vcRegistry := registry.NewVerifiableCredentialRegistry(&nodeClient) + pipClient := nutspxp.HTTPClient{PIPAddress: config.NutsPIPAddress} customerRepository := customers.NewJsonFileRepository(config.CustomersFile) server := createServer() - registerEHR(server, config, customerRepository, vcRegistry, &nodeClient) + registerEHR(server, config, customerRepository, &nodeClient, pipClient) // Start server server.Logger.Fatal(server.Start(fmt.Sprintf(":%d", config.HTTPPort))) @@ -131,7 +132,7 @@ func createServer() *echo.Echo { return server } -func registerEHR(server *echo.Echo, config Config, customerRepository customers.Repository, vcRegistry registry.VerifiableCredentialRegistry, nodeClient *nutsClient.HTTPClient) { +func registerEHR(server *echo.Echo, config Config, customerRepository customers.Repository, nodeClient *nutsClient.HTTPClient, pipClient nutspxp.Client) { var passwd string if config.Credentials.Empty() { passwd = generateAuthenticationPassword(config) @@ -166,8 +167,8 @@ func registerEHR(server *echo.Echo, config Config, customerRepository customers. dossierRepository := dossier.NewSQLiteDossierRepository(dossier.Factory{}, sqlDB) transferSenderRepo := sender.NewTransferRepository(sqlDB) transferReceiverRepo := receiver.NewTransferRepository(sqlDB) - transferSenderService := sender.NewTransferService(nodeClient, fhirClientFactory, transferSenderRepo, customerRepository, dossierRepository, patientRepository, orgRegistry, vcRegistry, fhirNotifier) - transferReceiverService := receiver.NewTransferService(nodeClient, fhirClientFactory, transferReceiverRepo, customerRepository, orgRegistry, vcRegistry, fhirNotifier) + transferSenderService := sender.NewTransferService(nodeClient, pipClient, fhirClientFactory, transferSenderRepo, customerRepository, dossierRepository, patientRepository, orgRegistry, fhirNotifier) + transferReceiverService := receiver.NewTransferService(nodeClient, fhirClientFactory, transferReceiverRepo, customerRepository, orgRegistry, fhirNotifier) tenantInitializer := func(tenant int) error { if !config.FHIR.Server.SupportsMultiTenancy() { return nil @@ -223,9 +224,9 @@ func registerEHR(server *echo.Echo, config Config, customerRepository customers. ZorginzageService: domain.ZorginzageService{NutsClient: nodeClient}, SharedCarePlanService: scpService, FHIRService: fhir.Service{ClientFactory: fhirClientFactory}, - EpisodeService: episode.NewService(fhirClientFactory, nodeClient, orgRegistry, vcRegistry, aclRepository), + EpisodeService: episode.NewService(fhirClientFactory, nodeClient, orgRegistry, aclRepository), TenantInitializer: tenantInitializer, - NotificationHandler: notification.NewHandler(nodeClient, fhirClientFactory, transferReceiverService, orgRegistry, vcRegistry), + NotificationHandler: notification.NewHandler(nodeClient, fhirClientFactory, transferReceiverService, orgRegistry), } // JWT checking for correct claims diff --git a/nuts/client/vcr.go b/nuts/client/vcr.go deleted file mode 100644 index 2e4215a8..00000000 --- a/nuts/client/vcr.go +++ /dev/null @@ -1,156 +0,0 @@ -package client - -import ( - "context" - "encoding/json" - "github.com/nuts-foundation/go-did" - "github.com/nuts-foundation/go-did/vc" - "github.com/sirupsen/logrus" - "net/http" - "time" - - "github.com/nuts-foundation/nuts-demo-ehr/nuts/client/vcr" -) - -var NutsV1ContextURI = ssi.MustParseURI("https://nuts.nl/credentials/v1") -var VerifiableCredentialLDContextV1 = ssi.MustParseURI("https://www.w3.org/2018/credentials/v1") - -type VCRClient interface { - CreateVC(ctx context.Context, typeName, issuer string, credentialSubject map[string]interface{}, expirationDate *time.Time, publishPublic bool) error - FindCredentials(ctx context.Context, credential vcr.SearchVCQuery, untrusted bool) ([]vc.VerifiableCredential, error) - FindCredentialIDs(ctx context.Context, credential vcr.SearchVCQuery, untrusted bool) ([]string, error) - RevokeCredential(ctx context.Context, credentialID string) error - ResolveCredential(ctx context.Context, credentialID string) (*vc.VerifiableCredential, error) -} - -func (c HTTPClient) CreateVC(ctx context.Context, typeName, issuer string, credentialSubject map[string]interface{}, expirationDate *time.Time, publishPublic bool) error { - var exp *string - - if expirationDate != nil { - formatted := expirationDate.Format(time.RFC3339) - exp = &formatted - } - - var visibility vcr.IssueVCRequestVisibility - if publishPublic { - visibility = vcr.Public - } else { - visibility = vcr.Private - } - t := new(vcr.IssueVCRequest_Type) - _ = t.FromIssueVCRequestType0(typeName) - response, err := c.vcr().IssueVC(ctx, vcr.IssueVCJSONRequestBody{ - Type: *t, - Issuer: issuer, - CredentialSubject: credentialSubject, - ExpirationDate: exp, - Visibility: &visibility, - }) - if err != nil { - return err - } - - body, err := testAndReadResponse(http.StatusOK, response) - if err != nil { - return err - } - logrus.Debugf("VC created, reponse: %s", body) - - return nil -} - -func (c HTTPClient) FindCredentials(ctx context.Context, credential vcr.SearchVCQuery, untrusted bool) ([]vc.VerifiableCredential, error) { - return c.search(ctx, credential, untrusted) -} - -func (c HTTPClient) FindCredentialIDs(ctx context.Context, credential vcr.SearchVCQuery, untrusted bool) ([]string, error) { - credentials, err := c.search(ctx, credential, untrusted) - if err != nil { - return nil, err - } - var credentialIDs = make([]string, len(credentials)) - j := 0 - for _, curr := range credentials { - if curr.ID != nil { - credentialIDs[j] = curr.ID.String() - j++ - } - } - return credentialIDs[:j], nil -} - -func (c HTTPClient) RevokeCredential(ctx context.Context, credentialID string) error { - response, err := c.vcr().RevokeVC(ctx, credentialID) - if err != nil { - return err - } - _, err = testAndReadResponse(http.StatusOK, response) - return err -} - -func (c HTTPClient) ResolveCredential(ctx context.Context, credentialID string) (*vc.VerifiableCredential, error) { - response, err := c.vcr().ResolveVC(ctx, credentialID) - if err != nil { - return nil, err - } - data, err := testAndReadResponse(http.StatusOK, response) - if err != nil { - return nil, err - } - var result vc.VerifiableCredential - if err := json.Unmarshal(data, &result); err != nil { - return nil, err - } - return &result, nil -} - -func GetNutsCredentialTemplate(credentialType ssi.URI) vcr.SearchVCQuery { - return vcr.SearchVCQuery{ - Context: []ssi.URI{VerifiableCredentialLDContextV1, NutsV1ContextURI}, - Type: []ssi.URI{vc.VerifiableCredentialTypeV1URI(), credentialType}, - } -} - -func (c HTTPClient) search(ctx context.Context, credential vcr.SearchVCQuery, untrusted bool) ([]vc.VerifiableCredential, error) { - response, err := c.vcr().SearchVCs(ctx, vcr.SearchVCsJSONRequestBody{Query: credential, SearchOptions: &vcr.SearchOptions{ - AllowUntrustedIssuer: &untrusted, - }}) - if err != nil { - return nil, err - } - - if err := testResponseCode(http.StatusOK, response); err != nil { - return nil, err - } - - searchResponse, err := vcr.ParseSearchVCsResponse(response) - if err != nil { - return nil, err - } - - var result []vc.VerifiableCredential - for _, curr := range searchResponse.JSON200.VerifiableCredentials { - if curr.Revocation == nil { - result = append(result, curr.VerifiableCredential) - } - } - - return result, nil -} - -func (c HTTPClient) vcr() vcr.ClientInterface { - var response vcr.ClientInterface - var err error - - if c.Authorizer != nil { - requestEditorFn := vcr.RequestEditorFn(c.Authorizer.RequestEditorFn()) - response, err = vcr.NewClientWithResponses(c.getNodeURL(), vcr.WithRequestEditorFn(requestEditorFn)) - } else { - response, err = vcr.NewClientWithResponses(c.getNodeURL()) - } - - if err != nil { - panic(err) - } - return response -} diff --git a/nuts/client/vcr/generated.go b/nuts/client/vcr/generated.go deleted file mode 100644 index 40f56b3b..00000000 --- a/nuts/client/vcr/generated.go +++ /dev/null @@ -1,2804 +0,0 @@ -// Package vcr provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/deepmap/oapi-codegen/v2 version v2.1.0 DO NOT EDIT. -package vcr - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - externalRef0 "github.com/nuts-foundation/nuts-demo-ehr/nuts/client/common" - "github.com/oapi-codegen/runtime" -) - -const ( - JwtBearerAuthScopes = "jwtBearerAuth.Scopes" -) - -// Defines values for CreateVPRequestFormat. -const ( - JwtVp CreateVPRequestFormat = "jwt_vp" - LdpVp CreateVPRequestFormat = "ldp_vp" -) - -// Defines values for CreateVPRequestProofPurpose. -const ( - AssertionMethod CreateVPRequestProofPurpose = "assertionMethod" - Authentication CreateVPRequestProofPurpose = "authentication" - CapabilityDelegation CreateVPRequestProofPurpose = "capabilityDelegation" - CapabilityInvocation CreateVPRequestProofPurpose = "capabilityInvocation" - KeyAgreement CreateVPRequestProofPurpose = "keyAgreement" -) - -// Defines values for IssueVCRequestFormat. -const ( - JwtVc IssueVCRequestFormat = "jwt_vc" - LdpVc IssueVCRequestFormat = "ldp_vc" -) - -// Defines values for IssueVCRequestVisibility. -const ( - Private IssueVCRequestVisibility = "private" - Public IssueVCRequestVisibility = "public" -) - -// CreateVPRequest A request for creating a new Verifiable Presentation for a set of Verifiable Credentials. -type CreateVPRequest struct { - // Context Array of JSON-LD contexts, contain definitions of the given types. - Context *[]string `json:"@context,omitempty"` - - // Challenge A random or pseudo-random value used by some authentication protocols to mitigate replay attacks. - Challenge *string `json:"challenge,omitempty"` - - // Domain A string value that specifies the operational domain of a digital proof. This could be an Internet domain - // name like example.com, an ad-hoc value such as mycorp-level3-access, or a very specific transaction value - // like 8zF6T$mqP. A signer could include a domain in its digital proof to restrict its use to particular - // target, identified by the specified domain. - Domain *string `json:"domain,omitempty"` - - // Expires Date and time at which proof will expire. If omitted, the proof does not have an end date. - Expires *string `json:"expires,omitempty"` - - // Format Proof format for the presentation (JSON-LD or JWT). If not set, it defaults to JSON-LD. - Format *CreateVPRequestFormat `json:"format,omitempty"` - - // ProofPurpose The specific intent for the proof, the reason why an entity created it. Acts as a safeguard to prevent the - // proof from being misused for a purpose other than the one it was intended for. - ProofPurpose *CreateVPRequestProofPurpose `json:"proofPurpose,omitempty"` - - // SignerDID Specifies the DID of the signing party that must be used to create the digital signature. - // If not specified, it is derived from the given Verifiable Credentials' subjectCredential ID. - // It can only be derived if all given Verifiable Credentials have the same, single subjectCredential. - SignerDID *string `json:"signerDID,omitempty"` - - // Type Array of VerifiablePresentation types that will be added next to the default type. Types must be available in the given context. - Type *[]string `json:"type,omitempty"` - VerifiableCredentials []VerifiableCredential `json:"verifiableCredentials"` -} - -// CreateVPRequestFormat Proof format for the presentation (JSON-LD or JWT). If not set, it defaults to JSON-LD. -type CreateVPRequestFormat string - -// CreateVPRequestProofPurpose The specific intent for the proof, the reason why an entity created it. Acts as a safeguard to prevent the -// proof from being misused for a purpose other than the one it was intended for. -type CreateVPRequestProofPurpose string - -// CredentialIssuer defines model for CredentialIssuer. -type CredentialIssuer struct { - // CredentialType a credential type - CredentialType string `json:"credentialType"` - - // Issuer the DID of an issuer - Issuer string `json:"issuer"` -} - -// IssueVCRequest A request for issuing a new Verifiable Credential. -type IssueVCRequest struct { - // Context The resolvable context of the credentialSubject as URI. If omitted, the "https://nuts.nl/credentials/v1" context is used. - Context *IssueVCRequest_Context `json:"@context,omitempty"` - - // CredentialSubject Subject of a Verifiable Credential identifying the holder and expressing claims. - CredentialSubject CredentialSubject `json:"credentialSubject"` - - // ExpirationDate RFC3339 time string until when the credential is valid. - ExpirationDate *string `json:"expirationDate,omitempty"` - - // Format Proof format for the credential (ldp_vc for JSON-LD or jwt_vc for JWT). If not set, it defaults to JSON-LD. - Format *IssueVCRequestFormat `json:"format,omitempty"` - - // Issuer DID according to Nuts specification. - Issuer string `json:"issuer"` - - // PublishToNetwork If set, the node publishes this credential to the network. This is the default behaviour. - // When set to false, the caller is responsible for distributing the VC to a holder. When the issuer is - // also the holder, it then can be used to directly create a presentation (self issued). - // Note: a not published credential can still be publicly revoked. - // Only valid for did:nuts issuers. - PublishToNetwork *bool `json:"publishToNetwork,omitempty"` - - // Type Type definition for the credential. - Type IssueVCRequest_Type `json:"type"` - - // Visibility When publishToNetwork is true, the credential can be published publicly or privately to the holder. - // This field is mandatory if publishToNetwork is true to prevent accidents. It defaults to "private". - // Only valid for did:nuts issuers. - Visibility *IssueVCRequestVisibility `json:"visibility,omitempty"` - - // WithStatusList2021Revocation Add a credentialStatus with statusPurpose 'revocation' to the issued credential. This allows a credential to - // be revoked using the referenced StatusList2021Credential. StatusPurpose 'suspension' is not supported (yet). - // See https://www.w3.org/TR/2023/WD-vc-status-list-20230427/ - // - // Credentials with a short lifespan (expiry) are preferred over adding a credentialStatus. - // This is a required field for credentials without an expirationDate. - // Only valid for did:web issuers. - WithStatusList2021Revocation *bool `json:"withStatusList2021Revocation,omitempty"` -} - -// IssueVCRequestContext0 defines model for . -type IssueVCRequestContext0 = string - -// IssueVCRequestContext1 defines model for . -type IssueVCRequestContext1 = []string - -// IssueVCRequest_Context The resolvable context of the credentialSubject as URI. If omitted, the "https://nuts.nl/credentials/v1" context is used. -type IssueVCRequest_Context struct { - union json.RawMessage -} - -// IssueVCRequestFormat Proof format for the credential (ldp_vc for JSON-LD or jwt_vc for JWT). If not set, it defaults to JSON-LD. -type IssueVCRequestFormat string - -// IssueVCRequestType0 defines model for . -type IssueVCRequestType0 = string - -// IssueVCRequestType1 defines model for . -type IssueVCRequestType1 = []string - -// IssueVCRequest_Type Type definition for the credential. -type IssueVCRequest_Type struct { - union json.RawMessage -} - -// IssueVCRequestVisibility When publishToNetwork is true, the credential can be published publicly or privately to the holder. -// This field is mandatory if publishToNetwork is true to prevent accidents. It defaults to "private". -// Only valid for did:nuts issuers. -type IssueVCRequestVisibility string - -// Revocation Credential revocation record -type Revocation = externalRef0.Revocation - -// SearchOptions defines model for SearchOptions. -type SearchOptions struct { - // AllowUntrustedIssuer If set to true, VCs from an untrusted issuer are returned. - AllowUntrustedIssuer *bool `json:"allowUntrustedIssuer,omitempty"` -} - -// SearchVCResult Result of a Search operation. -// The revocation property is only present if a credential is revoked with a Verifiable Credential of type CredentialRevocation. -// The absence of a the revocation property does not indicate a valid credential, use the /internal/vcr/v2/verifier/vc API for this. -type SearchVCResult struct { - // Revocation Credential revocation record - Revocation *Revocation `json:"revocation,omitempty"` - - // VerifiableCredential A credential according to the W3C and Nuts specs. - VerifiableCredential VerifiableCredential `json:"verifiableCredential"` -} - -// SearchVCResults result of a Search operation. -type SearchVCResults struct { - VerifiableCredentials []SearchVCResult `json:"verifiableCredentials"` -} - -// VCVerificationOptions defines model for VCVerificationOptions. -type VCVerificationOptions struct { - // AllowUntrustedIssuer If set to true, an untrusted credential issuer is allowed. - // Deprecated: - AllowUntrustedIssuer *bool `json:"allowUntrustedIssuer,omitempty"` -} - -// VCVerificationRequest defines model for VCVerificationRequest. -type VCVerificationRequest struct { - // VerifiableCredential A credential according to the W3C and Nuts specs. - VerifiableCredential VerifiableCredential `json:"verifiableCredential"` - VerificationOptions *VCVerificationOptions `json:"verificationOptions,omitempty"` -} - -// VCVerificationResult Contains the verifiable credential verification result. -type VCVerificationResult struct { - // Message Indicates what went wrong - Message *string `json:"message,omitempty"` - - // Validity Indicates the validity of the signature, issuer and revocation state. - Validity bool `json:"validity"` -} - -// VPVerificationRequest defines model for VPVerificationRequest. -type VPVerificationRequest struct { - // ValidAt Date and time at which the VP should be valid. If not supplied, the current date/time is used. - ValidAt *string `json:"validAt,omitempty"` - - // VerifiablePresentation Verifiable Presentation - VerifiablePresentation VerifiablePresentation `json:"verifiablePresentation"` - - // VerifyCredentials Indicates whether the Verifiable Credentials within the VP must be verified, default true. - VerifyCredentials *bool `json:"verifyCredentials,omitempty"` -} - -// VPVerificationResult Contains the verifiable presentation verification result. -type VPVerificationResult struct { - // Credentials If the VP is valid, it will contain the credentials inside the VP. - Credentials *[]VerifiableCredential `json:"credentials,omitempty"` - - // Message Indicates what went wrong - Message *string `json:"message,omitempty"` - - // Validity Indicates the validity of the signature, issuer and revocation state. - Validity bool `json:"validity"` -} - -// VerifiableCredential A credential according to the W3C and Nuts specs. -type VerifiableCredential = externalRef0.VerifiableCredential - -// VerifiablePresentation Verifiable Presentation -type VerifiablePresentation = externalRef0.VerifiablePresentation - -// SearchIssuedVCsParams defines parameters for SearchIssuedVCs. -type SearchIssuedVCsParams struct { - // CredentialType The type of the credential - CredentialType string `form:"credentialType" json:"credentialType"` - - // Issuer the DID of the issuer - Issuer string `form:"issuer" json:"issuer"` - - // Subject the URI which indicates the subject (usually a DID) - Subject *string `form:"subject,omitempty" json:"subject,omitempty"` -} - -// CreateVPJSONRequestBody defines body for CreateVP for application/json ContentType. -type CreateVPJSONRequestBody = CreateVPRequest - -// LoadVCJSONRequestBody defines body for LoadVC for application/json ContentType. -type LoadVCJSONRequestBody = VerifiableCredential - -// IssueVCJSONRequestBody defines body for IssueVC for application/json ContentType. -type IssueVCJSONRequestBody = IssueVCRequest - -// SearchVCsJSONRequestBody defines body for SearchVCs for application/json ContentType. -type SearchVCsJSONRequestBody = SearchVCRequest - -// UntrustIssuerJSONRequestBody defines body for UntrustIssuer for application/json ContentType. -type UntrustIssuerJSONRequestBody = CredentialIssuer - -// TrustIssuerJSONRequestBody defines body for TrustIssuer for application/json ContentType. -type TrustIssuerJSONRequestBody = CredentialIssuer - -// VerifyVCJSONRequestBody defines body for VerifyVC for application/json ContentType. -type VerifyVCJSONRequestBody = VCVerificationRequest - -// VerifyVPJSONRequestBody defines body for VerifyVP for application/json ContentType. -type VerifyVPJSONRequestBody = VPVerificationRequest - -// AsIssueVCRequestContext0 returns the union data inside the IssueVCRequest_Context as a IssueVCRequestContext0 -func (t IssueVCRequest_Context) AsIssueVCRequestContext0() (IssueVCRequestContext0, error) { - var body IssueVCRequestContext0 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromIssueVCRequestContext0 overwrites any union data inside the IssueVCRequest_Context as the provided IssueVCRequestContext0 -func (t *IssueVCRequest_Context) FromIssueVCRequestContext0(v IssueVCRequestContext0) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeIssueVCRequestContext0 performs a merge with any union data inside the IssueVCRequest_Context, using the provided IssueVCRequestContext0 -func (t *IssueVCRequest_Context) MergeIssueVCRequestContext0(v IssueVCRequestContext0) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsIssueVCRequestContext1 returns the union data inside the IssueVCRequest_Context as a IssueVCRequestContext1 -func (t IssueVCRequest_Context) AsIssueVCRequestContext1() (IssueVCRequestContext1, error) { - var body IssueVCRequestContext1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromIssueVCRequestContext1 overwrites any union data inside the IssueVCRequest_Context as the provided IssueVCRequestContext1 -func (t *IssueVCRequest_Context) FromIssueVCRequestContext1(v IssueVCRequestContext1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeIssueVCRequestContext1 performs a merge with any union data inside the IssueVCRequest_Context, using the provided IssueVCRequestContext1 -func (t *IssueVCRequest_Context) MergeIssueVCRequestContext1(v IssueVCRequestContext1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t IssueVCRequest_Context) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *IssueVCRequest_Context) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// AsIssueVCRequestType0 returns the union data inside the IssueVCRequest_Type as a IssueVCRequestType0 -func (t IssueVCRequest_Type) AsIssueVCRequestType0() (IssueVCRequestType0, error) { - var body IssueVCRequestType0 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromIssueVCRequestType0 overwrites any union data inside the IssueVCRequest_Type as the provided IssueVCRequestType0 -func (t *IssueVCRequest_Type) FromIssueVCRequestType0(v IssueVCRequestType0) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeIssueVCRequestType0 performs a merge with any union data inside the IssueVCRequest_Type, using the provided IssueVCRequestType0 -func (t *IssueVCRequest_Type) MergeIssueVCRequestType0(v IssueVCRequestType0) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -// AsIssueVCRequestType1 returns the union data inside the IssueVCRequest_Type as a IssueVCRequestType1 -func (t IssueVCRequest_Type) AsIssueVCRequestType1() (IssueVCRequestType1, error) { - var body IssueVCRequestType1 - err := json.Unmarshal(t.union, &body) - return body, err -} - -// FromIssueVCRequestType1 overwrites any union data inside the IssueVCRequest_Type as the provided IssueVCRequestType1 -func (t *IssueVCRequest_Type) FromIssueVCRequestType1(v IssueVCRequestType1) error { - b, err := json.Marshal(v) - t.union = b - return err -} - -// MergeIssueVCRequestType1 performs a merge with any union data inside the IssueVCRequest_Type, using the provided IssueVCRequestType1 -func (t *IssueVCRequest_Type) MergeIssueVCRequestType1(v IssueVCRequestType1) error { - b, err := json.Marshal(v) - if err != nil { - return err - } - - merged, err := runtime.JSONMerge(t.union, b) - t.union = merged - return err -} - -func (t IssueVCRequest_Type) MarshalJSON() ([]byte, error) { - b, err := t.union.MarshalJSON() - return b, err -} - -func (t *IssueVCRequest_Type) UnmarshalJSON(b []byte) error { - err := t.union.UnmarshalJSON(b) - return err -} - -// RequestEditorFn is the function signature for the RequestEditor callback function -type RequestEditorFn func(ctx context.Context, req *http.Request) error - -// Doer performs HTTP requests. -// -// The standard http.Client implements this interface. -type HttpRequestDoer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Client which conforms to the OpenAPI3 specification for this service. -type Client struct { - // The endpoint of the server conforming to this interface, with scheme, - // https://api.deepmap.com for example. This can contain a path relative - // to the server, such as https://api.deepmap.com/dev-test, and all the - // paths in the swagger spec will be appended to the server. - Server string - - // Doer for performing requests, typically a *http.Client with any - // customized settings, such as certificate chains. - Client HttpRequestDoer - - // A list of callbacks for modifying requests which are generated before sending over - // the network. - RequestEditors []RequestEditorFn -} - -// ClientOption allows setting custom parameters during construction -type ClientOption func(*Client) error - -// Creates a new Client, with reasonable defaults -func NewClient(server string, opts ...ClientOption) (*Client, error) { - // create a client with sane default values - client := Client{ - Server: server, - } - // mutate client and add all optional params - for _, o := range opts { - if err := o(&client); err != nil { - return nil, err - } - } - // ensure the server URL always has a trailing slash - if !strings.HasSuffix(client.Server, "/") { - client.Server += "/" - } - // create httpClient, if not already present - if client.Client == nil { - client.Client = &http.Client{} - } - return &client, nil -} - -// WithHTTPClient allows overriding the default Doer, which is -// automatically created using http.Client. This is useful for tests. -func WithHTTPClient(doer HttpRequestDoer) ClientOption { - return func(c *Client) error { - c.Client = doer - return nil - } -} - -// WithRequestEditorFn allows setting up a callback function, which will be -// called right before sending the request. This can be used to mutate the request. -func WithRequestEditorFn(fn RequestEditorFn) ClientOption { - return func(c *Client) error { - c.RequestEditors = append(c.RequestEditors, fn) - return nil - } -} - -// The interface specification for the client above. -type ClientInterface interface { - // CreateVPWithBody request with any body - CreateVPWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - CreateVP(ctx context.Context, body CreateVPJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // GetCredentialsInWallet request - GetCredentialsInWallet(ctx context.Context, did string, reqEditors ...RequestEditorFn) (*http.Response, error) - - // LoadVCWithBody request with any body - LoadVCWithBody(ctx context.Context, did string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - LoadVC(ctx context.Context, did string, body LoadVCJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // RemoveCredentialFromWallet request - RemoveCredentialFromWallet(ctx context.Context, did string, id string, reqEditors ...RequestEditorFn) (*http.Response, error) - - // IssueVCWithBody request with any body - IssueVCWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - IssueVC(ctx context.Context, body IssueVCJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // SearchIssuedVCs request - SearchIssuedVCs(ctx context.Context, params *SearchIssuedVCsParams, reqEditors ...RequestEditorFn) (*http.Response, error) - - // RevokeVC request - RevokeVC(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) - - // SearchVCsWithBody request with any body - SearchVCsWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - SearchVCs(ctx context.Context, body SearchVCsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // ResolveVC request - ResolveVC(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) - - // UntrustIssuerWithBody request with any body - UntrustIssuerWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - UntrustIssuer(ctx context.Context, body UntrustIssuerJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // TrustIssuerWithBody request with any body - TrustIssuerWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - TrustIssuer(ctx context.Context, body TrustIssuerJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // VerifyVCWithBody request with any body - VerifyVCWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - VerifyVC(ctx context.Context, body VerifyVCJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // VerifyVPWithBody request with any body - VerifyVPWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - - VerifyVP(ctx context.Context, body VerifyVPJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - - // ListTrusted request - ListTrusted(ctx context.Context, credentialType string, reqEditors ...RequestEditorFn) (*http.Response, error) - - // ListUntrusted request - ListUntrusted(ctx context.Context, credentialType string, reqEditors ...RequestEditorFn) (*http.Response, error) -} - -func (c *Client) CreateVPWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewCreateVPRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) CreateVP(ctx context.Context, body CreateVPJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewCreateVPRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) GetCredentialsInWallet(ctx context.Context, did string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetCredentialsInWalletRequest(c.Server, did) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) LoadVCWithBody(ctx context.Context, did string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewLoadVCRequestWithBody(c.Server, did, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) LoadVC(ctx context.Context, did string, body LoadVCJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewLoadVCRequest(c.Server, did, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) RemoveCredentialFromWallet(ctx context.Context, did string, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewRemoveCredentialFromWalletRequest(c.Server, did, id) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) IssueVCWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssueVCRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) IssueVC(ctx context.Context, body IssueVCJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewIssueVCRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) SearchIssuedVCs(ctx context.Context, params *SearchIssuedVCsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewSearchIssuedVCsRequest(c.Server, params) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) RevokeVC(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewRevokeVCRequest(c.Server, id) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) SearchVCsWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewSearchVCsRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) SearchVCs(ctx context.Context, body SearchVCsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewSearchVCsRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) ResolveVC(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewResolveVCRequest(c.Server, id) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) UntrustIssuerWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewUntrustIssuerRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) UntrustIssuer(ctx context.Context, body UntrustIssuerJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewUntrustIssuerRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) TrustIssuerWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTrustIssuerRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) TrustIssuer(ctx context.Context, body TrustIssuerJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewTrustIssuerRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) VerifyVCWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewVerifyVCRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) VerifyVC(ctx context.Context, body VerifyVCJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewVerifyVCRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) VerifyVPWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewVerifyVPRequestWithBody(c.Server, contentType, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) VerifyVP(ctx context.Context, body VerifyVPJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewVerifyVPRequest(c.Server, body) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) ListTrusted(ctx context.Context, credentialType string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewListTrustedRequest(c.Server, credentialType) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -func (c *Client) ListUntrusted(ctx context.Context, credentialType string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewListUntrustedRequest(c.Server, credentialType) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if err := c.applyEditors(ctx, req, reqEditors); err != nil { - return nil, err - } - return c.Client.Do(req) -} - -// NewCreateVPRequest calls the generic CreateVP builder with application/json body -func NewCreateVPRequest(server string, body CreateVPJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewCreateVPRequestWithBody(server, "application/json", bodyReader) -} - -// NewCreateVPRequestWithBody generates requests for CreateVP with any type of body -func NewCreateVPRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/holder/vp") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewGetCredentialsInWalletRequest generates requests for GetCredentialsInWallet -func NewGetCredentialsInWalletRequest(server string, did string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0 = did - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/holder/%s/vc", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewLoadVCRequest calls the generic LoadVC builder with application/json body -func NewLoadVCRequest(server string, did string, body LoadVCJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewLoadVCRequestWithBody(server, did, "application/json", bodyReader) -} - -// NewLoadVCRequestWithBody generates requests for LoadVC with any type of body -func NewLoadVCRequestWithBody(server string, did string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0 = did - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/holder/%s/vc", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewRemoveCredentialFromWalletRequest generates requests for RemoveCredentialFromWallet -func NewRemoveCredentialFromWalletRequest(server string, did string, id string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0 = did - - var pathParam1 string - - pathParam1, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/holder/%s/vc/%s", pathParam0, pathParam1) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("DELETE", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewIssueVCRequest calls the generic IssueVC builder with application/json body -func NewIssueVCRequest(server string, body IssueVCJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewIssueVCRequestWithBody(server, "application/json", bodyReader) -} - -// NewIssueVCRequestWithBody generates requests for IssueVC with any type of body -func NewIssueVCRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/issuer/vc") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewSearchIssuedVCsRequest generates requests for SearchIssuedVCs -func NewSearchIssuedVCsRequest(server string, params *SearchIssuedVCsParams) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/issuer/vc/search") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - if params != nil { - queryValues := queryURL.Query() - - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "credentialType", runtime.ParamLocationQuery, params.CredentialType); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "issuer", runtime.ParamLocationQuery, params.Issuer); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - if params.Subject != nil { - - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "subject", runtime.ParamLocationQuery, *params.Subject); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - } - - queryURL.RawQuery = queryValues.Encode() - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewRevokeVCRequest generates requests for RevokeVC -func NewRevokeVCRequest(server string, id string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/issuer/vc/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("DELETE", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewSearchVCsRequest calls the generic SearchVCs builder with application/json body -func NewSearchVCsRequest(server string, body SearchVCsJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewSearchVCsRequestWithBody(server, "application/json", bodyReader) -} - -// NewSearchVCsRequestWithBody generates requests for SearchVCs with any type of body -func NewSearchVCsRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/search") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewResolveVCRequest generates requests for ResolveVC -func NewResolveVCRequest(server string, id string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "id", runtime.ParamLocationPath, id) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/vc/%s", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewUntrustIssuerRequest calls the generic UntrustIssuer builder with application/json body -func NewUntrustIssuerRequest(server string, body UntrustIssuerJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewUntrustIssuerRequestWithBody(server, "application/json", bodyReader) -} - -// NewUntrustIssuerRequestWithBody generates requests for UntrustIssuer with any type of body -func NewUntrustIssuerRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/verifier/trust") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("DELETE", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewTrustIssuerRequest calls the generic TrustIssuer builder with application/json body -func NewTrustIssuerRequest(server string, body TrustIssuerJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewTrustIssuerRequestWithBody(server, "application/json", bodyReader) -} - -// NewTrustIssuerRequestWithBody generates requests for TrustIssuer with any type of body -func NewTrustIssuerRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/verifier/trust") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewVerifyVCRequest calls the generic VerifyVC builder with application/json body -func NewVerifyVCRequest(server string, body VerifyVCJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewVerifyVCRequestWithBody(server, "application/json", bodyReader) -} - -// NewVerifyVCRequestWithBody generates requests for VerifyVC with any type of body -func NewVerifyVCRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/verifier/vc") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewVerifyVPRequest calls the generic VerifyVP builder with application/json body -func NewVerifyVPRequest(server string, body VerifyVPJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewVerifyVPRequestWithBody(server, "application/json", bodyReader) -} - -// NewVerifyVPRequestWithBody generates requests for VerifyVP with any type of body -func NewVerifyVPRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { - var err error - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/verifier/vp") - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", queryURL.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", contentType) - - return req, nil -} - -// NewListTrustedRequest generates requests for ListTrusted -func NewListTrustedRequest(server string, credentialType string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "credentialType", runtime.ParamLocationPath, credentialType) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/verifier/%s/trusted", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -// NewListUntrustedRequest generates requests for ListUntrusted -func NewListUntrustedRequest(server string, credentialType string) (*http.Request, error) { - var err error - - var pathParam0 string - - pathParam0, err = runtime.StyleParamWithLocation("simple", false, "credentialType", runtime.ParamLocationPath, credentialType) - if err != nil { - return nil, err - } - - serverURL, err := url.Parse(server) - if err != nil { - return nil, err - } - - operationPath := fmt.Sprintf("/internal/vcr/v2/verifier/%s/untrusted", pathParam0) - if operationPath[0] == '/' { - operationPath = "." + operationPath - } - - queryURL, err := serverURL.Parse(operationPath) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", queryURL.String(), nil) - if err != nil { - return nil, err - } - - return req, nil -} - -func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { - for _, r := range c.RequestEditors { - if err := r(ctx, req); err != nil { - return err - } - } - for _, r := range additionalEditors { - if err := r(ctx, req); err != nil { - return err - } - } - return nil -} - -// ClientWithResponses builds on ClientInterface to offer response payloads -type ClientWithResponses struct { - ClientInterface -} - -// NewClientWithResponses creates a new ClientWithResponses, which wraps -// Client with return type handling -func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { - client, err := NewClient(server, opts...) - if err != nil { - return nil, err - } - return &ClientWithResponses{client}, nil -} - -// WithBaseURL overrides the baseURL. -func WithBaseURL(baseURL string) ClientOption { - return func(c *Client) error { - newBaseURL, err := url.Parse(baseURL) - if err != nil { - return err - } - c.Server = newBaseURL.String() - return nil - } -} - -// ClientWithResponsesInterface is the interface specification for the client with responses above. -type ClientWithResponsesInterface interface { - // CreateVPWithBodyWithResponse request with any body - CreateVPWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateVPResponse, error) - - CreateVPWithResponse(ctx context.Context, body CreateVPJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateVPResponse, error) - - // GetCredentialsInWalletWithResponse request - GetCredentialsInWalletWithResponse(ctx context.Context, did string, reqEditors ...RequestEditorFn) (*GetCredentialsInWalletResponse, error) - - // LoadVCWithBodyWithResponse request with any body - LoadVCWithBodyWithResponse(ctx context.Context, did string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*LoadVCResponse, error) - - LoadVCWithResponse(ctx context.Context, did string, body LoadVCJSONRequestBody, reqEditors ...RequestEditorFn) (*LoadVCResponse, error) - - // RemoveCredentialFromWalletWithResponse request - RemoveCredentialFromWalletWithResponse(ctx context.Context, did string, id string, reqEditors ...RequestEditorFn) (*RemoveCredentialFromWalletResponse, error) - - // IssueVCWithBodyWithResponse request with any body - IssueVCWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*IssueVCResponse, error) - - IssueVCWithResponse(ctx context.Context, body IssueVCJSONRequestBody, reqEditors ...RequestEditorFn) (*IssueVCResponse, error) - - // SearchIssuedVCsWithResponse request - SearchIssuedVCsWithResponse(ctx context.Context, params *SearchIssuedVCsParams, reqEditors ...RequestEditorFn) (*SearchIssuedVCsResponse, error) - - // RevokeVCWithResponse request - RevokeVCWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*RevokeVCResponse, error) - - // SearchVCsWithBodyWithResponse request with any body - SearchVCsWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SearchVCsResponse, error) - - SearchVCsWithResponse(ctx context.Context, body SearchVCsJSONRequestBody, reqEditors ...RequestEditorFn) (*SearchVCsResponse, error) - - // ResolveVCWithResponse request - ResolveVCWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*ResolveVCResponse, error) - - // UntrustIssuerWithBodyWithResponse request with any body - UntrustIssuerWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UntrustIssuerResponse, error) - - UntrustIssuerWithResponse(ctx context.Context, body UntrustIssuerJSONRequestBody, reqEditors ...RequestEditorFn) (*UntrustIssuerResponse, error) - - // TrustIssuerWithBodyWithResponse request with any body - TrustIssuerWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TrustIssuerResponse, error) - - TrustIssuerWithResponse(ctx context.Context, body TrustIssuerJSONRequestBody, reqEditors ...RequestEditorFn) (*TrustIssuerResponse, error) - - // VerifyVCWithBodyWithResponse request with any body - VerifyVCWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*VerifyVCResponse, error) - - VerifyVCWithResponse(ctx context.Context, body VerifyVCJSONRequestBody, reqEditors ...RequestEditorFn) (*VerifyVCResponse, error) - - // VerifyVPWithBodyWithResponse request with any body - VerifyVPWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*VerifyVPResponse, error) - - VerifyVPWithResponse(ctx context.Context, body VerifyVPJSONRequestBody, reqEditors ...RequestEditorFn) (*VerifyVPResponse, error) - - // ListTrustedWithResponse request - ListTrustedWithResponse(ctx context.Context, credentialType string, reqEditors ...RequestEditorFn) (*ListTrustedResponse, error) - - // ListUntrustedWithResponse request - ListUntrustedWithResponse(ctx context.Context, credentialType string, reqEditors ...RequestEditorFn) (*ListUntrustedResponse, error) -} - -type CreateVPResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *VerifiablePresentation - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r CreateVPResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r CreateVPResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type GetCredentialsInWalletResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *[]VerifiableCredential - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r GetCredentialsInWalletResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r GetCredentialsInWalletResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type LoadVCResponse struct { - Body []byte - HTTPResponse *http.Response - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r LoadVCResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r LoadVCResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type RemoveCredentialFromWalletResponse struct { - Body []byte - HTTPResponse *http.Response - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r RemoveCredentialFromWalletResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r RemoveCredentialFromWalletResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type IssueVCResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *VerifiableCredential - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r IssueVCResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r IssueVCResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type SearchIssuedVCsResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *SearchVCResults - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r SearchIssuedVCsResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r SearchIssuedVCsResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type RevokeVCResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *Revocation - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r RevokeVCResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r RevokeVCResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type SearchVCsResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *SearchVCResults - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r SearchVCsResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r SearchVCsResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type ResolveVCResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *VerifiableCredential - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r ResolveVCResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r ResolveVCResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type UntrustIssuerResponse struct { - Body []byte - HTTPResponse *http.Response - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r UntrustIssuerResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r UntrustIssuerResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type TrustIssuerResponse struct { - Body []byte - HTTPResponse *http.Response - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r TrustIssuerResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r TrustIssuerResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type VerifyVCResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *VCVerificationResult - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r VerifyVCResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r VerifyVCResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type VerifyVPResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *VPVerificationResult - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r VerifyVPResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r VerifyVPResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type ListTrustedResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *[]string - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r ListTrustedResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r ListTrustedResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -type ListUntrustedResponse struct { - Body []byte - HTTPResponse *http.Response - JSON200 *[]string - ApplicationproblemJSONDefault *struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } -} - -// Status returns HTTPResponse.Status -func (r ListUntrustedResponse) Status() string { - if r.HTTPResponse != nil { - return r.HTTPResponse.Status - } - return http.StatusText(0) -} - -// StatusCode returns HTTPResponse.StatusCode -func (r ListUntrustedResponse) StatusCode() int { - if r.HTTPResponse != nil { - return r.HTTPResponse.StatusCode - } - return 0 -} - -// CreateVPWithBodyWithResponse request with arbitrary body returning *CreateVPResponse -func (c *ClientWithResponses) CreateVPWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateVPResponse, error) { - rsp, err := c.CreateVPWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseCreateVPResponse(rsp) -} - -func (c *ClientWithResponses) CreateVPWithResponse(ctx context.Context, body CreateVPJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateVPResponse, error) { - rsp, err := c.CreateVP(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseCreateVPResponse(rsp) -} - -// GetCredentialsInWalletWithResponse request returning *GetCredentialsInWalletResponse -func (c *ClientWithResponses) GetCredentialsInWalletWithResponse(ctx context.Context, did string, reqEditors ...RequestEditorFn) (*GetCredentialsInWalletResponse, error) { - rsp, err := c.GetCredentialsInWallet(ctx, did, reqEditors...) - if err != nil { - return nil, err - } - return ParseGetCredentialsInWalletResponse(rsp) -} - -// LoadVCWithBodyWithResponse request with arbitrary body returning *LoadVCResponse -func (c *ClientWithResponses) LoadVCWithBodyWithResponse(ctx context.Context, did string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*LoadVCResponse, error) { - rsp, err := c.LoadVCWithBody(ctx, did, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseLoadVCResponse(rsp) -} - -func (c *ClientWithResponses) LoadVCWithResponse(ctx context.Context, did string, body LoadVCJSONRequestBody, reqEditors ...RequestEditorFn) (*LoadVCResponse, error) { - rsp, err := c.LoadVC(ctx, did, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseLoadVCResponse(rsp) -} - -// RemoveCredentialFromWalletWithResponse request returning *RemoveCredentialFromWalletResponse -func (c *ClientWithResponses) RemoveCredentialFromWalletWithResponse(ctx context.Context, did string, id string, reqEditors ...RequestEditorFn) (*RemoveCredentialFromWalletResponse, error) { - rsp, err := c.RemoveCredentialFromWallet(ctx, did, id, reqEditors...) - if err != nil { - return nil, err - } - return ParseRemoveCredentialFromWalletResponse(rsp) -} - -// IssueVCWithBodyWithResponse request with arbitrary body returning *IssueVCResponse -func (c *ClientWithResponses) IssueVCWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*IssueVCResponse, error) { - rsp, err := c.IssueVCWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssueVCResponse(rsp) -} - -func (c *ClientWithResponses) IssueVCWithResponse(ctx context.Context, body IssueVCJSONRequestBody, reqEditors ...RequestEditorFn) (*IssueVCResponse, error) { - rsp, err := c.IssueVC(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseIssueVCResponse(rsp) -} - -// SearchIssuedVCsWithResponse request returning *SearchIssuedVCsResponse -func (c *ClientWithResponses) SearchIssuedVCsWithResponse(ctx context.Context, params *SearchIssuedVCsParams, reqEditors ...RequestEditorFn) (*SearchIssuedVCsResponse, error) { - rsp, err := c.SearchIssuedVCs(ctx, params, reqEditors...) - if err != nil { - return nil, err - } - return ParseSearchIssuedVCsResponse(rsp) -} - -// RevokeVCWithResponse request returning *RevokeVCResponse -func (c *ClientWithResponses) RevokeVCWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*RevokeVCResponse, error) { - rsp, err := c.RevokeVC(ctx, id, reqEditors...) - if err != nil { - return nil, err - } - return ParseRevokeVCResponse(rsp) -} - -// SearchVCsWithBodyWithResponse request with arbitrary body returning *SearchVCsResponse -func (c *ClientWithResponses) SearchVCsWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SearchVCsResponse, error) { - rsp, err := c.SearchVCsWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseSearchVCsResponse(rsp) -} - -func (c *ClientWithResponses) SearchVCsWithResponse(ctx context.Context, body SearchVCsJSONRequestBody, reqEditors ...RequestEditorFn) (*SearchVCsResponse, error) { - rsp, err := c.SearchVCs(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseSearchVCsResponse(rsp) -} - -// ResolveVCWithResponse request returning *ResolveVCResponse -func (c *ClientWithResponses) ResolveVCWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*ResolveVCResponse, error) { - rsp, err := c.ResolveVC(ctx, id, reqEditors...) - if err != nil { - return nil, err - } - return ParseResolveVCResponse(rsp) -} - -// UntrustIssuerWithBodyWithResponse request with arbitrary body returning *UntrustIssuerResponse -func (c *ClientWithResponses) UntrustIssuerWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UntrustIssuerResponse, error) { - rsp, err := c.UntrustIssuerWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseUntrustIssuerResponse(rsp) -} - -func (c *ClientWithResponses) UntrustIssuerWithResponse(ctx context.Context, body UntrustIssuerJSONRequestBody, reqEditors ...RequestEditorFn) (*UntrustIssuerResponse, error) { - rsp, err := c.UntrustIssuer(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseUntrustIssuerResponse(rsp) -} - -// TrustIssuerWithBodyWithResponse request with arbitrary body returning *TrustIssuerResponse -func (c *ClientWithResponses) TrustIssuerWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TrustIssuerResponse, error) { - rsp, err := c.TrustIssuerWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseTrustIssuerResponse(rsp) -} - -func (c *ClientWithResponses) TrustIssuerWithResponse(ctx context.Context, body TrustIssuerJSONRequestBody, reqEditors ...RequestEditorFn) (*TrustIssuerResponse, error) { - rsp, err := c.TrustIssuer(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseTrustIssuerResponse(rsp) -} - -// VerifyVCWithBodyWithResponse request with arbitrary body returning *VerifyVCResponse -func (c *ClientWithResponses) VerifyVCWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*VerifyVCResponse, error) { - rsp, err := c.VerifyVCWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseVerifyVCResponse(rsp) -} - -func (c *ClientWithResponses) VerifyVCWithResponse(ctx context.Context, body VerifyVCJSONRequestBody, reqEditors ...RequestEditorFn) (*VerifyVCResponse, error) { - rsp, err := c.VerifyVC(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseVerifyVCResponse(rsp) -} - -// VerifyVPWithBodyWithResponse request with arbitrary body returning *VerifyVPResponse -func (c *ClientWithResponses) VerifyVPWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*VerifyVPResponse, error) { - rsp, err := c.VerifyVPWithBody(ctx, contentType, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseVerifyVPResponse(rsp) -} - -func (c *ClientWithResponses) VerifyVPWithResponse(ctx context.Context, body VerifyVPJSONRequestBody, reqEditors ...RequestEditorFn) (*VerifyVPResponse, error) { - rsp, err := c.VerifyVP(ctx, body, reqEditors...) - if err != nil { - return nil, err - } - return ParseVerifyVPResponse(rsp) -} - -// ListTrustedWithResponse request returning *ListTrustedResponse -func (c *ClientWithResponses) ListTrustedWithResponse(ctx context.Context, credentialType string, reqEditors ...RequestEditorFn) (*ListTrustedResponse, error) { - rsp, err := c.ListTrusted(ctx, credentialType, reqEditors...) - if err != nil { - return nil, err - } - return ParseListTrustedResponse(rsp) -} - -// ListUntrustedWithResponse request returning *ListUntrustedResponse -func (c *ClientWithResponses) ListUntrustedWithResponse(ctx context.Context, credentialType string, reqEditors ...RequestEditorFn) (*ListUntrustedResponse, error) { - rsp, err := c.ListUntrusted(ctx, credentialType, reqEditors...) - if err != nil { - return nil, err - } - return ParseListUntrustedResponse(rsp) -} - -// ParseCreateVPResponse parses an HTTP response from a CreateVPWithResponse call -func ParseCreateVPResponse(rsp *http.Response) (*CreateVPResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &CreateVPResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest VerifiablePresentation - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseGetCredentialsInWalletResponse parses an HTTP response from a GetCredentialsInWalletWithResponse call -func ParseGetCredentialsInWalletResponse(rsp *http.Response) (*GetCredentialsInWalletResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &GetCredentialsInWalletResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest []VerifiableCredential - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseLoadVCResponse parses an HTTP response from a LoadVCWithResponse call -func ParseLoadVCResponse(rsp *http.Response) (*LoadVCResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &LoadVCResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseRemoveCredentialFromWalletResponse parses an HTTP response from a RemoveCredentialFromWalletWithResponse call -func ParseRemoveCredentialFromWalletResponse(rsp *http.Response) (*RemoveCredentialFromWalletResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &RemoveCredentialFromWalletResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseIssueVCResponse parses an HTTP response from a IssueVCWithResponse call -func ParseIssueVCResponse(rsp *http.Response) (*IssueVCResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &IssueVCResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest VerifiableCredential - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseSearchIssuedVCsResponse parses an HTTP response from a SearchIssuedVCsWithResponse call -func ParseSearchIssuedVCsResponse(rsp *http.Response) (*SearchIssuedVCsResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &SearchIssuedVCsResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest SearchVCResults - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseRevokeVCResponse parses an HTTP response from a RevokeVCWithResponse call -func ParseRevokeVCResponse(rsp *http.Response) (*RevokeVCResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &RevokeVCResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Revocation - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseSearchVCsResponse parses an HTTP response from a SearchVCsWithResponse call -func ParseSearchVCsResponse(rsp *http.Response) (*SearchVCsResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &SearchVCsResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest SearchVCResults - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseResolveVCResponse parses an HTTP response from a ResolveVCWithResponse call -func ParseResolveVCResponse(rsp *http.Response) (*ResolveVCResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &ResolveVCResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest VerifiableCredential - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseUntrustIssuerResponse parses an HTTP response from a UntrustIssuerWithResponse call -func ParseUntrustIssuerResponse(rsp *http.Response) (*UntrustIssuerResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &UntrustIssuerResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseTrustIssuerResponse parses an HTTP response from a TrustIssuerWithResponse call -func ParseTrustIssuerResponse(rsp *http.Response) (*TrustIssuerResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &TrustIssuerResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseVerifyVCResponse parses an HTTP response from a VerifyVCWithResponse call -func ParseVerifyVCResponse(rsp *http.Response) (*VerifyVCResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &VerifyVCResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest VCVerificationResult - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseVerifyVPResponse parses an HTTP response from a VerifyVPWithResponse call -func ParseVerifyVPResponse(rsp *http.Response) (*VerifyVPResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &VerifyVPResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest VPVerificationResult - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseListTrustedResponse parses an HTTP response from a ListTrustedWithResponse call -func ParseListTrustedResponse(rsp *http.Response) (*ListTrustedResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &ListTrustedResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest []string - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} - -// ParseListUntrustedResponse parses an HTTP response from a ListUntrustedWithResponse call -func ParseListUntrustedResponse(rsp *http.Response) (*ListUntrustedResponse, error) { - bodyBytes, err := io.ReadAll(rsp.Body) - defer func() { _ = rsp.Body.Close() }() - if err != nil { - return nil, err - } - - response := &ListUntrustedResponse{ - Body: bodyBytes, - HTTPResponse: rsp, - } - - switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest []string - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: - var dest struct { - // Detail A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail"` - - // Status HTTP statuscode - Status float32 `json:"status"` - - // Title A short, human-readable summary of the problem type. - Title string `json:"title"` - } - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.ApplicationproblemJSONDefault = &dest - - } - - return response, nil -} diff --git a/nuts/client/vcr/types.go b/nuts/client/vcr/types.go deleted file mode 100644 index 2eda8da7..00000000 --- a/nuts/client/vcr/types.go +++ /dev/null @@ -1,26 +0,0 @@ -package vcr - -import ( - ssi "github.com/nuts-foundation/go-did" -) - -type CredentialSubject = interface{} - -// SearchVCRequest is the request body for searching VCs -type SearchVCRequest struct { - // A partial VerifiableCredential in JSON-LD format. Each field will be used to match credentials against. All fields MUST be present. - Query SearchVCQuery `json:"query"` - SearchOptions *SearchOptions `json:"searchOptions,omitempty"` -} - -// SearchVCQuery defines a helper struct to search for VerifiableCredentials. -type SearchVCQuery struct { - // Context defines the json-ld context to dereference the URIs - Context []ssi.URI `json:"@context"` - // Type holds multiple types for a credential. A credential must always have the 'VerifiableCredential' type. - Type []ssi.URI `json:"type,omitempty"` - // Issuer refers to the party that issued the credential - Issuer *ssi.URI `json:"issuer,omitempty"` - // CredentialSubject holds the actual data for the credential. It must be extracted using the UnmarshalCredentialSubject method and a custom type. - CredentialSubject interface{} `json:"credentialSubject,omitempty"` -} diff --git a/nuts/registry/verifiable_credential.go b/nuts/registry/verifiable_credential.go deleted file mode 100644 index de566669..00000000 --- a/nuts/registry/verifiable_credential.go +++ /dev/null @@ -1,135 +0,0 @@ -package registry - -import ( - "context" - "encoding/json" - "fmt" - ssi "github.com/nuts-foundation/go-did" - "github.com/nuts-foundation/go-did/vc" - - nutsClient "github.com/nuts-foundation/nuts-demo-ehr/nuts/client" -) - -type VCRSearchParams struct { - PurposeOfUse string - SubjectID string - Issuer string - Subject string - ResourcePath string -} - -var NutsAuthorizationCredentialTypeURI = ssi.MustParseURI("NutsAuthorizationCredential") - -// NutsAuthorizationCredentialSubject defines the CredentialSubject struct for the NutsAuthorizationCredential -type NutsAuthorizationCredentialSubject struct { - // ID contains the DID of the subject - ID string `json:"id"` - // PurposeOfUse refers to the Bolt access policy - PurposeOfUse string `json:"purposeOfUse"` - // Resources contains additional individual resources that can be accessed. - Resources []Resource `json:"resources,omitempty"` - // Subject contains a URN referring to the subject of care (not the credential subject) - Subject *string `json:"subject,omitempty"` -} - -// Resource defines a single accessbile resource -type Resource struct { - // Path defines the path of the resource relative to the service base URL. - // Which service acts as base URL is described by the Bolt. - Path string `json:"path"` - // Operations define which operations are allowed on the resource. - Operations []string `json:"operations"` - // UserContext defines if a user login contract is required for the resource. - UserContext bool `json:"userContext"` - // AssuranceLevel defines the assurance level required for the resource (low, substantial, high). - // Should be set if userContext = true, defaults to low - AssuranceLevel *string `json:"assuranceLevel"` -} - -type VerifiableCredentialRegistry interface { - // CreateAuthorizationCredential creates a NutsAuthorizationCredential on the nuts node - CreateAuthorizationCredential(ctx context.Context, issuer string, subject *NutsAuthorizationCredentialSubject) error - // RevokeAuthorizationCredential revokes a credential based on the resourcePath contained in the credential - RevokeAuthorizationCredential(ctx context.Context, purposeOfUse, subjectID, resourcePath string) error - // ResolveVerifiableCredential from the nuts node. It also returns untrusted credentials - ResolveVerifiableCredential(ctx context.Context, credentialID string) (*vc.VerifiableCredential, error) - // FindAuthorizationCredentials returns the NutsAuthorizationCredential for the given params - FindAuthorizationCredentials(ctx context.Context, params *VCRSearchParams) ([]vc.VerifiableCredential, error) -} - -type httpVerifiableCredentialRegistry struct { - nutsClient nutsClient.VCRClient -} - -func NewVerifiableCredentialRegistry(client nutsClient.VCRClient) VerifiableCredentialRegistry { - return &httpVerifiableCredentialRegistry{ - nutsClient: client, - } -} - -func (registry *httpVerifiableCredentialRegistry) CreateAuthorizationCredential(ctx context.Context, issuer string, subject *NutsAuthorizationCredentialSubject) error { - subjectMap := map[string]interface{}{} - - data, err := json.Marshal(subject) - if err != nil { - return fmt.Errorf("invalid subject: %w", err) - } - - if err := json.Unmarshal(data, &subjectMap); err != nil { - return fmt.Errorf("invalid subject: %w", err) - } - - return registry.nutsClient.CreateVC(ctx, NutsAuthorizationCredentialTypeURI.String(), issuer, subjectMap, nil, false) -} - -func (registry *httpVerifiableCredentialRegistry) FindAuthorizationCredentials(ctx context.Context, params *VCRSearchParams) ([]vc.VerifiableCredential, error) { - query := nutsClient.GetNutsCredentialTemplate(NutsAuthorizationCredentialTypeURI) - credentialSubject := make(map[string]interface{}, 0) - query.CredentialSubject = credentialSubject - - // may be extended by issuanceDate for even faster results. - credentialSubject["purposeOfUse"] = params.PurposeOfUse - credentialSubject["resources"] = map[string]string{"path": params.ResourcePath} - - if params.SubjectID != "" { - credentialSubject["id"] = params.SubjectID - } - - if params.Subject != "" { - credentialSubject["subject"] = params.Subject - } - - if params.Issuer != "" { - issuer := ssi.MustParseURI(params.Issuer) - query.Issuer = &issuer - } - - return registry.nutsClient.FindCredentials(ctx, query, true) -} - -func (registry *httpVerifiableCredentialRegistry) RevokeAuthorizationCredential(ctx context.Context, purposeOfUse, subjectID, resourcePath string) error { - // may be extended by issuanceDate for even faster results. - query := nutsClient.GetNutsCredentialTemplate(NutsAuthorizationCredentialTypeURI) - query.CredentialSubject = map[string]interface{}{ - "id": subjectID, - "purposeOfUse": purposeOfUse, - "resources": map[string]interface{}{ - "path": resourcePath, - }, - } - credentialIDs, err := registry.nutsClient.FindCredentialIDs(ctx, query, false) - if err != nil { - return err - } - for _, ID := range credentialIDs { - if err = registry.nutsClient.RevokeCredential(ctx, ID); err != nil { - return err - } - } - - return nil -} - -func (registry *httpVerifiableCredentialRegistry) ResolveVerifiableCredential(ctx context.Context, credentialID string) (*vc.VerifiableCredential, error) { - return registry.nutsClient.ResolveCredential(ctx, credentialID) -} diff --git a/nutspxp/client/pip.go b/nutspxp/client/pip.go new file mode 100644 index 00000000..e6b96585 --- /dev/null +++ b/nutspxp/client/pip.go @@ -0,0 +1,85 @@ +package nutspxp + +import ( + "context" + "errors" + "fmt" + "github.com/nuts-foundation/nuts-demo-ehr/nutspxp/client/pip" + "io" + "net/http" + "time" +) + +type Client interface { + AddPIPData(id string, client string, scope string, verifier string, authInput map[string]interface{}) error + DeletePIPData(id string) error +} + +type HTTPClient struct { + PIPAddress string +} + +var _ Client = HTTPClient{} + +func (c HTTPClient) AddPIPData(id string, client string, scope string, verifier string, authInput map[string]interface{}) error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + resp, err := c.client().CreateData(ctx, id, pip.CreateDataJSONRequestBody{ + AuthInput: authInput, + ClientId: client, + Scope: scope, + VerifierId: verifier, + }) + if err != nil { + return err + } + err = testResponseCode(http.StatusNoContent, resp) + if err != nil { + return err + } + return nil +} + +func (c HTTPClient) DeletePIPData(id string) error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + resp, err := c.client().DeleteData(ctx, id) + if err != nil { + return err + } + err = testResponseCode(http.StatusNoContent, resp) + if err != nil { + return err + } + return nil +} + +func (c HTTPClient) client() pip.ClientInterface { + response, err := pip.NewClientWithResponses(c.PIPAddress) + + if err != nil { + panic(err) + } + return response +} + +func testAndReadResponse(status int, response *http.Response) ([]byte, error) { + if response.StatusCode == http.StatusNotFound { + return nil, errors.New("not found") + } + if err := testResponseCode(status, response); err != nil { + return nil, err + } + return io.ReadAll(response.Body) +} + +func testResponseCode(expectedStatusCode int, response *http.Response) error { + if response.StatusCode != expectedStatusCode { + responseData, _ := io.ReadAll(response.Body) + return fmt.Errorf("server returned HTTP %d (expected: %d), response: %s", + response.StatusCode, expectedStatusCode, string(responseData)) + } + return nil +} diff --git a/nutspxp/client/pip/generated.go b/nutspxp/client/pip/generated.go new file mode 100644 index 00000000..41ab056e --- /dev/null +++ b/nutspxp/client/pip/generated.go @@ -0,0 +1,484 @@ +// Package pip provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/deepmap/oapi-codegen/v2 version v2.1.0 DO NOT EDIT. +package pip + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" +) + +// Data defines model for Data. +type Data struct { + // AuthInput Data used in OPA script + AuthInput map[string]interface{} `json:"auth_input"` + + // ClientId client DID (for now) + ClientId string `json:"client_id"` + + // Scope The scope. Corresponds to the auth scopes + Scope string `json:"scope"` + + // VerifierId verifier DID (for now) + VerifierId string `json:"verifier_id"` +} + +// CreateDataJSONRequestBody defines body for CreateData for application/json ContentType. +type CreateDataJSONRequestBody = Data + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // DeleteData request + DeleteData(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetData request + GetData(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateDataWithBody request with any body + CreateDataWithBody(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateData(ctx context.Context, id string, body CreateDataJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) DeleteData(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteDataRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetData(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetDataRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateDataWithBody(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateDataRequestWithBody(c.Server, id, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateData(ctx context.Context, id string, body CreateDataJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateDataRequest(c.Server, id, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewDeleteDataRequest generates requests for DeleteData +func NewDeleteDataRequest(server string, id string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0 = id + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/pip/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("DELETE", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetDataRequest generates requests for GetData +func NewGetDataRequest(server string, id string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0 = id + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/pip/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateDataRequest calls the generic CreateData builder with application/json body +func NewCreateDataRequest(server string, id string, body CreateDataJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateDataRequestWithBody(server, id, "application/json", bodyReader) +} + +// NewCreateDataRequestWithBody generates requests for CreateData with any type of body +func NewCreateDataRequestWithBody(server string, id string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0 = id + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/pip/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // DeleteDataWithResponse request + DeleteDataWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*DeleteDataResponse, error) + + // GetDataWithResponse request + GetDataWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*GetDataResponse, error) + + // CreateDataWithBodyWithResponse request with any body + CreateDataWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateDataResponse, error) + + CreateDataWithResponse(ctx context.Context, id string, body CreateDataJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateDataResponse, error) +} + +type DeleteDataResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r DeleteDataResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteDataResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetDataResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Data +} + +// Status returns HTTPResponse.Status +func (r GetDataResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetDataResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateDataResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r CreateDataResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateDataResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// DeleteDataWithResponse request returning *DeleteDataResponse +func (c *ClientWithResponses) DeleteDataWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*DeleteDataResponse, error) { + rsp, err := c.DeleteData(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteDataResponse(rsp) +} + +// GetDataWithResponse request returning *GetDataResponse +func (c *ClientWithResponses) GetDataWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*GetDataResponse, error) { + rsp, err := c.GetData(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetDataResponse(rsp) +} + +// CreateDataWithBodyWithResponse request with arbitrary body returning *CreateDataResponse +func (c *ClientWithResponses) CreateDataWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateDataResponse, error) { + rsp, err := c.CreateDataWithBody(ctx, id, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateDataResponse(rsp) +} + +func (c *ClientWithResponses) CreateDataWithResponse(ctx context.Context, id string, body CreateDataJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateDataResponse, error) { + rsp, err := c.CreateData(ctx, id, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateDataResponse(rsp) +} + +// ParseDeleteDataResponse parses an HTTP response from a DeleteDataWithResponse call +func ParseDeleteDataResponse(rsp *http.Response) (*DeleteDataResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteDataResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseGetDataResponse parses an HTTP response from a GetDataWithResponse call +func ParseGetDataResponse(rsp *http.Response) (*GetDataResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetDataResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Data + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseCreateDataResponse parses an HTTP response from a CreateDataWithResponse call +func ParseCreateDataResponse(rsp *http.Response) (*CreateDataResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateDataResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +}