diff --git a/deps/migrations/000001_create_tables.down.sql b/deps/migrations/000001_create_tables.down.sql index 956ecd505..fc15fe61d 100644 --- a/deps/migrations/000001_create_tables.down.sql +++ b/deps/migrations/000001_create_tables.down.sql @@ -3,6 +3,5 @@ BEGIN; DROP TABLE IF EXISTS secrets; DROP TABLE IF EXISTS keys; DROP TABLE IF EXISTS eth_accounts; -DROP TABLE IF EXISTS aliases; COMMIT; \ No newline at end of file diff --git a/deps/migrations/000001_create_tables.up.sql b/deps/migrations/000001_create_tables.up.sql index 6f5834f52..ffcdaec3d 100644 --- a/deps/migrations/000001_create_tables.up.sql +++ b/deps/migrations/000001_create_tables.up.sql @@ -44,12 +44,4 @@ CREATE TABLE IF NOT EXISTS eth_accounts ( UNIQUE(address, store_id) ); -CREATE TABLE IF NOT EXISTS aliases ( - pk SERIAL PRIMARY KEY, - key TEXT NOT NULL, - registry_name TEXT NOT NULL, - value TEXT NOT NULL, - UNIQUE(key, registry_name) -); - COMMIT; diff --git a/pkg/client/aliases.go b/pkg/client/aliases.go deleted file mode 100644 index a97349db2..000000000 --- a/pkg/client/aliases.go +++ /dev/null @@ -1,106 +0,0 @@ -package client - -import ( - "context" - "fmt" - - "github.com/consensys/quorum-key-manager/src/aliases/api/types" -) - -const ( - registryPathf = "%s/registries/%s" - aliasesPathf = "%s/registries/%s/aliases" - aliasPathf = "%s/registries/%s/aliases/%s" -) - -// CreateAlias creates an alias in the registry. -func (c *HTTPClient) CreateAlias(ctx context.Context, registry types.RegistryName, aliasKey types.AliasKey, req types.AliasRequest) (*types.AliasResponse, error) { - url := fmt.Sprintf(aliasPathf, c.config.URL, registry, aliasKey) - resp, err := postRequest(ctx, c.client, url, req) - if err != nil { - return nil, err - } - defer closeResponse(resp) - - var a types.AliasResponse - err = parseResponse(resp, &a) - if err != nil { - return nil, err - } - return &a, nil -} - -// GetAlias gets an alias from the registry. -func (c *HTTPClient) GetAlias(ctx context.Context, registry types.RegistryName, aliasKey types.AliasKey) (*types.AliasResponse, error) { - url := fmt.Sprintf(aliasPathf, c.config.URL, registry, aliasKey) - resp, err := getRequest(ctx, c.client, url) - if err != nil { - return nil, err - } - defer closeResponse(resp) - - var a types.AliasResponse - err = parseResponse(resp, &a) - if err != nil { - return nil, err - } - return &a, nil -} - -// UpdateAlias updates an alias in the registry. -func (c *HTTPClient) UpdateAlias(ctx context.Context, registry types.RegistryName, aliasKey types.AliasKey, req types.AliasRequest) (*types.AliasResponse, error) { - url := fmt.Sprintf(aliasPathf, c.config.URL, registry, aliasKey) - resp, err := putRequest(ctx, c.client, url, req) - if err != nil { - return nil, err - } - defer closeResponse(resp) - - var a types.AliasResponse - err = parseResponse(resp, &a) - if err != nil { - return nil, err - } - return &a, nil -} - -// DeleteAlias deletes an alias from the registry. -func (c *HTTPClient) DeleteAlias(ctx context.Context, registry types.RegistryName, aliasKey types.AliasKey) error { - url := fmt.Sprintf(aliasPathf, c.config.URL, registry, aliasKey) - resp, err := deleteRequest(ctx, c.client, url) - if err != nil { - return err - } - defer closeResponse(resp) - - return parseEmptyBodyResponse(resp) -} - -// ListAliases lists all aliases from a registry. -func (c *HTTPClient) ListAliases(ctx context.Context, registry types.RegistryName) ([]types.Alias, error) { - url := fmt.Sprintf(aliasesPathf, c.config.URL, registry) - resp, err := getRequest(ctx, c.client, url) - if err != nil { - return nil, err - } - defer closeResponse(resp) - - var a []types.Alias - err = parseResponse(resp, &a) - if err != nil { - return nil, err - } - return a, nil -} - -// DeleteRegistry deletes a registry, with all the aliases it contained. -func (c *HTTPClient) DeleteRegistry(ctx context.Context, registry types.RegistryName) error { - url := fmt.Sprintf(registryPathf, c.config.URL, registry) - resp, err := deleteRequest(ctx, c.client, url) - if err != nil { - return err - } - defer closeResponse(resp) - - return parseEmptyBodyResponse(resp) -} diff --git a/src/aliases/api/api.go b/src/aliases/api/api.go deleted file mode 100644 index 0723051ba..000000000 --- a/src/aliases/api/api.go +++ /dev/null @@ -1,22 +0,0 @@ -package aliasapi - -import ( - "github.com/gorilla/mux" - - "github.com/consensys/quorum-key-manager/src/aliases/api/handlers" - aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" -) - -type AliasAPI struct { - alias aliasent.AliasBackend -} - -func New(alias aliasent.AliasBackend) *AliasAPI { - return &AliasAPI{ - alias: alias, - } -} - -func (api *AliasAPI) Register(r *mux.Router) { - handlers.NewAliasHandler(api.alias).Register(r) -} diff --git a/src/aliases/api/handlers/handlers.go b/src/aliases/api/handlers/handlers.go deleted file mode 100644 index 81c7a2c74..000000000 --- a/src/aliases/api/handlers/handlers.go +++ /dev/null @@ -1,297 +0,0 @@ -package handlers - -import ( - "fmt" - "net/http" - "regexp" - "sync" - - "github.com/consensys/quorum-key-manager/pkg/errors" - jsonutils "github.com/consensys/quorum-key-manager/pkg/json" - "github.com/consensys/quorum-key-manager/src/aliases/api/types" - aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" - infrahttp "github.com/consensys/quorum-key-manager/src/infra/http" - "github.com/gorilla/mux" -) - -type AliasHandler struct { - alias aliasent.AliasBackend -} - -func NewAliasHandler(backend aliasent.AliasBackend) *AliasHandler { - h := AliasHandler{ - alias: backend, - } - - return &h -} - -func (h *AliasHandler) Register(r *mux.Router) { - regRoute := r.PathPrefix("/registries/{registry_name}").Subrouter() - regRoute.HandleFunc("", h.deleteRegistry).Methods(http.MethodDelete) - - alRoute := regRoute.PathPrefix("/aliases").Subrouter() - alRoute.HandleFunc("", h.listAliases).Methods(http.MethodGet) - alRoute.HandleFunc("/{alias_key}", h.createAlias).Methods(http.MethodPost) - alRoute.HandleFunc("/{alias_key}", h.getAlias).Methods(http.MethodGet) - alRoute.HandleFunc("/{alias_key}", h.updateAlias).Methods(http.MethodPut) - alRoute.HandleFunc("/{alias_key}", h.deleteAlias).Methods(http.MethodDelete) -} - -// @Summary Delete a registry -// @Description Delete a registry and all its keys -// @Tags Registries -// @Param registry_name path string true "registry identifier" -// @Success 204 "Deleted successfully" -// @Failure 400 {object} ErrorResponse "Invalid request format" -// @Failure 404 {object} ErrorResponse "Registry not found" -// @Failure 500 {object} ErrorResponse "Internal server error" -// @Router /registries/{registry_name} [delete] -func (h *AliasHandler) deleteRegistry(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - // should always exist in this subrouter - regName := vars["registry_name"] - - err := validatePathVars(regName) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, errors.InvalidFormatError(err.Error())) - return - } - - err = h.alias.DeleteRegistry(r.Context(), aliasent.RegistryName(regName)) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, err) - return - } - w.Header().Set("X-Content-Type-Options", "nosniff") - w.WriteHeader(http.StatusNoContent) -} - -// @Summary Creates an alias -// @Description Create an alias of a key in a dedicated alias registry -// @Tags Aliases -// @Accept json -// @Produce json -// @Param registry_name path string true "registry identifier" -// @Param alias_key path string true "alias identifier" -// @Param request body types.AliasRequest true "Create Alias Request" -// @Success 200 {object} types.AliasResponse "Alias data" -// @Failure 400 {object} ErrorResponse "Invalid request format" -// @Failure 500 {object} ErrorResponse "Internal server error" -// @Router /registries/{registry_name}/aliases/{alias_key} [post] -func (h *AliasHandler) createAlias(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - // should always exist in this subrouter - regName := vars["registry_name"] - key := vars["alias_key"] - - err := validatePathVars(regName, key) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, errors.InvalidFormatError(err.Error())) - return - } - - var aliasReq types.AliasRequest - err = jsonutils.UnmarshalBody(r.Body, &aliasReq) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, errors.InvalidFormatError(err.Error())) - return - } - - eAlias := types.FormatAlias(types.RegistryName(regName), key, aliasReq.Value) - alias, err := h.alias.CreateAlias(r.Context(), eAlias.RegistryName, eAlias) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, err) - return - } - - resp := types.AliasResponse{ - Value: types.AliasValue(alias.Value), - } - err = infrahttp.WriteJSON(w, resp) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, err) - return - } -} - -// @Summary Get an alias -// @Description Get an alias of a key from a dedicated alias registry -// @Tags Aliases -// @Produce json -// @Param registry_name path string true "registry identifier" -// @Param alias_key path string true "alias identifier" -// @Success 200 {object} types.AliasResponse "Alias data" -// @Failure 400 {object} ErrorResponse "Invalid request format" -// @Failure 404 {object} ErrorResponse "Alias not found" -// @Failure 500 {object} ErrorResponse "Internal server error" -// @Router /registries/{registry_name}/aliases/{alias_key} [get] -func (h *AliasHandler) getAlias(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - // should always exist in this subrouter - regName := vars["registry_name"] - key := vars["alias_key"] - - err := validatePathVars(regName, key) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, errors.InvalidFormatError(err.Error())) - return - } - - alias, err := h.alias.GetAlias(r.Context(), aliasent.RegistryName(regName), aliasent.AliasKey(key)) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, err) - return - } - - err = infrahttp.WriteJSON(w, types.AliasResponse{ - Value: types.AliasValue(alias.Value), - }) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, err) - return - } -} - -// updateAlias updates an alias value. -// @Summary Update an alias -// @Description Update an alias of a key from a dedicated alias registry -// @Tags Aliases -// @Accept json -// @Produce json -// @Param registry_name path string true "registry identifier" -// @Param alias_key path string true "alias identifier" -// @Param request body types.AliasRequest true "Update Alias Request" -// @Success 200 {object} types.AliasResponse "Alias data" -// @Failure 400 {object} ErrorResponse "Invalid request format" -// @Failure 404 {object} ErrorResponse "Alias not found" -// @Failure 500 {object} ErrorResponse "Internal server error" -// @Router /registries/{registry_name}/aliases/{alias_key} [put] -func (h *AliasHandler) updateAlias(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - // should always exist in this subrouter - regName := vars["registry_name"] - key := vars["alias_key"] - - err := validatePathVars(regName, key) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, errors.InvalidFormatError(err.Error())) - return - } - - var aliasReq types.AliasRequest - err = jsonutils.UnmarshalBody(r.Body, &aliasReq) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, errors.InvalidFormatError(err.Error())) - return - } - - alias := &aliasent.Alias{ - RegistryName: aliasent.RegistryName(regName), - Key: aliasent.AliasKey(key), - Value: aliasent.AliasValue(aliasReq.Value), - } - - alias, err = h.alias.UpdateAlias(r.Context(), aliasent.RegistryName(regName), *alias) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, err) - return - } - - err = infrahttp.WriteJSON(w, types.AliasResponse{ - Value: types.AliasValue(alias.Value), - }) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, err) - return - } -} - -// deleteAlias deletes an alias value. -// @Summary Delete an alias -// @Description Delete an alias of a key from a dedicated alias registry -// @Tags Aliases -// @Param registry_name path string true "registry identifier" -// @Param alias_key path string true "alias identifier" -// @Success 204 "Deleted successfully" -// @Failure 400 {object} ErrorResponse "Invalid request format" -// @Failure 404 {object} ErrorResponse "Alias not found" -// @Failure 500 {object} ErrorResponse "Internal server error" -// @Router /registries/{registry_name}/aliases/{alias_key} [delete] -func (h *AliasHandler) deleteAlias(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - // should always exist in this subrouter - regName := vars["registry_name"] - key := vars["alias_key"] - - err := validatePathVars(regName, key) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, errors.InvalidFormatError(err.Error())) - return - } - - err = h.alias.DeleteAlias(r.Context(), aliasent.RegistryName(regName), aliasent.AliasKey(key)) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, err) - return - } - - w.Header().Set("X-Content-Type-Options", "nosniff") - w.WriteHeader(http.StatusNoContent) -} - -// @Summary Get all the aliases in a registry -// @Description Get all the aliases in a registry -// @Tags Aliases -// @Produce json -// @Param registry_name path string true "registry identifier" -// @Param alias_key path string true "alias identifier" -// @Success 200 {array} types.Alias "a list of Aliases" -// @Failure 400 {object} ErrorResponse "Invalid request format" -// @Failure 500 {object} ErrorResponse "Internal server error" -// @Router /registries/{registry_name}/aliases [get] -func (h *AliasHandler) listAliases(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - // should always exist in this subrouter - regName := vars["registry_name"] - - err := validatePathVars(regName) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, errors.InvalidFormatError(err.Error())) - return - } - - als, err := h.alias.ListAliases(r.Context(), aliasent.RegistryName(regName)) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, err) - return - } - - err = infrahttp.WriteJSON(w, types.FormatEntityAliases(als)) - if err != nil { - infrahttp.WriteHTTPErrorResponse(w, err) - return - } -} - -var pathVarsRegexCompileOnce sync.Once -var pathVarsRegex *regexp.Regexp - -const pathVarsFormat = "^[a-zA-Z0-9-_+]+$" - -func validatePathVars(pathVars ...string) error { - var err error - pathVarsRegexCompileOnce.Do(func() { - pathVarsRegex, err = regexp.Compile(pathVarsFormat) - }) - if err != nil { - return err - } - - for _, v := range pathVars { - if !pathVarsRegex.MatchString(v) { - return fmt.Errorf("`%v` in path is not in the correct format: %v", v, pathVarsFormat) - } - } - return nil -} diff --git a/src/aliases/api/handlers/handlers_test.go b/src/aliases/api/handlers/handlers_test.go deleted file mode 100644 index fde466571..000000000 --- a/src/aliases/api/handlers/handlers_test.go +++ /dev/null @@ -1,443 +0,0 @@ -package handlers_test - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/golang/mock/gomock" - "github.com/gorilla/mux" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/consensys/quorum-key-manager/pkg/errors" - aliasapi "github.com/consensys/quorum-key-manager/src/aliases/api" - "github.com/consensys/quorum-key-manager/src/aliases/api/types" - aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" - "github.com/consensys/quorum-key-manager/src/aliases/entities/mock" -) - -type apiHelper struct { - ctx context.Context - mock *mock.MockAliasBackend - rec *httptest.ResponseRecorder - router *mux.Router - handler *aliasapi.AliasAPI -} - -func newAPIHelper(t *testing.T) *apiHelper { - ctrl := gomock.NewController(t) - store := mock.NewMockAliasBackend(ctrl) - handler := aliasapi.New(store) - router := mux.NewRouter() - handler.Register(router) - - return &apiHelper{ - ctx: context.Background(), - mock: store, - rec: httptest.NewRecorder(), - router: router, - handler: handler, - } -} - -const nonExistingKey = "non_existing_key" - -type Case struct { - reg string - key string - value string - - status int -} - -func defaultCase() Case { - return Case{"my-registry", "group-A", `[ “ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc=”, ”2T7xkjblN568N1QmPeElTjoeoNT4tkWYOJYxSMDO5i0=” ]`, http.StatusOK} -} - -func TestCreateAlias(t *testing.T) { - t.Run("one element", func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - c := defaultCase() - req := types.AliasRequest{ - Value: types.AliasValue(c.value), - } - var b bytes.Buffer - err := json.NewEncoder(&b).Encode(req) - require.NoError(t, err) - - ent := newEntAlias(c.reg, c.key, c.value) - helper.mock.EXPECT().CreateAlias(gomock.Any(), ent.RegistryName, ent).Return(&ent, nil) - - path := fmt.Sprintf("/registries/%s/aliases/%s", c.reg, c.key) - r, err := newJSONRequest(helper.ctx, "POST", path, &b) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, c.status, helper.rec.Code) - res, err := ioutil.ReadAll(helper.rec.Body) - require.NoError(t, err) - - var resp types.AliasResponse - err = json.Unmarshal(res, &resp) - require.NoError(t, err) - - assert.Equal(t, types.AliasResponse{Value: types.AliasValue(c.value)}, resp) - }) - - t.Run("already existing alias", func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - c := defaultCase() - c.key = "existing_key" - c.status = http.StatusConflict - - req := types.AliasRequest{ - Value: types.AliasValue(c.value), - } - var b bytes.Buffer - err := json.NewEncoder(&b).Encode(req) - require.NoError(t, err) - - ent := newEntAlias(c.reg, c.key, c.value) - helper.mock.EXPECT().CreateAlias(gomock.Any(), ent.RegistryName, ent).Return(nil, errors.AlreadyExistsError("")) - - path := fmt.Sprintf("/registries/%s/aliases/%s", c.reg, c.key) - r, err := newJSONRequest(helper.ctx, "POST", path, &b) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, c.status, helper.rec.Code) - res, err := ioutil.ReadAll(helper.rec.Body) - require.NoError(t, err) - assert.Contains(t, string(res), `"code":"ST200"`) - }) - -} - -func TestUpdateAlias(t *testing.T) { - t.Run("one element", func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - - c := defaultCase() - req := types.AliasRequest{ - Value: types.AliasValue(c.value), - } - var b bytes.Buffer - err := json.NewEncoder(&b).Encode(req) - require.NoError(t, err) - - ent := newEntAlias(c.reg, c.key, c.value) - helper.mock.EXPECT().UpdateAlias(gomock.Any(), ent.RegistryName, ent).Return(&ent, nil) - - path := fmt.Sprintf("/registries/%s/aliases/%s", c.reg, c.key) - r, err := newJSONRequest(helper.ctx, "PUT", path, &b) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, helper.rec.Code, c.status) - res, err := ioutil.ReadAll(helper.rec.Body) - require.NoError(t, err) - - var resp types.AliasResponse - err = json.Unmarshal(res, &resp) - require.NoError(t, err) - - assert.Equal(t, types.AliasResponse{ - Value: types.AliasValue(c.value), - }, - resp) - }) - - t.Run("non-existing alias", func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - - c := defaultCase() - c.key = nonExistingKey - c.status = http.StatusNotFound - alias := types.AliasRequest{ - Value: types.AliasValue(c.value), - } - var b bytes.Buffer - err := json.NewEncoder(&b).Encode(alias) - require.NoError(t, err) - - ent := newEntAlias(c.reg, c.key, c.value) - helper.mock.EXPECT().UpdateAlias(gomock.Any(), ent.RegistryName, ent).Return(nil, errors.NotFoundError("")) - - path := fmt.Sprintf("/registries/%s/aliases/%s", c.reg, c.key) - r, err := newJSONRequest(helper.ctx, "PUT", path, &b) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, c.status, helper.rec.Code) - res, err := ioutil.ReadAll(helper.rec.Body) - require.NoError(t, err) - assert.Contains(t, string(res), errors.NotFound) - }) -} - -func TestGetAlias(t *testing.T) { - t.Run("one element", func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - - c := defaultCase() - ent := newEntAlias(c.reg, c.key, c.value) - helper.mock.EXPECT().GetAlias(gomock.Any(), ent.RegistryName, ent.Key).Return(&ent, nil) - - path := fmt.Sprintf("/registries/%s/aliases/%s", c.reg, c.key) - r, err := newJSONRequest(helper.ctx, "GET", path, nil) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, c.status, helper.rec.Code) - res, err := ioutil.ReadAll(helper.rec.Body) - require.NoError(t, err) - - var resp types.AliasResponse - err = json.Unmarshal(res, &resp) - require.NoError(t, err) - - assert.Equal(t, types.AliasResponse{ - Value: types.AliasValue(c.value), - }, resp) - - }) - - t.Run("non-existing alias", func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - - c := defaultCase() - c.key = nonExistingKey - c.status = http.StatusNotFound - ent := newEntAlias(c.reg, c.key, "") - helper.mock.EXPECT().GetAlias(gomock.Any(), ent.RegistryName, ent.Key).Return(nil, errors.NotFoundError("")) - - path := fmt.Sprintf("/registries/%s/aliases/%s", c.reg, c.key) - r, err := newJSONRequest(helper.ctx, "GET", path, nil) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, c.status, helper.rec.Code) - res, err := ioutil.ReadAll(helper.rec.Body) - require.NoError(t, err) - assert.Contains(t, string(res), errors.NotFound) - }) -} - -func TestDeleteAlias(t *testing.T) { - t.Run("one element", func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - - c := defaultCase() - c.status = http.StatusNoContent - ent := newEntAlias(c.reg, c.key, c.value) - helper.mock.EXPECT().DeleteAlias(gomock.Any(), ent.RegistryName, ent.Key).Return(nil) - - path := fmt.Sprintf("/registries/%s/aliases/%s", c.reg, c.key) - r, err := newJSONRequest(helper.ctx, "DELETE", path, nil) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, helper.rec.Code, c.status) - }) - t.Run("non-existing alias", func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - - c := defaultCase() - c.key = nonExistingKey - c.status = http.StatusNotFound - ent := newEntAlias(c.reg, c.key, "") - helper.mock.EXPECT().DeleteAlias(gomock.Any(), ent.RegistryName, ent.Key).Return(errors.NotFoundError("")) - - path := fmt.Sprintf("/registries/%s/aliases/%s", c.reg, c.key) - r, err := newJSONRequest(helper.ctx, "DELETE", path, nil) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, c.status, helper.rec.Code) - res, err := ioutil.ReadAll(helper.rec.Body) - require.NoError(t, err) - assert.Contains(t, string(res), errors.NotFound) - }) -} - -func TestListAliases(t *testing.T) { - t.Run("non-existing registry", func(t *testing.T) { - t.Parallel() - - helper := newAPIHelper(t) - - c := defaultCase() - c.reg = "non_existing_registry" - c.status = http.StatusNotFound - helper.mock.EXPECT().ListAliases(gomock.Any(), aliasent.RegistryName(c.reg)).Return(nil, errors.NotFoundError("")) - - path := fmt.Sprintf("/registries/%s/aliases", c.reg) - r, err := newJSONRequest(helper.ctx, "GET", path, nil) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, helper.rec.Code, c.status) - res, err := ioutil.ReadAll(helper.rec.Body) - require.NoError(t, err) - assert.Contains(t, string(res), errors.NotFound) - }) - - t.Run("empty list", func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - - c := defaultCase() - var ents []aliasent.Alias - helper.mock.EXPECT().ListAliases(gomock.Any(), aliasent.RegistryName(c.reg)).Return(ents, nil) - - path := fmt.Sprintf("/registries/%s/aliases", c.reg) - r, err := newJSONRequest(helper.ctx, "GET", path, nil) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, helper.rec.Code, c.status) - - var als []types.Alias - err = json.Unmarshal(helper.rec.Body.Bytes(), &als) - require.NoError(t, err) - - alses := types.FormatEntityAliases(ents) - assert.Equal(t, als, alses) - - }) - - t.Run("list of 2 elements", func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - - c := defaultCase() - ents := []aliasent.Alias{ - { - Key: "JPM", - Value: `[ "ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc=" ]`, - }, - { - Key: "GS", - Value: `[ "2T7xkjblN568N1QmPeElTjoeoNT4tkWYOJYxSMDO5i0=" ]`, - }, - } - helper.mock.EXPECT().ListAliases(gomock.Any(), aliasent.RegistryName(c.reg)).Return(ents, nil) - - path := fmt.Sprintf("/registries/%s/aliases", c.reg) - r, err := newJSONRequest(helper.ctx, "GET", path, nil) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, c.status, helper.rec.Code) - - var als []types.Alias - err = json.Unmarshal(helper.rec.Body.Bytes(), &als) - require.NoError(t, err) - assert.Equal(t, als, types.FormatEntityAliases(ents)) - }) -} - -func TestPathValidate(t *testing.T) { - cases := []struct { - path string - }{ - {"/registries/bad*registry/aliases/ok-key"}, - {"/registries/ok_registry/aliases/bad@key"}, - } - - requests := []struct { - method string - input string - }{ - {"GET", ``}, - {"POST", `{"value": "[ \"ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc=\" ]"}`}, - {"PUT", `{"value": "[ \"XOAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc=\" ]"}`}, - {"DELETE", ``}, - } - - for _, c := range cases { - for _, r := range requests { - t.Run(fmt.Sprintf("%s %s", r.method, c.path), func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - - input := strings.NewReader(r.input) - - r, err := newJSONRequest(helper.ctx, r.method, c.path, input) - require.NoError(t, err) - - helper.router.ServeHTTP(helper.rec, r) - assert.Equal(t, http.StatusBadRequest, helper.rec.Result().StatusCode) - }) - } - } -} - -func TestJSONHeader(t *testing.T) { - cases := []struct { - method string - path string - input string - }{ - {"POST", "/registries/1/aliases", `{"key": "1", "value": "[ \"0123\" ]"}`}, - {"GET", "/registries/1/aliases", ``}, - {"GET", "/registries/1/aliases/1", ``}, - {"PUT", "/registries/1/aliases/1", `{"key": "1", "value": "[ \"01234\" ]"}`}, - // DELETE doesn't return any content, only 204 or 404 - } - - for _, c := range cases { - t.Run(fmt.Sprintf("%s %s", c.method, c.path), func(t *testing.T) { - t.Parallel() - helper := newAPIHelper(t) - - input := strings.NewReader(c.input) - - r, err := newJSONRequest(helper.ctx, c.method, c.path, input) - require.NoError(t, err) - - ent := newEntAlias("1", "1", `[ \"0123\" ]`) - // accept any call just to make the test work - helper.mock.EXPECT().CreateAlias(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(&ent, nil) - helper.mock.EXPECT().GetAlias(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(&ent, nil) - helper.mock.EXPECT().UpdateAlias(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(&ent, nil) - helper.mock.EXPECT().ListAliases(gomock.Any(), gomock.Any()).AnyTimes().Return([]aliasent.Alias{ent}, nil) - - helper.router.ServeHTTP(helper.rec, r) - assert.Contains(t, helper.rec.Result().Header.Values("Content-Type"), "application/json") - }) - } -} - -func newEntAlias(registry, key, value string) aliasent.Alias { - return aliasent.Alias{ - RegistryName: aliasent.RegistryName(registry), - Key: aliasent.AliasKey(key), - Value: aliasent.AliasValue(value), - } -} - -func newJSONRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { - r, err := http.NewRequestWithContext(ctx, method, path, body) - if err != nil { - return nil, err - } - r.Header["Content-Type"] = []string{"application/json"} - return r, nil -} diff --git a/src/aliases/api/types/alias.go b/src/aliases/api/types/alias.go deleted file mode 100644 index ba9316a86..000000000 --- a/src/aliases/api/types/alias.go +++ /dev/null @@ -1,49 +0,0 @@ -package types - -import aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" - -type Alias struct { - Key AliasKey `json:"key"` - Value AliasValue `json:"value"` - - registryName RegistryName -} - -func FormatEntityAlias(ent aliasent.Alias) Alias { - return Alias{ - registryName: RegistryName(ent.RegistryName), - Key: AliasKey(ent.Key), - Value: AliasValue(ent.Value), - } -} - -func FormatAlias(registry RegistryName, key string, value AliasValue) aliasent.Alias { - return aliasent.Alias{ - RegistryName: aliasent.RegistryName(registry), - Key: aliasent.AliasKey(key), - Value: aliasent.AliasValue(value), - } -} - -func FormatEntityAliases(ents []aliasent.Alias) []Alias { - var als = []Alias{} - for _, v := range ents { - als = append(als, FormatEntityAlias(v)) - } - - return als -} - -type AliasValue string - -type AliasKey string - -type RegistryName string - -type AliasRequest struct { - Value AliasValue `json:"value"` -} - -type AliasResponse struct { - Value AliasValue `json:"value"` -} diff --git a/src/aliases/config.go b/src/aliases/config.go deleted file mode 100644 index db303ac43..000000000 --- a/src/aliases/config.go +++ /dev/null @@ -1,9 +0,0 @@ -package aliases - -import ( - pg "github.com/consensys/quorum-key-manager/src/infra/postgres/client" -) - -type Config struct { - Postgres *pg.Config -} diff --git a/src/aliases/entities/alias.go b/src/aliases/entities/alias.go deleted file mode 100644 index ce2f3f651..000000000 --- a/src/aliases/entities/alias.go +++ /dev/null @@ -1,18 +0,0 @@ -package aliasent - -// Alias allows the user to associates a RegistryName + a Key to 1 or more public keys stored -// in Value. The Value has 2 formats: -// - a JSON string if AliasKind is an AliasKindString. -// - a JSON array of strings if AliasKind is an AliasKindArray. -type Alias struct { - Key AliasKey - RegistryName RegistryName - // Value is a JSON array containing Tessera/Orion keys base64 encoded in strings. - Value AliasValue -} - -type AliasKey string - -type AliasValue string - -type RegistryName string diff --git a/src/aliases/entities/backend.go b/src/aliases/entities/backend.go deleted file mode 100644 index 6ddb4889c..000000000 --- a/src/aliases/entities/backend.go +++ /dev/null @@ -1,25 +0,0 @@ -package aliasent - -import ( - "context" -) - -//go:generate mockgen -source=backend.go -destination=mock/backend.go -package=mock - -// Alias handles the aliases. -type AliasBackend interface { - // CreateAlias creates an alias in the registry. - CreateAlias(ctx context.Context, registry RegistryName, alias Alias) (*Alias, error) - // GetAlias gets an alias from the registry. - GetAlias(ctx context.Context, registry RegistryName, aliasKey AliasKey) (*Alias, error) - // UpdateAlias updates an alias in the registry. - UpdateAlias(ctx context.Context, registry RegistryName, alias Alias) (*Alias, error) - // GetAlias deletes an alias from the registry. - DeleteAlias(ctx context.Context, registry RegistryName, aliasKey AliasKey) error - - // ListAlias lists all aliases from a registry. - ListAliases(ctx context.Context, registry RegistryName) ([]Alias, error) - - // DeleteRegistry deletes a registry, with all the aliases it contained. - DeleteRegistry(ctx context.Context, registry RegistryName) error -} diff --git a/src/aliases/entities/mock/backend.go b/src/aliases/entities/mock/backend.go deleted file mode 100644 index b059a2981..000000000 --- a/src/aliases/entities/mock/backend.go +++ /dev/null @@ -1,124 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: backend.go - -// Package mock is a generated GoMock package. -package mock - -import ( - context "context" - reflect "reflect" - - aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" - gomock "github.com/golang/mock/gomock" -) - -// MockAliasBackend is a mock of AliasBackend interface. -type MockAliasBackend struct { - ctrl *gomock.Controller - recorder *MockAliasBackendMockRecorder -} - -// MockAliasBackendMockRecorder is the mock recorder for MockAliasBackend. -type MockAliasBackendMockRecorder struct { - mock *MockAliasBackend -} - -// NewMockAliasBackend creates a new mock instance. -func NewMockAliasBackend(ctrl *gomock.Controller) *MockAliasBackend { - mock := &MockAliasBackend{ctrl: ctrl} - mock.recorder = &MockAliasBackendMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAliasBackend) EXPECT() *MockAliasBackendMockRecorder { - return m.recorder -} - -// CreateAlias mocks base method. -func (m *MockAliasBackend) CreateAlias(ctx context.Context, registry aliasent.RegistryName, alias aliasent.Alias) (*aliasent.Alias, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateAlias", ctx, registry, alias) - ret0, _ := ret[0].(*aliasent.Alias) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateAlias indicates an expected call of CreateAlias. -func (mr *MockAliasBackendMockRecorder) CreateAlias(ctx, registry, alias interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateAlias", reflect.TypeOf((*MockAliasBackend)(nil).CreateAlias), ctx, registry, alias) -} - -// DeleteAlias mocks base method. -func (m *MockAliasBackend) DeleteAlias(ctx context.Context, registry aliasent.RegistryName, aliasKey aliasent.AliasKey) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteAlias", ctx, registry, aliasKey) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteAlias indicates an expected call of DeleteAlias. -func (mr *MockAliasBackendMockRecorder) DeleteAlias(ctx, registry, aliasKey interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAlias", reflect.TypeOf((*MockAliasBackend)(nil).DeleteAlias), ctx, registry, aliasKey) -} - -// DeleteRegistry mocks base method. -func (m *MockAliasBackend) DeleteRegistry(ctx context.Context, registry aliasent.RegistryName) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteRegistry", ctx, registry) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteRegistry indicates an expected call of DeleteRegistry. -func (mr *MockAliasBackendMockRecorder) DeleteRegistry(ctx, registry interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteRegistry", reflect.TypeOf((*MockAliasBackend)(nil).DeleteRegistry), ctx, registry) -} - -// GetAlias mocks base method. -func (m *MockAliasBackend) GetAlias(ctx context.Context, registry aliasent.RegistryName, aliasKey aliasent.AliasKey) (*aliasent.Alias, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAlias", ctx, registry, aliasKey) - ret0, _ := ret[0].(*aliasent.Alias) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAlias indicates an expected call of GetAlias. -func (mr *MockAliasBackendMockRecorder) GetAlias(ctx, registry, aliasKey interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAlias", reflect.TypeOf((*MockAliasBackend)(nil).GetAlias), ctx, registry, aliasKey) -} - -// ListAliases mocks base method. -func (m *MockAliasBackend) ListAliases(ctx context.Context, registry aliasent.RegistryName) ([]aliasent.Alias, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListAliases", ctx, registry) - ret0, _ := ret[0].([]aliasent.Alias) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListAliases indicates an expected call of ListAliases. -func (mr *MockAliasBackendMockRecorder) ListAliases(ctx, registry interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListAliases", reflect.TypeOf((*MockAliasBackend)(nil).ListAliases), ctx, registry) -} - -// UpdateAlias mocks base method. -func (m *MockAliasBackend) UpdateAlias(ctx context.Context, registry aliasent.RegistryName, alias aliasent.Alias) (*aliasent.Alias, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateAlias", ctx, registry, alias) - ret0, _ := ret[0].(*aliasent.Alias) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateAlias indicates an expected call of UpdateAlias. -func (mr *MockAliasBackendMockRecorder) UpdateAlias(ctx, registry, alias interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAlias", reflect.TypeOf((*MockAliasBackend)(nil).UpdateAlias), ctx, registry, alias) -} diff --git a/src/aliases/service.go b/src/aliases/service.go deleted file mode 100644 index e90a26872..000000000 --- a/src/aliases/service.go +++ /dev/null @@ -1,30 +0,0 @@ -package aliases - -import ( - "github.com/consensys/quorum-key-manager/pkg/app" - aliasapi "github.com/consensys/quorum-key-manager/src/aliases/api" - aliaspg "github.com/consensys/quorum-key-manager/src/aliases/store/postgres" - "github.com/consensys/quorum-key-manager/src/infra/log" - "github.com/consensys/quorum-key-manager/src/infra/postgres/client" -) - -// RegisterService creates and register the alias service in the app. -func RegisterService(a *app.App, logger log.Logger) error { - var cfg Config - err := a.ServiceConfig(&cfg) - if err != nil { - return err - } - - pgClient, err := client.NewClient(cfg.Postgres) - if err != nil { - return err - } - - db := aliaspg.NewDatabase(pgClient) - - api := aliasapi.New(db.Alias()) - api.Register(a.Router()) - - return nil -} diff --git a/src/aliases/store/database.go b/src/aliases/store/database.go deleted file mode 100644 index 30e7e4511..000000000 --- a/src/aliases/store/database.go +++ /dev/null @@ -1,11 +0,0 @@ -package aliasstore - -import ( - aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" -) - -//go:generate mockgen -source=database.go -destination=mock/database.go -package=mock - -type Database interface { - Alias() aliasent.AliasBackend -} diff --git a/src/aliases/store/mock/database.go b/src/aliases/store/mock/database.go deleted file mode 100644 index 44d26463b..000000000 --- a/src/aliases/store/mock/database.go +++ /dev/null @@ -1,49 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: database.go - -// Package mock is a generated GoMock package. -package mock - -import ( - reflect "reflect" - - aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" - gomock "github.com/golang/mock/gomock" -) - -// MockDatabase is a mock of Database interface. -type MockDatabase struct { - ctrl *gomock.Controller - recorder *MockDatabaseMockRecorder -} - -// MockDatabaseMockRecorder is the mock recorder for MockDatabase. -type MockDatabaseMockRecorder struct { - mock *MockDatabase -} - -// NewMockDatabase creates a new mock instance. -func NewMockDatabase(ctrl *gomock.Controller) *MockDatabase { - mock := &MockDatabase{ctrl: ctrl} - mock.recorder = &MockDatabaseMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockDatabase) EXPECT() *MockDatabaseMockRecorder { - return m.recorder -} - -// Alias mocks base method. -func (m *MockDatabase) Alias() aliasent.AliasBackend { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Alias") - ret0, _ := ret[0].(aliasent.AliasBackend) - return ret0 -} - -// Alias indicates an expected call of Alias. -func (mr *MockDatabaseMockRecorder) Alias() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Alias", reflect.TypeOf((*MockDatabase)(nil).Alias)) -} diff --git a/src/aliases/store/models/alias.go b/src/aliases/store/models/alias.go deleted file mode 100644 index 52d66c711..000000000 --- a/src/aliases/store/models/alias.go +++ /dev/null @@ -1,47 +0,0 @@ -package aliasmodels - -import aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" - -// Alias allows the user to associates a RegistryName + a Key to 1 or more public keys stored -// in Value. The Value has 2 formats: -// - a JSON string if AliasKind is an AliasKindString. -// - a JSON array of strings if AliasKind is an AliasKindArray. -type Alias struct { - tableName struct{} `pg:"aliases"` // nolint:unused,structcheck // reason - - Key AliasKey `pg:",pk"` - RegistryName RegistryName `pg:",pk"` - // Value is a JSON array containing Tessera/Orion keys base64 encoded in strings. - Value AliasValue -} - -func AliasFromEntity(ent aliasent.Alias) Alias { - return Alias{ - Key: AliasKey(ent.Key), - RegistryName: RegistryName(ent.RegistryName), - Value: AliasValue(ent.Value), - } -} - -func (a *Alias) ToEntity() *aliasent.Alias { - return &aliasent.Alias{ - Key: aliasent.AliasKey(a.Key), - RegistryName: aliasent.RegistryName(a.RegistryName), - Value: aliasent.AliasValue(a.Value), - } -} - -func AliasesToEntity(aliases []Alias) []aliasent.Alias { - var ents []aliasent.Alias - for _, v := range aliases { - ent := v.ToEntity() - ents = append(ents, *ent) - } - return ents -} - -type AliasKey string - -type AliasValue string - -type RegistryName string diff --git a/src/aliases/store/postgres/alias.go b/src/aliases/store/postgres/alias.go deleted file mode 100644 index f61f42b6c..000000000 --- a/src/aliases/store/postgres/alias.go +++ /dev/null @@ -1,76 +0,0 @@ -package aliaspg - -import ( - "context" - - "github.com/consensys/quorum-key-manager/pkg/errors" - aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" - aliasmodels "github.com/consensys/quorum-key-manager/src/aliases/store/models" - "github.com/consensys/quorum-key-manager/src/infra/postgres" -) - -var _ aliasent.AliasBackend = &AliasStore{} - -// AliasStore stores the alias data in a postgres DB. -type AliasStore struct { - pgClient postgres.Client -} - -func NewAlias(pgClient postgres.Client) *AliasStore { - return &AliasStore{ - pgClient: pgClient, - } -} - -func (s *AliasStore) CreateAlias(ctx context.Context, registry aliasent.RegistryName, alias aliasent.Alias) (*aliasent.Alias, error) { - a := aliasmodels.AliasFromEntity(alias) - a.RegistryName = aliasmodels.RegistryName(registry) - - err := s.pgClient.Insert(ctx, &a) - if err != nil { - return nil, err - } - return &alias, nil -} - -func (s *AliasStore) GetAlias(ctx context.Context, registry aliasent.RegistryName, aliasKey aliasent.AliasKey) (*aliasent.Alias, error) { - a := aliasmodels.Alias{ - Key: aliasmodels.AliasKey(aliasKey), - RegistryName: aliasmodels.RegistryName(registry), - } - err := s.pgClient.SelectPK(ctx, &a) - return a.ToEntity(), err -} - -func (s *AliasStore) UpdateAlias(ctx context.Context, registry aliasent.RegistryName, alias aliasent.Alias) (*aliasent.Alias, error) { - a := aliasmodels.AliasFromEntity(alias) - a.RegistryName = aliasmodels.RegistryName(registry) - - err := s.pgClient.UpdatePK(ctx, &a) - return a.ToEntity(), err -} - -func (s *AliasStore) DeleteAlias(ctx context.Context, registry aliasent.RegistryName, aliasKey aliasent.AliasKey) error { - a := aliasmodels.Alias{ - Key: aliasmodels.AliasKey(aliasKey), - RegistryName: aliasmodels.RegistryName(registry), - } - return s.pgClient.DeletePK(ctx, &a) -} - -func (s *AliasStore) ListAliases(ctx context.Context, registry aliasent.RegistryName) ([]aliasent.Alias, error) { - reg := aliasmodels.RegistryName(registry) - - var als []aliasmodels.Alias - err := s.pgClient.SelectWhere(ctx, &als, "alias.registry_name = ?", reg) - if err != nil { - return nil, err - } - - ents := aliasmodels.AliasesToEntity(als) - return ents, err -} - -func (s *AliasStore) DeleteRegistry(ctx context.Context, registry aliasent.RegistryName) error { - return errors.NotImplementedError("DeleteRegistry not implemented") -} diff --git a/src/aliases/store/postgres/database.go b/src/aliases/store/postgres/database.go deleted file mode 100644 index af7108e8c..000000000 --- a/src/aliases/store/postgres/database.go +++ /dev/null @@ -1,20 +0,0 @@ -package aliaspg - -import ( - aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" - "github.com/consensys/quorum-key-manager/src/infra/postgres" -) - -type Database struct { - alias *AliasStore -} - -func NewDatabase(pgClient postgres.Client) *Database { - return &Database{ - alias: NewAlias(pgClient), - } -} - -func (db *Database) Alias() aliasent.AliasBackend { - return db.alias -} diff --git a/src/app.go b/src/app.go index f3dfc7798..d1629c271 100644 --- a/src/app.go +++ b/src/app.go @@ -4,7 +4,6 @@ import ( "github.com/consensys/quorum-key-manager/pkg/app" "github.com/consensys/quorum-key-manager/pkg/http/middleware" "github.com/consensys/quorum-key-manager/pkg/http/server" - "github.com/consensys/quorum-key-manager/src/aliases" "github.com/consensys/quorum-key-manager/src/auth" "github.com/consensys/quorum-key-manager/src/infra/log" "github.com/consensys/quorum-key-manager/src/infra/postgres/client" @@ -77,15 +76,5 @@ func New(cfg *Config, logger log.Logger) (*app.App, error) { return nil, err } - err = a.RegisterServiceConfig(&aliases.Config{Postgres: cfg.Postgres}) - if err != nil { - return nil, err - } - - err = aliases.RegisterService(a, logger.WithComponent("aliases")) - if err != nil { - return nil, err - } - return a, nil } diff --git a/tests/acceptance/alias_store.go b/tests/acceptance/alias_store.go deleted file mode 100644 index 082d49c49..000000000 --- a/tests/acceptance/alias_store.go +++ /dev/null @@ -1,134 +0,0 @@ -// +build acceptance - -package acceptancetests - -import ( - "math/rand" - "strconv" - - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" - - aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" -) - -type aliasStoreTestSuite struct { - suite.Suite - env *IntegrationEnvironment - srv aliasent.AliasBackend - rand *rand.Rand -} - -func (s *aliasStoreTestSuite) fakeAlias() aliasent.Alias { - randInt := s.rand.Intn(1 << 32) - randID := strconv.Itoa(randInt) - return aliasent.Alias{ - RegistryName: aliasent.RegistryName("JPM-" + randID), - Key: aliasent.AliasKey("Goldman Sachs-" + randID), - Value: `["ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc=","2T7xkjblN568N1QmPeElTjoeoNT4tkWYOJYxSMDO5i0="]`, - } -} - -func (s *aliasStoreTestSuite) TestCreateAlias() { - s.Run("should create an unique alias without error", func() { - in := s.fakeAlias() - out, err := s.srv.CreateAlias(s.env.ctx, in.RegistryName, in) - require.NoError(s.T(), err) - require.Equal(s.T(), in, *out) - }) -} - -func (s *aliasStoreTestSuite) TestGetAlias() { - s.Run("non existing alias", func() { - in := s.fakeAlias() - _, err := s.srv.GetAlias(s.env.ctx, in.RegistryName, in.Key) - require.Error(s.T(), err) - }) - - s.Run("just created alias", func() { - in := s.fakeAlias() - out, err := s.srv.CreateAlias(s.env.ctx, in.RegistryName, in) - require.NoError(s.T(), err) - require.Equal(s.T(), in, *out) - - got, err := s.srv.GetAlias(s.env.ctx, in.RegistryName, in.Key) - require.NoError(s.T(), err) - require.Equal(s.T(), &in, got) - }) -} - -func (s *aliasStoreTestSuite) TestUpdateAlias() { - s.Run("non existing alias", func() { - in := s.fakeAlias() - _, err := s.srv.UpdateAlias(s.env.ctx, in.RegistryName, in) - require.Error(s.T(), err) - }) - - s.Run("just created alias", func() { - in := s.fakeAlias() - out, err := s.srv.CreateAlias(s.env.ctx, in.RegistryName, in) - require.NoError(s.T(), err) - require.Equal(s.T(), in, *out) - - updated := in - updated.Value = `["SOAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc=","3T7xkjblN568N1QmPeElTjoeoNT4tkWYOJYxSMDO5i0="]` - - out, err = s.srv.UpdateAlias(s.env.ctx, in.RegistryName, updated) - require.NoError(s.T(), err) - - got, err := s.srv.GetAlias(s.env.ctx, in.RegistryName, in.Key) - require.NoError(s.T(), err) - require.Equal(s.T(), &updated, got) - }) -} - -func (s *aliasStoreTestSuite) TestDeleteAlias() { - s.Run("non existing alias", func() { - in := s.fakeAlias() - err := s.srv.DeleteAlias(s.env.ctx, in.RegistryName, in.Key) - require.Error(s.T(), err) - }) - - s.Run("just created alias", func() { - in := s.fakeAlias() - out, err := s.srv.CreateAlias(s.env.ctx, in.RegistryName, in) - require.NoError(s.T(), err) - require.Equal(s.T(), in, *out) - - err = s.srv.DeleteAlias(s.env.ctx, in.RegistryName, in.Key) - require.NoError(s.T(), err) - - _, err = s.srv.GetAlias(s.env.ctx, in.RegistryName, in.Key) - require.Error(s.T(), err) - }) -} - -func (s *aliasStoreTestSuite) TestListAlias() { - s.Run("non existing alias", func() { - in := s.fakeAlias() - als, err := s.srv.ListAliases(s.env.ctx, in.RegistryName) - require.NoError(s.T(), err) - require.Len(s.T(), als, 0) - }) - - s.Run("just created alias", func() { - in := s.fakeAlias() - out, err := s.srv.CreateAlias(s.env.ctx, in.RegistryName, in) - require.NoError(s.T(), err) - require.Equal(s.T(), in, *out) - - newAlias := in - newAlias.Key = `Crédit Mutuel` - newAlias.Value = `[ SOAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc= ]` - out, err = s.srv.CreateAlias(s.env.ctx, in.RegistryName, newAlias) - require.NoError(s.T(), err) - require.Equal(s.T(), newAlias, *out) - - als, err := s.srv.ListAliases(s.env.ctx, in.RegistryName) - require.NoError(s.T(), err) - require.NotEmpty(s.T(), als) - require.Len(s.T(), als, 2) - require.Equal(s.T(), als[0].Key, in.Key) - require.Equal(s.T(), als[1].Key, newAlias.Key) - }) -} diff --git a/tests/acceptance/environment.go b/tests/acceptance/environment.go index ee06e726f..f2c6cae33 100644 --- a/tests/acceptance/environment.go +++ b/tests/acceptance/environment.go @@ -8,7 +8,6 @@ import ( "strconv" "time" - aliasent "github.com/consensys/quorum-key-manager/src/aliases/entities" "github.com/consensys/quorum-key-manager/src/infra/hashicorp" hashicorpclient "github.com/consensys/quorum-key-manager/src/infra/hashicorp/client" "github.com/consensys/quorum-key-manager/src/infra/log" @@ -348,7 +347,6 @@ func (env *IntegrationEnvironment) createTables() error { &models2.Secret{}, &models2.Key{}, &models2.ETHAccount{}, - &aliasent.Alias{}, } { err = db.Model(v).CreateTable(opts) diff --git a/tests/e2e/alias_test.go b/tests/e2e/alias_test.go deleted file mode 100644 index a3aec4513..000000000 --- a/tests/e2e/alias_test.go +++ /dev/null @@ -1,242 +0,0 @@ -// +build e2e - -package e2e - -import ( - "context" - "math/rand" - "net/http" - "strconv" - "testing" - "time" - - "github.com/consensys/quorum-key-manager/pkg/client" - "github.com/consensys/quorum-key-manager/src/aliases/api/types" - "github.com/consensys/quorum-key-manager/tests" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" -) - -type aliasTestSuite struct { - suite.Suite - err error - ctx context.Context - rand *rand.Rand - - client *client.HTTPClient -} - -func TestAlias(t *testing.T) { - cfg, err := tests.NewConfig() - require.NoError(t, err) - - token, err := generateJWT("./certificates/client.key", "*:*", "e2e|keys_test") - require.NoError(t, err) - - cl := client.NewHTTPClient( - &http.Client{ - Transport: NewTestHttpTransport(token, "", nil), - }, &client.Config{ - URL: cfg.KeyManagerURL, - }) - s := aliasTestSuite{ - client: cl, - ctx: context.Background(), - rand: rand.New(rand.NewSource(time.Now().UnixNano())), - } - suite.Run(t, &s) -} - -type testAlias struct { - reg types.RegistryName - key types.AliasKey - val types.AliasValue - newVal types.AliasValue -} - -func (s *aliasTestSuite) fakeAlias() testAlias { - randInt := s.rand.Intn(1 << 32) - randID := strconv.Itoa(randInt) - return testAlias{ - reg: types.RegistryName("JPM-" + randID), - key: types.AliasKey("GoldmanSachs-" + randID), - val: `["ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc=","2T7xkjblN568N1QmPeElTjoeoNT4tkWYOJYxSMDO5i0="]`, - newVal: `["ZOAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc=","2T7xkjblN568N1QmPeElTjoeoNT4tkWYOJYxSMDO5i0="]`, - } -} - -func (s *aliasTestSuite) TestFull() { - fakeAlias := s.fakeAlias() - s.Run("should create a new alias successfully", func() { - a, err := s.client.CreateAlias(s.ctx, fakeAlias.reg, fakeAlias.key, types.AliasRequest{Value: fakeAlias.val}) - s.Require().NoError(err) - - s.Equal(fakeAlias.val, a.Value) - }) - s.Run("should get the new alias successfully", func() { - a, err := s.client.GetAlias(s.ctx, fakeAlias.reg, fakeAlias.key) - s.Require().NoError(err) - - s.Equal(fakeAlias.val, a.Value) - }) - s.Run("should update the new alias with a new value successfully", func() { - a, err := s.client.UpdateAlias(s.ctx, fakeAlias.reg, fakeAlias.key, types.AliasRequest{Value: fakeAlias.newVal}) - s.Require().NoError(err) - - s.Equal(fakeAlias.newVal, a.Value) - }) - s.Run("should get the update alias successfully", func() { - a, err := s.client.GetAlias(s.ctx, fakeAlias.reg, fakeAlias.key) - s.Require().NoError(err) - - s.Equal(fakeAlias.newVal, a.Value) - }) - s.Run("should list the updated alias successfully", func() { - as, err := s.client.ListAliases(s.ctx, fakeAlias.reg) - s.Require().NoError(err) - - s.Require().Len(as, 1) - s.Equal(fakeAlias.newVal, as[0].Value) - }) - s.Run("should delete the updated alias successfully", func() { - err := s.client.DeleteAlias(s.ctx, fakeAlias.reg, fakeAlias.key) - s.Require().NoError(err) - }) - s.Run("should fail with not found error if alias is deleted", func() { - _, err := s.client.GetAlias(s.ctx, fakeAlias.reg, fakeAlias.key) - s.Require().Error(err) - - s.checkErr(err, http.StatusNotFound) - }) -} - -func (s *aliasTestSuite) TestCreateAlias() { - fakeAlias := s.fakeAlias() - s.Run("should fail with bad request if registry has a bad format", func() { - fakeAlias := fakeAlias - fakeAlias.reg = "bad@registry" - _, err := s.client.CreateAlias(s.ctx, fakeAlias.reg, fakeAlias.key, types.AliasRequest{Value: fakeAlias.val}) - s.Require().Error(err) - - s.checkErr(err, http.StatusBadRequest) - }) - s.Run("should fail with bad request if key has a bad format", func() { - fakeAlias := fakeAlias - fakeAlias.key = "bad@key" - _, err := s.client.CreateAlias(s.ctx, fakeAlias.reg, fakeAlias.key, types.AliasRequest{Value: fakeAlias.val}) - s.Require().Error(err) - - s.checkErr(err, http.StatusBadRequest) - }) -} - -func (s *aliasTestSuite) TestUpdateAlias() { - fakeAlias := s.fakeAlias() - s.Run("should fail with bad request if registry has a bad format", func() { - fakeAlias := fakeAlias - fakeAlias.reg = "bad@registry" - _, err := s.client.UpdateAlias(s.ctx, fakeAlias.reg, fakeAlias.key, types.AliasRequest{Value: fakeAlias.newVal}) - s.Require().Error(err) - - s.checkErr(err, http.StatusBadRequest) - }) - s.Run("should fail with bad request if key has a bad format", func() { - fakeAlias := fakeAlias - fakeAlias.key = "bad@key" - _, err := s.client.UpdateAlias(s.ctx, fakeAlias.reg, fakeAlias.key, types.AliasRequest{Value: fakeAlias.newVal}) - s.Require().Error(err) - - s.checkErr(err, http.StatusBadRequest) - }) - s.Run("should fail with not found if key does not exist", func() { - fakeAlias := fakeAlias - fakeAlias.key = "notfound-key" - _, err := s.client.UpdateAlias(s.ctx, fakeAlias.reg, fakeAlias.key, types.AliasRequest{Value: fakeAlias.newVal}) - s.Require().Error(err) - - s.checkErr(err, http.StatusNotFound) - }) -} - -func (s *aliasTestSuite) TestGetAlias() { - fakeAlias := s.fakeAlias() - s.Run("should fail with bad request if registry has a bad format", func() { - fakeAlias := fakeAlias - fakeAlias.reg = "bad@registry" - _, err := s.client.GetAlias(s.ctx, fakeAlias.reg, fakeAlias.key) - s.Require().Error(err) - - s.checkErr(err, http.StatusBadRequest) - }) - s.Run("should fail with bad request if key has a bad format", func() { - fakeAlias := fakeAlias - fakeAlias.key = "bad@key" - _, err := s.client.GetAlias(s.ctx, fakeAlias.reg, fakeAlias.key) - s.Require().Error(err) - - s.checkErr(err, http.StatusBadRequest) - }) - s.Run("should fail with not found if key does not exist", func() { - fakeAlias := fakeAlias - fakeAlias.key = "notfound-key" - _, err := s.client.GetAlias(s.ctx, fakeAlias.reg, fakeAlias.key) - s.Require().Error(err) - - s.checkErr(err, http.StatusNotFound) - }) -} - -func (s *aliasTestSuite) TestDeleteAlias() { - fakeAlias := s.fakeAlias() - s.Run("should fail with bad request if registry has a bad format", func() { - fakeAlias := fakeAlias - fakeAlias.reg = "bad@registry" - err := s.client.DeleteAlias(s.ctx, fakeAlias.reg, fakeAlias.key) - s.Require().Error(err) - - s.checkErr(err, http.StatusBadRequest) - }) - s.Run("should fail with bad request if key has a bad format", func() { - fakeAlias := fakeAlias - fakeAlias.key = "bad@key" - err := s.client.DeleteAlias(s.ctx, fakeAlias.reg, fakeAlias.key) - s.Require().Error(err) - - s.checkErr(err, http.StatusBadRequest) - }) - s.Run("should fail with not found if key does not exist", func() { - fakeAlias := fakeAlias - fakeAlias.key = "notfound-key" - err := s.client.DeleteAlias(s.ctx, fakeAlias.reg, fakeAlias.key) - s.Require().Error(err) - - s.checkErr(err, http.StatusNotFound) - }) -} - -func (s *aliasTestSuite) TestListAliases() { - fakeAlias := s.fakeAlias() - s.Run("should fail with bad request if registry has a bad format", func() { - fakeAlias := fakeAlias - fakeAlias.reg = "bad@registry" - _, err := s.client.ListAliases(s.ctx, fakeAlias.reg) - s.Require().Error(err) - - s.checkErr(err, http.StatusBadRequest) - }) - s.Run("should fail with not found if key does not exist", func() { - fakeAlias := fakeAlias - fakeAlias.key = "notfound-key" - as, err := s.client.ListAliases(s.ctx, fakeAlias.reg) - s.Require().NoError(err) - - s.NotNil(as) - s.Len(as, 0) - }) -} - -func (s *aliasTestSuite) checkErr(err error, status int) { - httpError, ok := err.(*client.ResponseError) - s.Require().True(ok) - s.Equal(status, httpError.StatusCode) -}