diff --git a/README.md b/README.md index bd9d976..33705ec 100644 --- a/README.md +++ b/README.md @@ -154,11 +154,11 @@ curl -X GET http://admin:password@127.0.0.1:5984/_all_dbs ``` Output: ``` -["_replicator","_users","kmspkprimarykey","vctdbmaple2021jsonldcontexts","vctdbconfig"] +["_replicator","_users","kmspkprimarykey","vctdbmaple2021ldcontexts","vctdbconfig"] ``` Then, filter databases from the output above by `VCT_DATABASE_PREFIX=vctdb` env. -Databases we need to backup are `vctdbmaple2021jsonldcontexts` and `vctdbconfig` +Databases we need to backup are `vctdbmaple2021ldcontexts` and `vctdbconfig` Make a backup according to CouchDB documentation. ### Trillian Storage diff --git a/cmd/vct/startcmd/start.go b/cmd/vct/startcmd/start.go index 8516401..8341d02 100644 --- a/cmd/vct/startcmd/start.go +++ b/cmd/vct/startcmd/start.go @@ -29,20 +29,26 @@ import ( "github.com/hyperledger/aries-framework-go-ext/component/storage/mysql" "github.com/hyperledger/aries-framework-go/component/storageutil/mem" "github.com/hyperledger/aries-framework-go/pkg/common/log" + ldrest "github.com/hyperledger/aries-framework-go/pkg/controller/rest/ld" "github.com/hyperledger/aries-framework-go/pkg/crypto" "github.com/hyperledger/aries-framework-go/pkg/crypto/tinkcrypto" webcrypto "github.com/hyperledger/aries-framework-go/pkg/crypto/webkms" "github.com/hyperledger/aries-framework-go/pkg/doc/did" + "github.com/hyperledger/aries-framework-go/pkg/doc/ld" + "github.com/hyperledger/aries-framework-go/pkg/doc/ldcontext/remote" vdrapi "github.com/hyperledger/aries-framework-go/pkg/framework/aries/api/vdr" "github.com/hyperledger/aries-framework-go/pkg/kms" "github.com/hyperledger/aries-framework-go/pkg/kms/localkms" "github.com/hyperledger/aries-framework-go/pkg/kms/webkms" + ldsvc "github.com/hyperledger/aries-framework-go/pkg/ld" "github.com/hyperledger/aries-framework-go/pkg/secretlock" "github.com/hyperledger/aries-framework-go/pkg/secretlock/noop" + ldstore "github.com/hyperledger/aries-framework-go/pkg/store/ld" "github.com/hyperledger/aries-framework-go/pkg/vdr" vdrkey "github.com/hyperledger/aries-framework-go/pkg/vdr/key" vdrweb "github.com/hyperledger/aries-framework-go/pkg/vdr/web" "github.com/hyperledger/aries-framework-go/spi/storage" + jsonld "github.com/piprate/json-gold/ld" "github.com/rs/cors" "github.com/spf13/cobra" tlsutils "github.com/trustbloc/edge-core/pkg/utils/tls" @@ -142,6 +148,11 @@ const ( devModeFlagUsage = "Enable dev mode." + " Alternatively, this can be set with the following environment variable: " + devModeFlagEnvKey devModeFlagEnvKey = envPrefix + "DEV_MODE" + + contextProviderFlagName = "context-provider-url" + contextProviderFlagUsage = "Comma-separated list of remote context provider URLs to get JSON-LD contexts from." + + " Alternatively, this can be set with the following environment variable: " + contextProviderEnvKey + contextProviderEnvKey = envPrefix + "CONTEXT_PROVIDER_URL" ) const ( @@ -197,6 +208,9 @@ func (s *HTTPServer) ListenAndServe(host string, router http.Handler, certFile, return http.ListenAndServe(host, router) // nolint: wrapcheck } +// StorageProvider represents a storage provider. +type StorageProvider storage.Provider + // Cmd returns the Cobra start command. func Cmd(server server) (*cobra.Command, error) { startCmd := createStartCMD(server) @@ -207,18 +221,19 @@ func Cmd(server server) (*cobra.Command, error) { } type agentParameters struct { - logs []command.Log - host string - metricsHost string - baseURL string - datasourceName string - timeout uint64 - syncTimeout uint64 - databasePrefix string - kmsEndpoint string - tlsParams *tlsParameters - server server - devMode bool + logs []command.Log + host string + metricsHost string + baseURL string + datasourceName string + timeout uint64 + syncTimeout uint64 + databasePrefix string + kmsEndpoint string + contextProviderURLs []string + tlsParams *tlsParameters + server server + devMode bool } type tlsParameters struct { @@ -290,12 +305,18 @@ func createStartCMD(server server) *cobra.Command { //nolint: funlen syncTimeoutStr := getUserSetVarOptional(cmd, syncTimeoutFlagName, syncTimeoutEnvKey) issuersStr := getUserSetVarOptional(cmd, issuersFlagName, issuersEnvKey) devModeStr := getUserSetVarOptional(cmd, devModeFlagName, devModeFlagEnvKey) + contextProviderURLsStr := getUserSetVarOptional(cmd, contextProviderFlagName, contextProviderEnvKey) var issuers []string if issuersStr != "" { issuers = strings.Split(issuersStr, ",") } + var contextProviderURLs []string + if contextProviderURLsStr != "" { + contextProviderURLs = strings.Split(contextProviderURLsStr, ",") + } + timeout, err := strconv.ParseUint(timeoutStr, 10, 64) if err != nil { return fmt.Errorf("timeout is not a number(positive): %w", err) @@ -326,18 +347,19 @@ func createStartCMD(server server) *cobra.Command { //nolint: funlen } parameters := &agentParameters{ - server: server, - host: host, - metricsHost: metricsHost, - logs: parseLogs(logsVal, issuers), - timeout: timeout, - syncTimeout: syncTimeout, - kmsEndpoint: kmsEndpoint, - datasourceName: datasourceName, - databasePrefix: databasePrefix, - tlsParams: tlsParams, - baseURL: baseURL, - devMode: devMode, + server: server, + host: host, + metricsHost: metricsHost, + logs: parseLogs(logsVal, issuers), + timeout: timeout, + syncTimeout: syncTimeout, + kmsEndpoint: kmsEndpoint, + datasourceName: datasourceName, + databasePrefix: databasePrefix, + tlsParams: tlsParams, + baseURL: baseURL, + devMode: devMode, + contextProviderURLs: contextProviderURLs, } return startAgent(parameters) @@ -411,7 +433,7 @@ func createKID(km kms.KeyManager, cfg storage.Store, syncTimeout uint64) (string return keyID, keyType, err } -func startAgent(parameters *agentParameters) error { // nolint: funlen +func startAgent(parameters *agentParameters) error { //nolint:funlen,gocyclo,cyclop store, err := createStoreProvider( parameters.datasourceName, parameters.databasePrefix, @@ -457,6 +479,8 @@ func startAgent(parameters *agentParameters) error { // nolint: funlen return fmt.Errorf("create kid: %w", err) } + var aliases []string + conns := map[string]*grpc.ClientConn{} for i := range parameters.logs { @@ -480,6 +504,8 @@ func startAgent(parameters *agentParameters) error { // nolint: funlen parameters.logs[i].ID = tree.TreeId parameters.logs[i].Client = trillian.NewTrillianLogClient(conn) + + aliases = append(aliases, parameters.logs[i].Alias) } defer func() { @@ -488,6 +514,29 @@ func startAgent(parameters *agentParameters) error { // nolint: funlen } }() + loaders := map[string]jsonld.DocumentLoader{} + ldStoreProviders := map[string]*ldStoreProvider{} + + for _, alias := range aliases { + storageProvider := &customizedStorageProvider{ + alias: alias, + StorageProvider: store, + } + + ldStore, er := createLDStoreProvider(storageProvider) + if er != nil { + return fmt.Errorf("create ld store provider: %w", er) + } + + loader, er := createJSONLDDocumentLoader(ldStore, httpClient, parameters.contextProviderURLs) + if er != nil { + return fmt.Errorf("create document loader: %w", er) + } + + loaders[alias] = loader + ldStoreProviders[alias] = ldStore + } + mf := prometheus.MetricFactory{} cmd, err := command.New(&command.Config{ @@ -502,8 +551,8 @@ func startAgent(parameters *agentParameters) error { // nolint: funlen ID: keyID, Type: keyType, }, - StorageProvider: store, BaseURL: parameters.baseURL, + DocumentLoaders: loaders, }, mf) if err != nil { return fmt.Errorf("create command instance: %w", err) @@ -522,6 +571,15 @@ func startAgent(parameters *agentParameters) error { // nolint: funlen } } + for alias, ldStore := range ldStoreProviders { + r := router.PathPrefix(strings.ReplaceAll(rest.BasePath, rest.AliasPath, "/"+alias)).Subrouter() + + // handlers for JSON-LD context operations + for _, handler := range ldrest.New(ldsvc.New(ldStore)).GetRESTHandlers() { + r.HandleFunc(handler.Path(), handler.Handle()).Methods(handler.Method()) + } + } + go startMetrics(parameters, metricsRouter) logger.Infof("Starting vct on host [%s]", parameters.host) @@ -676,6 +734,7 @@ func createFlags(startCmd *cobra.Command) { startCmd.Flags().String(tlsServeKeyPathFlagName, "", tlsServeKeyPathFlagUsage) startCmd.Flags().String(issuersFlagName, "", issuersFlagUsage) startCmd.Flags().String(devModeFlagName, "", devModeFlagUsage) + startCmd.Flags().String(contextProviderFlagName, "", contextProviderFlagUsage) } func getTLS(cmd *cobra.Command) (*tlsParameters, error) { @@ -751,3 +810,66 @@ func (k kmsProvider) StorageProvider() storage.Provider { func (k kmsProvider) SecretLock() secretlock.Service { return k.secretLock } + +type customizedStorageProvider struct { + alias string + StorageProvider +} + +func (p *customizedStorageProvider) OpenStore(name string) (storage.Store, error) { + return p.StorageProvider.OpenStore(p.alias + name) +} + +func (p *customizedStorageProvider) SetStoreConfig(name string, config storage.StoreConfiguration) error { + return p.StorageProvider.SetStoreConfig(p.alias+name, config) +} + +type ldStoreProvider struct { + ContextStore ldstore.ContextStore + RemoteProviderStore ldstore.RemoteProviderStore +} + +func (p *ldStoreProvider) JSONLDContextStore() ldstore.ContextStore { + return p.ContextStore +} + +func (p *ldStoreProvider) JSONLDRemoteProviderStore() ldstore.RemoteProviderStore { + return p.RemoteProviderStore +} + +func createLDStoreProvider(provider storage.Provider) (*ldStoreProvider, error) { + contextStore, err := ldstore.NewContextStore(provider) + if err != nil { + return nil, fmt.Errorf("create JSON-LD context store: %w", err) + } + + remoteProviderStore, err := ldstore.NewRemoteProviderStore(provider) + if err != nil { + return nil, fmt.Errorf("create remote provider store: %w", err) + } + + return &ldStoreProvider{ + ContextStore: contextStore, + RemoteProviderStore: remoteProviderStore, + }, nil +} + +func createJSONLDDocumentLoader(ldStore *ldStoreProvider, httpClient *http.Client, + providerURLs []string) (jsonld.DocumentLoader, error) { + var loaderOpts []ld.DocumentLoaderOpts + + for _, u := range providerURLs { + loaderOpts = append(loaderOpts, + ld.WithRemoteProvider( + remote.NewProvider(u, remote.WithHTTPClient(httpClient)), + ), + ) + } + + loader, err := ld.NewDocumentLoader(ldStore, loaderOpts...) + if err != nil { + return nil, fmt.Errorf("new document loader: %w", err) + } + + return loader, nil +} diff --git a/internal/pkg/ldcontext/ldcontext.go b/internal/pkg/ldcontext/ldcontext.go index 64d9299..2dc728c 100644 --- a/internal/pkg/ldcontext/ldcontext.go +++ b/internal/pkg/ldcontext/ldcontext.go @@ -10,8 +10,13 @@ import ( "encoding/json" "os" "sync" + "testing" + "github.com/hyperledger/aries-framework-go/pkg/doc/ld" "github.com/hyperledger/aries-framework-go/pkg/doc/ldcontext" + mockldstore "github.com/hyperledger/aries-framework-go/pkg/mock/ld" + ldstore "github.com/hyperledger/aries-framework-go/pkg/store/ld" + "github.com/stretchr/testify/require" ) const testdataDir = "testdata" @@ -74,3 +79,31 @@ func MustGetAll() []ldcontext.Document { return docs } + +type mockLDStoreProvider struct { + ContextStore ldstore.ContextStore + RemoteProviderStore ldstore.RemoteProviderStore +} + +func (p *mockLDStoreProvider) JSONLDContextStore() ldstore.ContextStore { + return p.ContextStore +} + +func (p *mockLDStoreProvider) JSONLDRemoteProviderStore() ldstore.RemoteProviderStore { + return p.RemoteProviderStore +} + +// DocumentLoader returns a document loader with preloaded test contexts. +func DocumentLoader(t *testing.T) *ld.DocumentLoader { + t.Helper() + + ldStore := &mockLDStoreProvider{ + ContextStore: mockldstore.NewMockContextStore(), + RemoteProviderStore: mockldstore.NewMockRemoteProviderStore(), + } + + loader, err := ld.NewDocumentLoader(ldStore, ld.WithExtraContexts(MustGetAll()...)) + require.NoError(t, err) + + return loader +} diff --git a/pkg/client/vct/client.go b/pkg/client/vct/client.go index 5b4f8e9..4bf5953 100644 --- a/pkg/client/vct/client.go +++ b/pkg/client/vct/client.go @@ -21,9 +21,7 @@ import ( "time" "github.com/google/trillian/merkle/rfc6962/hasher" - ldcmd "github.com/hyperledger/aries-framework-go/pkg/controller/command/ld" "github.com/hyperledger/aries-framework-go/pkg/crypto/tinkcrypto" - "github.com/hyperledger/aries-framework-go/pkg/doc/ldcontext" "github.com/hyperledger/aries-framework-go/pkg/doc/verifiable" "github.com/hyperledger/aries-framework-go/pkg/kms/localkms" @@ -82,21 +80,6 @@ func (c *Client) AddVC(ctx context.Context, credential []byte) (*command.AddVCRe return result, nil } -// AddJSONLDContexts imports extra contexts for the service. -func (c *Client) AddJSONLDContexts(ctx context.Context, docs ...ldcontext.Document) error { - body, err := json.Marshal(ldcmd.AddContextsRequest{Documents: docs}) - if err != nil { - return fmt.Errorf("marshal AddRequest for JSONLDContexts: %w", err) - } - - err = c.do(ctx, rest.AddContextPath, nil, withMethod(http.MethodPost), withBody(body)) - if err != nil { - return fmt.Errorf("add JSON ld contexts: %w", err) - } - - return nil -} - // Webfinger returns discovery info. func (c *Client) Webfinger(ctx context.Context) (*command.WebFingerResponse, error) { var result *command.WebFingerResponse diff --git a/pkg/client/vct/client_test.go b/pkg/client/vct/client_test.go index 97d3244..7e58abb 100644 --- a/pkg/client/vct/client_test.go +++ b/pkg/client/vct/client_test.go @@ -19,7 +19,6 @@ import ( "github.com/golang/mock/gomock" "github.com/hyperledger/aries-framework-go/pkg/doc/ld" - "github.com/hyperledger/aries-framework-go/pkg/doc/ldcontext" "github.com/hyperledger/aries-framework-go/pkg/doc/util" "github.com/hyperledger/aries-framework-go/pkg/doc/verifiable" mockldstore "github.com/hyperledger/aries-framework-go/pkg/mock/ld" @@ -98,42 +97,6 @@ func TestClient_AddVC(t *testing.T) { }) } -func TestClient_AddJSONLDContexts(t *testing.T) { - t.Run("Success", func(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - httpClient := NewMockHTTPClient(ctrl) - httpClient.EXPECT().Do(gomock.Any()).Return(&http.Response{ - Body: ioutil.NopCloser(bytes.NewBuffer([]byte(`{}`))), - StatusCode: http.StatusOK, - }, nil) - - client := vct.New(endpoint+"/maple2020", vct.WithHTTPClient(httpClient)) - require.NoError(t, client.AddJSONLDContexts(context.Background(), ldcontext.Document{})) - }) - - t.Run("Error", func(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - expected := rest.ErrorResponse{Message: "error"} - - fakeResp, err := json.Marshal(expected) - require.NoError(t, err) - - httpClient := NewMockHTTPClient(ctrl) - httpClient.EXPECT().Do(gomock.Any()).Return(&http.Response{ - Body: ioutil.NopCloser(bytes.NewBuffer(fakeResp)), - StatusCode: http.StatusInternalServerError, - }, nil) - - client := vct.New(endpoint, vct.WithHTTPClient(httpClient)) - err = client.AddJSONLDContexts(context.Background(), ldcontext.Document{}) - require.EqualError(t, err, "add JSON ld contexts: error") - }) -} - func TestClient_GetIssuers(t *testing.T) { t.Run("Success", func(t *testing.T) { ctrl := gomock.NewController(t) diff --git a/pkg/controller/command/command.go b/pkg/controller/command/command.go index 6b8f6d5..4153bc3 100644 --- a/pkg/controller/command/command.go +++ b/pkg/controller/command/command.go @@ -7,7 +7,6 @@ SPDX-License-Identifier: Apache-2.0 package command import ( - "bytes" "context" "crypto/sha256" "encoding/base64" @@ -20,15 +19,11 @@ import ( "github.com/google/trillian" "github.com/google/trillian/monitoring" "github.com/google/trillian/types" - ldcmd "github.com/hyperledger/aries-framework-go/pkg/controller/command/ld" "github.com/hyperledger/aries-framework-go/pkg/crypto" - "github.com/hyperledger/aries-framework-go/pkg/doc/ld" "github.com/hyperledger/aries-framework-go/pkg/doc/verifiable" "github.com/hyperledger/aries-framework-go/pkg/framework/aries/api/vdr" "github.com/hyperledger/aries-framework-go/pkg/kms" - ldsvc "github.com/hyperledger/aries-framework-go/pkg/ld" - ldstore "github.com/hyperledger/aries-framework-go/pkg/store/ld" - "github.com/hyperledger/aries-framework-go/spi/storage" + jsonld "github.com/piprate/json-gold/ld" "github.com/trustbloc/vct/pkg/controller/errors" ) @@ -43,15 +38,11 @@ const ( GetIssuers = "getIssuers" Webfinger = "webfinger" AddVC = "addVC" - AddLdContext = "addLdContext" PublicKeyType = "https://trustbloc.dev/ns/public-key" LedgerType = "https://trustbloc.dev/ns/ledger-type" ) -// StorageProvider represents a storage provider. -type StorageProvider storage.Provider - // KeyManager manages keys and their storage. type KeyManager kms.KeyManager @@ -69,18 +60,16 @@ type Key struct { // Cmd is a controller for commands. type Cmd struct { - baseURL string - logs map[string]Log - VCLogID [32]byte - kh interface{} - vdr vdr.Registry - kms KeyManager - crypto crypto.Crypto - PubKey []byte - storageProvider StorageProvider - alg *SignatureAndHashAlgorithm - loaders sync.Map - ctxCommands sync.Map + baseURL string + logs map[string]Log + VCLogID [32]byte + kh interface{} + vdr vdr.Registry + kms KeyManager + crypto crypto.Crypto + PubKey []byte + alg *SignatureAndHashAlgorithm + loaders map[string]jsonld.DocumentLoader } type permission int32 @@ -104,20 +93,14 @@ type Log struct { // Config for the Cmd. type Config struct { KMS KeyManager - StorageProvider StorageProvider Crypto crypto.Crypto VDR vdr.Registry Logs []Log + DocumentLoaders map[string]jsonld.DocumentLoader // alias -> loader Key Key BaseURL string } -type storageProviderFn func() storage.Provider - -func (spf storageProviderFn) StorageProvider() storage.Provider { - return spf() -} - // nolint: gochecknoglobals var ( once sync.Once @@ -162,32 +145,19 @@ func New(cfg *Config, mf monitoring.MetricFactory) (*Cmd, error) { } return &Cmd{ - storageProvider: cfg.StorageProvider, - vdr: cfg.VDR, - PubKey: pubBytes, - VCLogID: sha256.Sum256(pubBytes), - logs: logs, - kms: cfg.KMS, - kh: kh, - crypto: cfg.Crypto, - alg: alg, - baseURL: cfg.BaseURL, + vdr: cfg.VDR, + PubKey: pubBytes, + VCLogID: sha256.Sum256(pubBytes), + logs: logs, + kms: cfg.KMS, + kh: kh, + crypto: cfg.Crypto, + alg: alg, + baseURL: cfg.BaseURL, + loaders: cfg.DocumentLoaders, }, nil } -type customizedStorageProvider struct { - alias string - StorageProvider -} - -func (s *customizedStorageProvider) OpenStore(name string) (storage.Store, error) { - return s.StorageProvider.OpenStore(s.alias + name) -} - -func (s *customizedStorageProvider) SetStoreConfig(name string, config storage.StoreConfiguration) error { - return s.StorageProvider.SetStoreConfig(s.alias+name, config) -} - // GetHandlers returns list of all commands supported by this controller. func (c *Cmd) GetHandlers() []Handler { return []Handler{ @@ -199,65 +169,7 @@ func (c *Cmd) GetHandlers() []Handler { NewCmdHandler(GetIssuers, c.GetIssuers), NewCmdHandler(Webfinger, c.Webfinger), NewCmdHandler(AddVC, c.AddVC), - NewCmdHandler(AddLdContext, c.AddLdContext), - } -} - -// AddLdContext adds jsonld context. -func (c *Cmd) AddLdContext(w io.Writer, r io.Reader) error { - var req AddLdContextRequest - - if err := json.NewDecoder(r).Decode(&req); err != nil { - return fmt.Errorf("decode AddLdContext request: %w", err) - } - - if err := c.hasPermissions(req.Alias, write); err != nil { - return fmt.Errorf("has permissions: %w", err) - } - - ctxCmd, err := c.getCtxCmd(req.Alias) - if err != nil { - return fmt.Errorf("%w: get ctx cmd", errors.ErrInternal) - } - - return ctxCmd.AddContexts(w, bytes.NewBuffer(req.Context)) // nolint: wrapcheck -} - -func (c *Cmd) getCtxCmd(alias string) (*ldcmd.Command, error) { - val, ok := c.ctxCommands.Load(alias) - if ok { - return val.(*ldcmd.Command), nil - } - - ldStore, err := c.getLDStoreProvider(alias) - if err != nil { - return nil, fmt.Errorf("get LD store provider: %w", err) - } - - c.ctxCommands.Store(alias, ldcmd.New(ldsvc.New(ldStore))) - - return c.getCtxCmd(alias) -} - -func (c *Cmd) documentLoader(alias string) (*ld.DocumentLoader, error) { - val, ok := c.loaders.Load(alias) - if ok { - return val.(*ld.DocumentLoader), nil } - - ldStore, err := c.getLDStoreProvider(alias) - if err != nil { - return nil, fmt.Errorf("get LD store provider: %w", err) - } - - loader, err := ld.NewDocumentLoader(ldStore) - if err != nil { - return nil, fmt.Errorf("new document loader: %w", err) - } - - c.loaders.Store(alias, loader) - - return c.documentLoader(alias) } // GetIssuers returns issuers. @@ -346,9 +258,9 @@ func (c *Cmd) AddVC(w io.Writer, r io.Reader) error { // nolint: funlen return fmt.Errorf("has permissions: %w", err) } - loader, err := c.documentLoader(req.Alias) - if err != nil { - return fmt.Errorf("document loader: %w", err) + loader, ok := c.loaders[req.Alias] + if !ok { + return fmt.Errorf("no document loader found for alias %s", req.Alias) } parseCredentialTime := time.Now() @@ -423,7 +335,7 @@ func (c *Cmd) AddVC(w io.Writer, r io.Reader) error { // nolint: funlen }) } -// GetSTH retrieves latest signed tree head. +// GetSTH retrieves the latest signed tree head. func (c *Cmd) GetSTH(w io.Writer, r io.Reader) error { var alias string @@ -777,40 +689,3 @@ func contains(s []string, e string) bool { return false } - -type ldStoreProvider struct { - ContextStore ldstore.ContextStore - RemoteProviderStore ldstore.RemoteProviderStore -} - -func (p *ldStoreProvider) JSONLDContextStore() ldstore.ContextStore { - return p.ContextStore -} - -func (p *ldStoreProvider) JSONLDRemoteProviderStore() ldstore.RemoteProviderStore { - return p.RemoteProviderStore -} - -func (c *Cmd) getLDStoreProvider(alias string) (*ldStoreProvider, error) { - storageProvider := storageProviderFn(func() storage.Provider { - return &customizedStorageProvider{ - alias: alias, - StorageProvider: c.storageProvider, - } - })() - - contextStore, err := ldstore.NewContextStore(storageProvider) - if err != nil { - return nil, fmt.Errorf("create JSON-LD context store: %w", err) - } - - providerStore, err := ldstore.NewRemoteProviderStore(storageProvider) - if err != nil { - return nil, fmt.Errorf("create remote provider store: %w", err) - } - - return &ldStoreProvider{ - ContextStore: contextStore, - RemoteProviderStore: providerStore, - }, nil -} diff --git a/pkg/controller/command/command_test.go b/pkg/controller/command/command_test.go index 6e538d1..fabd6a1 100644 --- a/pkg/controller/command/command_test.go +++ b/pkg/controller/command/command_test.go @@ -7,7 +7,7 @@ SPDX-License-Identifier: Apache-2.0 package command_test // nolint: lll -//go:generate mockgen -destination gomocks_test.go -self_package mocks -package command_test . KeyManager,TrillianLogClient,Crypto,StorageProvider +//go:generate mockgen -destination gomocks_test.go -self_package mocks -package command_test . KeyManager,TrillianLogClient,Crypto import ( "bytes" @@ -28,7 +28,6 @@ import ( "github.com/hyperledger/aries-framework-go/pkg/kms/localkms" "github.com/hyperledger/aries-framework-go/pkg/secretlock" "github.com/hyperledger/aries-framework-go/pkg/secretlock/noop" - ldstore "github.com/hyperledger/aries-framework-go/pkg/store/ld" "github.com/hyperledger/aries-framework-go/pkg/vdr" "github.com/hyperledger/aries-framework-go/pkg/vdr/key" "github.com/hyperledger/aries-framework-go/spi/storage" @@ -72,7 +71,6 @@ func TestNew(t *testing.T) { ID: kid, Type: kms.ECDSAP256TypeDER, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -91,7 +89,6 @@ func TestNew(t *testing.T) { ID: kid, Type: kms.ECDSAP256TypeDER, }, - StorageProvider: mem.NewProvider(), }, nil) require.EqualError(t, err, "public key is empty") require.Nil(t, cmd) @@ -135,132 +132,6 @@ func TestNew(t *testing.T) { }) } -func TestCmd_AddLdContext(t *testing.T) { - const kid = "kid" - - t.Run("Context URL is mandatory", func(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - km := NewMockKeyManager(ctrl) - km.EXPECT().Get(kid).Return(nil, nil) - km.EXPECT().ExportPubKeyBytes(kid).Return([]byte(`public key`), nil) - - cmd, err := New(&Config{ - KMS: km, Key: Key{ - ID: kid, - Type: kms.ECDSAP256TypeIEEEP1363, - }, - Logs: []Log{{ - Alias: alias, - Permission: "rw", - }}, - StorageProvider: mem.NewProvider(), - }, nil) - require.NoError(t, err) - require.NotNil(t, cmd) - - const payload = `{"alias":"maple2021","context":"eyJkb2N1bWVudHMiOlt7fV19"}` - - require.Error(t, cmd.AddLdContext(nil, bytes.NewBufferString(payload))) - require.Error(t, lookupHandler(t, cmd, AddLdContext)(nil, bytes.NewBufferString(payload))) - }) - - t.Run("Create cmd failed", func(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - km := NewMockKeyManager(ctrl) - km.EXPECT().Get(kid).Return(nil, nil) - km.EXPECT().ExportPubKeyBytes(kid).Return([]byte(`public key`), nil) - - sp := NewMockStorageProvider(ctrl) - sp.EXPECT().OpenStore(gomock.Any()).Return(nil, errors.New("error")).Times(2) - - cmd, err := New(&Config{ - KMS: km, Key: Key{ - ID: kid, - Type: kms.ECDSAP256TypeIEEEP1363, - }, - Logs: []Log{{ - Alias: alias, - Permission: "rw", - }}, - StorageProvider: sp, - }, nil) - require.NoError(t, err) - require.NotNil(t, cmd) - - const ( - errorMsg = "internal error: get ctx cmd" - payload = `{"alias":"maple2021","context":"eyJkb2N1bWVudHMiOlt7fV19"}` - ) - - require.EqualError(t, cmd.AddLdContext(nil, bytes.NewBufferString(payload)), errorMsg) - require.EqualError(t, lookupHandler(t, cmd, AddLdContext)(nil, bytes.NewBufferString(payload)), errorMsg) - }) - - t.Run("No permissions", func(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - km := NewMockKeyManager(ctrl) - km.EXPECT().Get(kid).Return(nil, nil) - km.EXPECT().ExportPubKeyBytes(kid).Return([]byte(`public key`), nil) - - cmd, err := New(&Config{ - KMS: km, Key: Key{ - ID: kid, - Type: kms.ECDSAP256TypeIEEEP1363, - }, - Logs: []Log{{ - Alias: alias, - Permission: "r", - }}, - StorageProvider: mem.NewProvider(), - }, nil) - require.NoError(t, err) - require.NotNil(t, cmd) - - const ( - errorMsg = "has permissions: action forbidden for \"maple2021\"" - payload = `{"alias":"maple2021","context":"eyJkb2N1bWVudHMiOlt7fV19"}` - ) - - require.EqualError(t, cmd.AddLdContext(nil, bytes.NewBufferString(payload)), errorMsg) - require.EqualError(t, lookupHandler(t, cmd, AddLdContext)(nil, bytes.NewBufferString(payload)), errorMsg) - }) - - t.Run("Decode failed", func(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - km := NewMockKeyManager(ctrl) - km.EXPECT().Get(kid).Return(nil, nil) - km.EXPECT().ExportPubKeyBytes(kid).Return([]byte(`public key`), nil) - - cmd, err := New(&Config{ - KMS: km, Key: Key{ - ID: kid, - Type: kms.ECDSAP256TypeIEEEP1363, - }, - StorageProvider: mem.NewProvider(), - }, nil) - require.NoError(t, err) - require.NotNil(t, cmd) - - const errMsg = "decode AddLdContext request: json: cannot unmarshal array into Go" + - " value of type command.AddLdContextRequest" - - require.EqualError(t, cmd.AddLdContext(nil, - bytes.NewBufferString("[]")), errMsg, - ) - require.EqualError(t, lookupHandler(t, cmd, AddLdContext)(nil, - bytes.NewBufferString("[]")), errMsg, - ) - }) -} - func TestCmd_GetIssuers(t *testing.T) { const kid = "kid" @@ -282,7 +153,6 @@ func TestCmd_GetIssuers(t *testing.T) { Permission: "r", Issuers: []string{"issuer_a", "issuer_b"}, }}, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -319,7 +189,6 @@ func TestCmd_GetIssuers(t *testing.T) { Permission: "w", Issuers: []string{"issuer_a", "issuer_b"}, }}, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -352,7 +221,6 @@ func TestCmd_GetIssuers(t *testing.T) { Permission: "w", Issuers: []string{"issuer_a", "issuer_b"}, }}, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -383,8 +251,7 @@ func TestCmd_Webfinger(t *testing.T) { ID: kid, Type: kms.ECDSAP256TypeIEEEP1363, }, - BaseURL: "https://vct.com", - StorageProvider: mem.NewProvider(), + BaseURL: "https://vct.com", }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -440,7 +307,6 @@ func TestCmd_GetEntries(t *testing.T) { Permission: "r", Client: client, }}, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -474,7 +340,6 @@ func TestCmd_GetEntries(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -499,7 +364,6 @@ func TestCmd_GetEntries(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -536,7 +400,6 @@ func TestCmd_GetEntries(t *testing.T) { Permission: "r", Client: client, }}, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -573,7 +436,6 @@ func TestCmd_GetEntries(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -612,7 +474,6 @@ func TestCmd_GetEntries(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -654,7 +515,6 @@ func TestCmd_GetEntries(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -682,7 +542,6 @@ func TestCmd_GetEntries(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -727,7 +586,6 @@ func TestCmd_GetProofByHash(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -764,7 +622,6 @@ func TestCmd_GetProofByHash(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -789,7 +646,6 @@ func TestCmd_GetProofByHash(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -831,7 +687,6 @@ func TestCmd_GetProofByHash(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -880,7 +735,6 @@ func TestCmd_GetSTHConsistency(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -921,7 +775,6 @@ func TestCmd_GetSTHConsistency(t *testing.T) { Alias: alias, Permission: "r", }}, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -958,7 +811,6 @@ func TestCmd_GetSTHConsistency(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -983,7 +835,6 @@ func TestCmd_GetSTHConsistency(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1025,7 +876,6 @@ func TestCmd_GetSTHConsistency(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1054,7 +904,6 @@ func TestCmd_GetSTHConsistency(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1104,7 +953,6 @@ func TestCmd_GetSTH(t *testing.T) { ID: newKID, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1151,7 +999,6 @@ func TestCmd_GetSTH(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1185,7 +1032,6 @@ func TestCmd_GetSTH(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1221,7 +1067,6 @@ func TestCmd_GetSTH(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1261,7 +1106,6 @@ func TestCmd_GetSTH(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1309,7 +1153,6 @@ func TestCmd_GetEntryAndProof(t *testing.T) { ID: newKID, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1362,7 +1205,6 @@ func TestCmd_GetEntryAndProof(t *testing.T) { ID: newKID, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1404,7 +1246,6 @@ func TestCmd_GetEntryAndProof(t *testing.T) { ID: newKID, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1442,6 +1283,8 @@ func TestCmd_AddVC(t *testing.T) { keyType = kms.ECDSAP256TypeIEEEP1363 ) + documentLoader := ldcontext.DocumentLoader(t) + t.Run("Success", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -1459,9 +1302,6 @@ func TestCmd_AddVC(t *testing.T) { }, nil, ).Times(2) - db := mem.NewProvider() - loadContexts(t, db, alias) - cmd, err := New(&Config{ KMS: km, Crypto: cr, @@ -1475,7 +1315,7 @@ func TestCmd_AddVC(t *testing.T) { ID: newKID, Type: keyType, }, - StorageProvider: db, + DocumentLoaders: map[string]jsonld.DocumentLoader{alias: documentLoader}, }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1521,9 +1361,6 @@ func TestCmd_AddVC(t *testing.T) { newKID, _, err := km.Create(keyType) require.NoError(t, err) - db := NewMockStorageProvider(ctrl) - db.EXPECT().OpenStore(gomock.Any()).Return(nil, errors.New("error")).Times(2) - cmd, err := New(&Config{ KMS: km, Crypto: cr, @@ -1537,7 +1374,6 @@ func TestCmd_AddVC(t *testing.T) { ID: newKID, Type: keyType, }, - StorageProvider: db, }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1567,7 +1403,6 @@ func TestCmd_AddVC(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: mem.NewProvider(), }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1595,7 +1430,7 @@ func TestCmd_AddVC(t *testing.T) { Alias: alias, Permission: "w", }}, - StorageProvider: mem.NewProvider(), + DocumentLoaders: map[string]jsonld.DocumentLoader{alias: documentLoader}, }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1613,9 +1448,6 @@ func TestCmd_AddVC(t *testing.T) { km.EXPECT().Get(kid).Return(nil, nil) km.EXPECT().ExportPubKeyBytes(kid).Return([]byte(`public key`), nil) - db := mem.NewProvider() - loadContexts(t, db, alias) - cmd, err := New(&Config{ KMS: km, Logs: []Log{{ @@ -1628,7 +1460,7 @@ func TestCmd_AddVC(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: db, + DocumentLoaders: map[string]jsonld.DocumentLoader{alias: documentLoader}, }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1655,9 +1487,6 @@ func TestCmd_AddVC(t *testing.T) { client := NewMockTrillianLogClient(ctrl) client.EXPECT().QueueLeaf(gomock.Any(), gomock.Any()).Return(nil, errors.New("error")).Times(2) - db := mem.NewProvider() - loadContexts(t, db, alias) - cmd, err := New(&Config{ KMS: km, Logs: []Log{{ @@ -1670,7 +1499,7 @@ func TestCmd_AddVC(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: db, + DocumentLoaders: map[string]jsonld.DocumentLoader{alias: documentLoader}, }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1697,9 +1526,6 @@ func TestCmd_AddVC(t *testing.T) { client := NewMockTrillianLogClient(ctrl) client.EXPECT().QueueLeaf(gomock.Any(), gomock.Any()).Return(&trillian.QueueLeafResponse{}, nil).Times(2) - db := mem.NewProvider() - loadContexts(t, db, alias) - cmd, err := New(&Config{ KMS: km, Logs: []Log{{ @@ -1712,7 +1538,7 @@ func TestCmd_AddVC(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: db, + DocumentLoaders: map[string]jsonld.DocumentLoader{alias: documentLoader}, }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1745,9 +1571,6 @@ func TestCmd_AddVC(t *testing.T) { }, }, nil).Times(2) - db := mem.NewProvider() - loadContexts(t, db, alias) - cmd, err := New(&Config{ KMS: km, Logs: []Log{{ @@ -1760,7 +1583,7 @@ func TestCmd_AddVC(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: db, + DocumentLoaders: map[string]jsonld.DocumentLoader{alias: documentLoader}, }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1796,9 +1619,6 @@ func TestCmd_AddVC(t *testing.T) { }, }, nil).Times(2) - db := mem.NewProvider() - loadContexts(t, db, alias) - cmd, err := New(&Config{ KMS: km, Logs: []Log{{ @@ -1812,7 +1632,7 @@ func TestCmd_AddVC(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: db, + DocumentLoaders: map[string]jsonld.DocumentLoader{alias: documentLoader}, }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1836,9 +1656,6 @@ func TestCmd_AddVC(t *testing.T) { km.EXPECT().Get(kid).Return(nil, nil) km.EXPECT().ExportPubKeyBytes(kid).Return([]byte(`public key`), nil) - db := mem.NewProvider() - loadContexts(t, db, alias) - cmd, err := New(&Config{ KMS: km, Logs: []Log{{ @@ -1851,7 +1668,7 @@ func TestCmd_AddVC(t *testing.T) { ID: kid, Type: keyType, }, - StorageProvider: db, + DocumentLoaders: map[string]jsonld.DocumentLoader{alias: documentLoader}, }, nil) require.NoError(t, err) require.NotNil(t, cmd) @@ -1884,32 +1701,6 @@ func lookupHandler(t *testing.T, cmd *Cmd, name string) Exec { } } -func loadContexts(t *testing.T, p storage.Provider, prefix string) { // nolint: unparam - t.Helper() - - store, err := p.OpenStore(prefix + ldstore.ContextStoreName) - require.NoError(t, err) - - var ops []storage.Operation - - for _, doc := range ldcontext.MustGetAll() { - var content interface{} - content, err = jsonld.DocumentFromReader(bytes.NewReader(doc.Content)) - require.NoError(t, err) - - var b []byte - b, err = json.Marshal(jsonld.RemoteDocument{ - DocumentURL: doc.URL, - Document: content, - }) - require.NoError(t, err) - - ops = append(ops, storage.Operation{Key: doc.URL, Value: b}) - } - - require.NoError(t, store.Batch(ops)) -} - func createKMSAndCrypto(t *testing.T) (kms.KeyManager, crypto.Crypto) { t.Helper() diff --git a/pkg/controller/command/models.go b/pkg/controller/command/models.go index 7b831fe..69035fe 100644 --- a/pkg/controller/command/models.go +++ b/pkg/controller/command/models.go @@ -263,12 +263,6 @@ type AddVCRequest struct { VCEntry []byte `json:"vc_entry"` } -// AddLdContextRequest represents the request to add ld context. -type AddLdContextRequest struct { - Alias string `json:"alias"` - Context []byte `json:"context"` -} - // WebFingerResponse web finger response. type WebFingerResponse struct { Subject string `json:"subject,omitempty"` diff --git a/pkg/controller/rest/models.go b/pkg/controller/rest/models.go index 33fb944..2257500 100644 --- a/pkg/controller/rest/models.go +++ b/pkg/controller/rest/models.go @@ -9,8 +9,6 @@ package rest import ( "time" - ldcmd "github.com/hyperledger/aries-framework-go/pkg/controller/command/ld" - "github.com/trustbloc/vct/pkg/controller/command" ) @@ -22,28 +20,6 @@ type genericError struct { // nolint:unused,deadcode Body ErrorResponse } -// Request message -// -// swagger:parameters addLdContextRequest -type addLdContextRequest struct { // nolint: unused,deadcode - // Alias - // - // in: path - // required: true - Alias string `json:"alias"` - - // in: body - Body ldcmd.AddContextsRequest -} - -// Response message -// -// swagger:response addLdContextResponse -type addLdContextResponse struct { // nolint: unused,deadcode - // in: body - Body struct{} -} - // Request message // // swagger:parameters addVCRequest diff --git a/pkg/controller/rest/operation.go b/pkg/controller/rest/operation.go index 5fbf6bf..c9bc27c 100644 --- a/pkg/controller/rest/operation.go +++ b/pkg/controller/rest/operation.go @@ -32,16 +32,15 @@ var logger = log.New("controller/rest") const ( aliasVarName = "alias" AliasPath = "/{" + aliasVarName + "}" - basePath = AliasPath + "/v1" - AddVCPath = basePath + "/add-vc" - GetSTHPath = basePath + "/get-sth" - GetSTHConsistencyPath = basePath + "/get-sth-consistency" - GetProofByHashPath = basePath + "/get-proof-by-hash" - GetEntriesPath = basePath + "/get-entries" - GetIssuersPath = basePath + "/get-issuers" - GetEntryAndProofPath = basePath + "/get-entry-and-proof" + BasePath = AliasPath + "/v1" + AddVCPath = BasePath + "/add-vc" + GetSTHPath = BasePath + "/get-sth" + GetSTHConsistencyPath = BasePath + "/get-sth-consistency" + GetProofByHashPath = BasePath + "/get-proof-by-hash" + GetEntriesPath = BasePath + "/get-entries" + GetIssuersPath = BasePath + "/get-issuers" + GetEntryAndProofPath = BasePath + "/get-entry-and-proof" WebfingerPath = AliasPath + "/.well-known/webfinger" - AddContextPath = basePath + "/context/add" HealthCheckPath = "/healthcheck" MetricsPath = "/metrics" ) @@ -68,8 +67,6 @@ var ( getEntryAndProofLatency monitoring.Histogram getIssuersCounter monitoring.Counter getIssuersLatency monitoring.Histogram - contextAddCounter monitoring.Counter - contextAddLatency monitoring.Histogram webfingerCounter monitoring.Counter webfingerLatency monitoring.Histogram ) @@ -97,9 +94,6 @@ func createMetrics(mf monitoring.MetricFactory) { getIssuersCounter = mf.NewCounter("get_issuers", "Number of /get-issuers operation", "alias") getIssuersLatency = mf.NewHistogram("get_issuers_latency", "Latency of /get-issuers operation in seconds", "alias") - contextAddCounter = mf.NewCounter("context_add", "Number of /context/add operation", "alias") - contextAddLatency = mf.NewHistogram("context_add_latency", "Latency of /context/add operation in seconds", "alias") - webfingerCounter = mf.NewCounter("webfinger", "Number of /webfinger operation", "alias") webfingerLatency = mf.NewHistogram("webfinger_latency", "Latency of /webfinger operation in seconds", "alias") } @@ -114,7 +108,6 @@ type Cmd interface { GetEntries(io.Writer, io.Reader) error GetEntryAndProof(io.Writer, io.Reader) error Webfinger(io.Writer, io.Reader) error - AddLdContext(io.Writer, io.Reader) error } // Operation represents REST API controller. @@ -146,8 +139,6 @@ func (c *Operation) GetRESTHandlers() []Handler { NewHTTPHandler(WebfingerPath, http.MethodGet, c.Webfinger), NewHTTPHandler(GetEntryAndProofPath, http.MethodGet, c.GetEntryAndProof), NewHTTPHandler(HealthCheckPath, http.MethodGet, c.HealthCheck), - // JSON-LD contexts API - NewHTTPHandler(AddContextPath, http.MethodPost, c.AddLdContext), // Metrics NewHTTPHandler(MetricsPath, http.MethodGet, c.metrics()), } @@ -166,48 +157,6 @@ func (c *Operation) metrics() http.HandlerFunc { } } -// AddLdContext swagger:route POST /{alias}/v1/context/add vct addLdContextRequest -// -// Adds jsonld context. -// -// Responses: -// default: genericError -// 200: addLdContextResponse -func (c *Operation) AddLdContext(w http.ResponseWriter, r *http.Request) { - var ( - context bytes.Buffer - start = time.Now() - ) - - _, err := io.Copy(&context, r.Body) - if err != nil { - sendError(w, fmt.Errorf("%w: copy context", errors.ErrInternal)) - - return - } - - req, err := json.Marshal(command.AddLdContextRequest{ - Alias: mux.Vars(r)[aliasVarName], - Context: context.Bytes(), - }) - if err != nil { - sendError(w, fmt.Errorf("%w: marshal AddLdContextRequest", errors.ErrInternal)) - - return - } - - execute(func(rw io.Writer, req io.Reader) error { - if err := c.cmd.AddLdContext(rw, req); err != nil { - return err - } - - contextAddCounter.Add(1, mux.Vars(r)[aliasVarName]) - contextAddLatency.Observe(time.Since(start).Seconds(), mux.Vars(r)[aliasVarName]) - - return nil - }, w, bytes.NewBuffer(req)) -} - // AddVC swagger:route POST /{alias}/v1/add-vc vct addVCRequest // // Adds verifiable credential to log. diff --git a/pkg/controller/rest/operation_test.go b/pkg/controller/rest/operation_test.go index bea021a..7f4f45d 100644 --- a/pkg/controller/rest/operation_test.go +++ b/pkg/controller/rest/operation_test.go @@ -87,65 +87,6 @@ func TestOperation_AddVC(t *testing.T) { }) } -func TestOperation_AddLdContext(t *testing.T) { - t.Run("Success", func(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - const dummyPayload = `{"documents":[]}` - - cmd := NewMockCmd(ctrl) - cmd.EXPECT().AddLdContext(gomock.Any(), gomock.Any()).Do(func(_ io.Writer, r io.Reader) { - var req *command.AddLdContextRequest - require.NoError(t, json.NewDecoder(r).Decode(&req)) - require.Equal(t, alias, req.Alias) - }).Return(nil) - - operation := New(cmd, nil) - - _, code := sendRequestToHandler(t, - handlerLookup(t, operation, AddContextPath), - bytes.NewBufferString(dummyPayload), strings.Replace(AddContextPath, "{alias}", alias, 1), - ) - - require.Equal(t, http.StatusOK, code) - }) - - t.Run("Internal server error", func(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - const dummyPayload = `{"documents":[]}` - - cmd := NewMockCmd(ctrl) - cmd.EXPECT().AddLdContext(gomock.Any(), gomock.Any()).Do(func(_ io.Writer, r io.Reader) { - var req *command.AddLdContextRequest - require.NoError(t, json.NewDecoder(r).Decode(&req)) - require.Equal(t, alias, req.Alias) - }).Return(errors.New("error")) - - operation := New(cmd, nil) - - _, code := sendRequestToHandler(t, - handlerLookup(t, operation, AddContextPath), - bytes.NewBufferString(dummyPayload), strings.Replace(AddContextPath, "{alias}", alias, 1), - ) - - require.Equal(t, http.StatusInternalServerError, code) - }) - - t.Run("Bad request", func(t *testing.T) { - operation := New(nil, nil) - - _, code := sendRequestToHandler(t, - handlerLookup(t, operation, AddContextPath), - &readerMock{errors.New("EOF")}, AddContextPath, - ) - - require.Equal(t, http.StatusInternalServerError, code) - }) -} - func TestOperation_GetSTH(t *testing.T) { t.Run("Success", func(t *testing.T) { ctrl := gomock.NewController(t) diff --git a/test/bdd/features/rest_controller.feature b/test/bdd/features/rest_controller.feature index 9c56804..aaf7aa8 100644 --- a/test/bdd/features/rest_controller.feature +++ b/test/bdd/features/rest_controller.feature @@ -80,10 +80,6 @@ Feature: Verifiable credentials transparency API. And Retrieve entries from log and check that len is "1" And Retrieve merkle audit proof from log by leaf hash for "maple2020/bachelor_degree_web_no_proof.json" - Scenario: Context is not supported - Given VCT agent is running on "http://localhost:5678/maple2024" without contexts - Then Add verifiable credential "maple2020/bachelor_degree_web_no_proof.json" to Log is not a valid JSON-LD context - Scenario: Checks issuers Given VCT agent is running on "http://localhost:5678/maple2020" Then The issuer "did:key:zUC724vuGvHpnCGFG1qqpXb81SiBLu3KLSqVzenwEZNPoY35i2Bscb8DLaVwHvRFs6F2NkNNXRcPWvqnPDUd9ukdjLkjZd3u9zzL4wDZDUpkPAatLDGLEYVo8kkAzuAKJQMr7N7" is supported diff --git a/test/bdd/fixtures/vct/contexts/ld-contexts.json b/test/bdd/fixtures/vct/contexts/ld-contexts.json new file mode 100644 index 0000000..9dac070 --- /dev/null +++ b/test/bdd/fixtures/vct/contexts/ld-contexts.json @@ -0,0 +1,486 @@ +{ + "documents": [ + { + "url": "https://trustbloc.github.io/did-method-orb/contexts/anchor/v1", + "content": { + "@context": { + "@version": 1.1, + "@protected": true, + "AnchorCredential": { + "@id": "https://trustbloc.dev/ns/orb#AnchorCredential", + "@context": { + "@version": 1.1, + "@protected": true, + "id": "@id", + "type": "@type" + } + }, + "Anchor": { + "@id": "https://trustbloc.dev/ns/orb#Anchor", + "@context": { + "@version": 1.1, + "@protected": true, + "id": "@id", + "type": "@type", + "orb": "https://trustbloc.dev/ns/orb#", + "coreIndex": "orb:coreIndex", + "operationCount": "orb:operationCount", + "namespace": "orb:namespace", + "previousAnchors": "orb:previousAnchors", + "version": "orb:version" + } + }, + "AnchorCredentialReference": { + "@id": "https://trustbloc.dev/ns/orb#AnchorCredentialReference", + "@context": { + "@version": 1.1, + "@protected": true, + "id": "@id", + "type": "@type" + } + }, + "ContentAddressedStorage": { + "@id": "https://trustbloc.dev/ns/orb#ContentAddressedStorage", + "@context": { + "@version": 1.1, + "@protected": true, + "id": "@id", + "type": "@type", + "orb": "https://trustbloc.dev/ns/orb#", + "cid": "orb:contentIdentifier" + } + } + } + } + }, + { + "url": "https://www.w3.org/2018/credentials/examples/v1", + "content": { + "@context": [{ + "@version": 1.1 + },"https://www.w3.org/ns/odrl.jsonld", { + "ex": "https://example.org/examples#", + "schema": "http://schema.org/", + "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + + "3rdPartyCorrelation": "ex:3rdPartyCorrelation", + "AllVerifiers": "ex:AllVerifiers", + "Archival": "ex:Archival", + "BachelorDegree": "ex:BachelorDegree", + "Child": "ex:Child", + "CLCredentialDefinition2019": "ex:CLCredentialDefinition2019", + "CLSignature2019": "ex:CLSignature2019", + "IssuerPolicy": "ex:IssuerPolicy", + "HolderPolicy": "ex:HolderPolicy", + "Mother": "ex:Mother", + "RelationshipCredential": "ex:RelationshipCredential", + "UniversityDegreeCredential": "ex:UniversityDegreeCredential", + "ZkpExampleSchema2018": "ex:ZkpExampleSchema2018", + + "issuerData": "ex:issuerData", + "attributes": "ex:attributes", + "signature": "ex:signature", + "signatureCorrectnessProof": "ex:signatureCorrectnessProof", + "primaryProof": "ex:primaryProof", + "nonRevocationProof": "ex:nonRevocationProof", + + "alumniOf": {"@id": "schema:alumniOf", "@type": "rdf:HTML"}, + "child": {"@id": "ex:child", "@type": "@id"}, + "degree": "ex:degree", + "degreeType": "ex:degreeType", + "degreeSchool": "ex:degreeSchool", + "college": "ex:college", + "name": {"@id": "schema:name", "@type": "rdf:HTML"}, + "givenName": "schema:givenName", + "familyName": "schema:familyName", + "parent": {"@id": "ex:parent", "@type": "@id"}, + "referenceId": "ex:referenceId", + "documentPresence": "ex:documentPresence", + "evidenceDocument": "ex:evidenceDocument", + "spouse": "schema:spouse", + "subjectPresence": "ex:subjectPresence", + "verifier": {"@id": "ex:verifier", "@type": "@id"} + }] + } + }, + { + "url": "https://w3id.org/jws/v1", + "content": { + "@context": { + "privateKeyJwk": "https://w3id.org/security#privateKeyJwk", + "JsonWebKey2020": { + "@id": "https://w3id.org/security#JsonWebKey2020", + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "publicKeyJwk": "https://w3id.org/security#publicKeyJwk" + } + }, + "JsonWebSignature2020": { + "@id": "https://w3id.org/security#JsonWebSignature2020", + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "challenge": "https://w3id.org/security#challenge", + "created": { + "@id": "http://purl.org/dc/terms/created", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + }, + "domain": "https://w3id.org/security#domain", + "expires": { + "@id": "https://w3id.org/security#expiration", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + }, + "jws": "https://w3id.org/security#jws", + "nonce": "https://w3id.org/security#nonce", + "proofPurpose": { + "@id": "https://w3id.org/security#proofPurpose", + "@type": "@vocab", + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "assertionMethod": { + "@id": "https://w3id.org/security#assertionMethod", + "@type": "@id", + "@container": "@set" + }, + "authentication": { + "@id": "https://w3id.org/security#authenticationMethod", + "@type": "@id", + "@container": "@set" + }, + "capabilityInvocation": { + "@id": "https://w3id.org/security#capabilityInvocationMethod", + "@type": "@id", + "@container": "@set" + }, + "capabilityDelegation": { + "@id": "https://w3id.org/security#capabilityDelegationMethod", + "@type": "@id", + "@container": "@set" + }, + "keyAgreement": { + "@id": "https://w3id.org/security#keyAgreementMethod", + "@type": "@id", + "@container": "@set" + } + } + }, + "verificationMethod": { + "@id": "https://w3id.org/security#verificationMethod", + "@type": "@id" + } + } + } + } + } + }, + { + "url": "https://www.w3.org/ns/odrl.jsonld", + "content": { + "@context": { + "odrl": "http://www.w3.org/ns/odrl/2/", + "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + "rdfs": "http://www.w3.org/2000/01/rdf-schema#", + "owl": "http://www.w3.org/2002/07/owl#", + "skos": "http://www.w3.org/2004/02/skos/core#", + "dct": "http://purl.org/dc/terms/", + "xsd": "http://www.w3.org/2001/XMLSchema#", + "vcard": "http://www.w3.org/2006/vcard/ns#", + "foaf": "http://xmlns.com/foaf/0.1/", + "schema": "http://schema.org/", + "cc": "http://creativecommons.org/ns#", + "uid": "@id", + "type": "@type", + "Policy": "odrl:Policy", + "Rule": "odrl:Rule", + "profile": { + "@type": "@id", + "@id": "odrl:profile" + }, + "inheritFrom": { + "@type": "@id", + "@id": "odrl:inheritFrom" + }, + "ConflictTerm": "odrl:ConflictTerm", + "conflict": { + "@type": "@vocab", + "@id": "odrl:conflict" + }, + "perm": "odrl:perm", + "prohibit": "odrl:prohibit", + "invalid": "odrl:invalid", + "Agreement": "odrl:Agreement", + "Assertion": "odrl:Assertion", + "Offer": "odrl:Offer", + "Privacy": "odrl:Privacy", + "Invitation": "odrl:Invitation", + "Set": "odrl:Set", + "Ticket": "odrl:Ticket", + "Asset": "odrl:Asset", + "AssetCollection": "odrl:AssetCollection", + "relation": { + "@type": "@id", + "@id": "odrl:relation" + }, + "hasPolicy": { + "@type": "@id", + "@id": "odrl:hasPolicy" + }, + "target": { + "@type": "@id", + "@id": "odrl:target" + }, + "output": { + "@type": "@id", + "@id": "odrl:output" + }, + "partOf": { + "@type": "@id", + "@id": "odrl:partOf" + }, + "source": { + "@type": "@id", + "@id": "odrl:source" + }, + "Party": "odrl:Party", + "PartyCollection": "odrl:PartyCollection", + "function": { + "@type": "@vocab", + "@id": "odrl:function" + }, + "PartyScope": "odrl:PartyScope", + "assignee": { + "@type": "@id", + "@id": "odrl:assignee" + }, + "assigner": { + "@type": "@id", + "@id": "odrl:assigner" + }, + "assigneeOf": { + "@type": "@id", + "@id": "odrl:assigneeOf" + }, + "assignerOf": { + "@type": "@id", + "@id": "odrl:assignerOf" + }, + "attributedParty": { + "@type": "@id", + "@id": "odrl:attributedParty" + }, + "attributingParty": { + "@type": "@id", + "@id": "odrl:attributingParty" + }, + "compensatedParty": { + "@type": "@id", + "@id": "odrl:compensatedParty" + }, + "compensatingParty": { + "@type": "@id", + "@id": "odrl:compensatingParty" + }, + "consentingParty": { + "@type": "@id", + "@id": "odrl:consentingParty" + }, + "consentedParty": { + "@type": "@id", + "@id": "odrl:consentedParty" + }, + "informedParty": { + "@type": "@id", + "@id": "odrl:informedParty" + }, + "informingParty": { + "@type": "@id", + "@id": "odrl:informingParty" + }, + "trackingParty": { + "@type": "@id", + "@id": "odrl:trackingParty" + }, + "trackedParty": { + "@type": "@id", + "@id": "odrl:trackedParty" + }, + "contractingParty": { + "@type": "@id", + "@id": "odrl:contractingParty" + }, + "contractedParty": { + "@type": "@id", + "@id": "odrl:contractedParty" + }, + "Action": "odrl:Action", + "action": { + "@type": "@vocab", + "@id": "odrl:action" + }, + "includedIn": { + "@type": "@id", + "@id": "odrl:includedIn" + }, + "implies": { + "@type": "@id", + "@id": "odrl:implies" + }, + "Permission": "odrl:Permission", + "permission": { + "@type": "@id", + "@id": "odrl:permission" + }, + "Prohibition": "odrl:Prohibition", + "prohibition": { + "@type": "@id", + "@id": "odrl:prohibition" + }, + "obligation": { + "@type": "@id", + "@id": "odrl:obligation" + }, + "use": "odrl:use", + "grantUse": "odrl:grantUse", + "aggregate": "odrl:aggregate", + "annotate": "odrl:annotate", + "anonymize": "odrl:anonymize", + "archive": "odrl:archive", + "concurrentUse": "odrl:concurrentUse", + "derive": "odrl:derive", + "digitize": "odrl:digitize", + "display": "odrl:display", + "distribute": "odrl:distribute", + "execute": "odrl:execute", + "extract": "odrl:extract", + "give": "odrl:give", + "index": "odrl:index", + "install": "odrl:install", + "modify": "odrl:modify", + "move": "odrl:move", + "play": "odrl:play", + "present": "odrl:present", + "print": "odrl:print", + "read": "odrl:read", + "reproduce": "odrl:reproduce", + "sell": "odrl:sell", + "stream": "odrl:stream", + "textToSpeech": "odrl:textToSpeech", + "transfer": "odrl:transfer", + "transform": "odrl:transform", + "translate": "odrl:translate", + "Duty": "odrl:Duty", + "duty": { + "@type": "@id", + "@id": "odrl:duty" + }, + "consequence": { + "@type": "@id", + "@id": "odrl:consequence" + }, + "remedy": { + "@type": "@id", + "@id": "odrl:remedy" + }, + "acceptTracking": "odrl:acceptTracking", + "attribute": "odrl:attribute", + "compensate": "odrl:compensate", + "delete": "odrl:delete", + "ensureExclusivity": "odrl:ensureExclusivity", + "include": "odrl:include", + "inform": "odrl:inform", + "nextPolicy": "odrl:nextPolicy", + "obtainConsent": "odrl:obtainConsent", + "reviewPolicy": "odrl:reviewPolicy", + "uninstall": "odrl:uninstall", + "watermark": "odrl:watermark", + "Constraint": "odrl:Constraint", + "LogicalConstraint": "odrl:LogicalConstraint", + "constraint": { + "@type": "@id", + "@id": "odrl:constraint" + }, + "refinement": { + "@type": "@id", + "@id": "odrl:refinement" + }, + "Operator": "odrl:Operator", + "operator": { + "@type": "@vocab", + "@id": "odrl:operator" + }, + "RightOperand": "odrl:RightOperand", + "rightOperand": "odrl:rightOperand", + "rightOperandReference": { + "@type": "xsd:anyURI", + "@id": "odrl:rightOperandReference" + }, + "LeftOperand": "odrl:LeftOperand", + "leftOperand": { + "@type": "@vocab", + "@id": "odrl:leftOperand" + }, + "unit": "odrl:unit", + "dataType": { + "@type": "xsd:anyType", + "@id": "odrl:datatype" + }, + "status": "odrl:status", + "absolutePosition": "odrl:absolutePosition", + "absoluteSpatialPosition": "odrl:absoluteSpatialPosition", + "absoluteTemporalPosition": "odrl:absoluteTemporalPosition", + "absoluteSize": "odrl:absoluteSize", + "count": "odrl:count", + "dateTime": "odrl:dateTime", + "delayPeriod": "odrl:delayPeriod", + "deliveryChannel": "odrl:deliveryChannel", + "elapsedTime": "odrl:elapsedTime", + "event": "odrl:event", + "fileFormat": "odrl:fileFormat", + "industry": "odrl:industry:", + "language": "odrl:language", + "media": "odrl:media", + "meteredTime": "odrl:meteredTime", + "payAmount": "odrl:payAmount", + "percentage": "odrl:percentage", + "product": "odrl:product", + "purpose": "odrl:purpose", + "recipient": "odrl:recipient", + "relativePosition": "odrl:relativePosition", + "relativeSpatialPosition": "odrl:relativeSpatialPosition", + "relativeTemporalPosition": "odrl:relativeTemporalPosition", + "relativeSize": "odrl:relativeSize", + "resolution": "odrl:resolution", + "spatial": "odrl:spatial", + "spatialCoordinates": "odrl:spatialCoordinates", + "systemDevice": "odrl:systemDevice", + "timeInterval": "odrl:timeInterval", + "unitOfCount": "odrl:unitOfCount", + "version": "odrl:version", + "virtualLocation": "odrl:virtualLocation", + "eq": "odrl:eq", + "gt": "odrl:gt", + "gteq": "odrl:gteq", + "lt": "odrl:lt", + "lteq": "odrl:lteq", + "neq": "odrl:neg", + "isA": "odrl:isA", + "hasPart": "odrl:hasPart", + "isPartOf": "odrl:isPartOf", + "isAllOf": "odrl:isAllOf", + "isAnyOf": "odrl:isAnyOf", + "isNoneOf": "odrl:isNoneOf", + "or": "odrl:or", + "xone": "odrl:xone", + "and": "odrl:and", + "andSequence": "odrl:andSequence", + "policyUsage": "odrl:policyUsage" + } + } + } + ] +} diff --git a/test/bdd/fixtures/vct/docker-compose.yml b/test/bdd/fixtures/vct/docker-compose.yml index d853a43..f2cd553 100644 --- a/test/bdd/fixtures/vct/docker-compose.yml +++ b/test/bdd/fixtures/vct/docker-compose.yml @@ -135,6 +135,7 @@ services: - VCT_DATABASE_PREFIX=vctdb_ - VCT_ISSUERS=maple2021@did:key:zUC724vuGvHpnCGFG1qqpXb81SiBLu3KLSqVzenwEZNPoY35i2Bscb8DLaVwHvRFs6F2NkNNXRcPWvqnPDUd9ukdjLkjZd3u9zzL4wDZDUpkPAatLDGLEYVo8kkAzuAKJQMr7N2,maple2020@did:key:zUC724vuGvHpnCGFG1qqpXb81SiBLu3KLSqVzenwEZNPoY35i2Bscb8DLaVwHvRFs6F2NkNNXRcPWvqnPDUd9ukdjLkjZd3u9zzL4wDZDUpkPAatLDGLEYVo8kkAzuAKJQMr7N7 - VCT_TLS_CACERTS=/etc/tls/vct.local.crt + - VCT_CONTEXT_PROVIDER_URL=https://web.vct.local:443/ld-contexts.json volumes: - ./keys/tls:/etc/tls command: start @@ -142,6 +143,7 @@ services: - vct.mongodb - vct.kms - vct.trillian.log.server + - web.vct.local networks: - witness_ledger_net @@ -159,6 +161,7 @@ services: - VCT_DATABASE_PREFIX=vctdb_ - VCT_ISSUERS=maple2021@did:key:zUC724vuGvHpnCGFG1qqpXb81SiBLu3KLSqVzenwEZNPoY35i2Bscb8DLaVwHvRFs6F2NkNNXRcPWvqnPDUd9ukdjLkjZd3u9zzL4wDZDUpkPAatLDGLEYVo8kkAzuAKJQMr7N2,maple2020@did:key:zUC724vuGvHpnCGFG1qqpXb81SiBLu3KLSqVzenwEZNPoY35i2Bscb8DLaVwHvRFs6F2NkNNXRcPWvqnPDUd9ukdjLkjZd3u9zzL4wDZDUpkPAatLDGLEYVo8kkAzuAKJQMr7N7 - VCT_TLS_CACERTS=/etc/tls/vct.local.crt + - VCT_CONTEXT_PROVIDER_URL=https://web.vct.local:443/ld-contexts.json volumes: - ./keys/tls:/etc/tls command: start @@ -166,6 +169,7 @@ services: - vct.mongodb - vct.kms - vct.trillian.log.server + - web.vct.local networks: - witness_ledger_net @@ -181,6 +185,7 @@ services: ports: - 443:443 volumes: + - ./contexts/ld-contexts.json:/web/ld-contexts.json - ./wellknown/did.json:/web/.well-known/did.json - ./keys/tls:/etc/tls networks: diff --git a/test/bdd/pkg/controller/rest/rest_controller_steps.go b/test/bdd/pkg/controller/rest/rest_controller_steps.go index d4bbab1..b8fc4b3 100644 --- a/test/bdd/pkg/controller/rest/rest_controller_steps.go +++ b/test/bdd/pkg/controller/rest/rest_controller_steps.go @@ -56,9 +56,7 @@ func New() *Steps { // RegisterSteps registers the BDD steps on the suite. func (s *Steps) RegisterSteps(suite *godog.Suite) { suite.Step(`VCT agent is running on "([^"]*)"$`, s.setVCTClient) - suite.Step(`VCT agent is running on "([^"]*)" without contexts$`, s.setVCTClientNoContexts) suite.Step(`Add verifiable credential "([^"]*)" to Log$`, s.addVC) - suite.Step(`Add verifiable credential "([^"]*)" to Log is not a valid JSON-LD context$`, s.addVCBadContext) suite.Step(`No permissions to write$`, s.noWritePerm) suite.Step(`No permissions to read$`, s.noReadPerm) suite.Step(`Retrieve latest signed tree head and check that tree_size is "([^"]*)"$`, s.getSTH) @@ -112,22 +110,6 @@ func (s *Steps) issuerIsNotSupported(issuer string) error { }, backoff.WithMaxRetries(backoff.NewConstantBackOff(time.Second), 15)) } -func (s *Steps) setVCTClientNoContexts(endpoint string) error { - s.vct = vct.New(endpoint, vct.WithHTTPClient(s.client)) - - return backoff.Retry(func() error { // nolint: wrapcheck - resp, err := s.vct.GetSTH(context.Background()) - // ignores the error if it is a permission issue - if err != nil && !strings.Contains(err.Error(), "action forbidden for") { - return err - } - - s.state.GetSTHResponse = resp - - return nil - }, backoff.WithMaxRetries(backoff.NewConstantBackOff(time.Second), 220)) -} - func (s *Steps) setVCTClient(endpoint string) error { s.vct = vct.New(endpoint, vct.WithHTTPClient(s.client)) @@ -140,11 +122,6 @@ func (s *Steps) setVCTClient(endpoint string) error { s.state.GetSTHResponse = resp - err = s.vct.AddJSONLDContexts(context.Background(), ldcontext.MustGetAll()...) - if err != nil && !strings.Contains(err.Error(), "action forbidden for") { - return err - } - return nil }, backoff.WithMaxRetries(backoff.NewConstantBackOff(time.Second), 220)) } @@ -260,24 +237,6 @@ func (s *Steps) addVC(file string) error { return nil } -func (s *Steps) addVCBadContext(file string) error { - src, err := readFile(file) - if err != nil { - return fmt.Errorf("read file: %w", err) - } - - _, err = s.vct.AddVC(context.Background(), src) - if err == nil { - return fmt.Errorf("vc was added successfully") - } - - if strings.Contains(err.Error(), "URL did not result in a valid JSON-LD context") { - return nil - } - - return err -} - func (s *Steps) setTimestamp(from, to string) error { s.state.AddedCredentials[to] = s.state.AddedCredentials[from]