diff --git a/.version b/.version index 4cc0e35..3b867cc 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -5.6.0 \ No newline at end of file +5.7.0 \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index d37c043..027865d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +### v5.7.0 +* Обновлены зависимости +* Добавлено поле `http_method` в `access_list` ### v5.6.0 * Для endpoint'а `system/secure/authenticate` в ответ добавлено поле `appName` (название приложения) * Обновлена версия `go` до `1.25` diff --git a/controller/access_list.go b/controller/access_list.go index 1cdaa16..cbdb7b0 100644 --- a/controller/access_list.go +++ b/controller/access_list.go @@ -16,6 +16,7 @@ type AccessListService interface { SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) DeleteList(ctx context.Context, req domain.AccessListDeleteListRequest) error + DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) error } type AccessList struct { @@ -141,3 +142,30 @@ func (c AccessList) DeleteList(ctx context.Context, req domain.AccessListDeleteL return err } } + +// DeleteListWithMethods godoc +// +// @Tags accessList +// @Summary Удалить список доступных методов для приложения +// @Description Удаляет заданный список методов для приложения +// @Accept json +// @Produce json +// @Param body body domain.AccessListDeleteV2ListRequest false "тело запроса" +// @Success 200 {object} any +// @Failure 404 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error +// @Router /access_list/delete_list_with_methods [POST] +func (c AccessList) DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) error { + err := c.service.DeleteListWithMethods(ctx, req) + switch { + case errors.Is(err, domain.ErrApplicationNotFound): + return apierrors.New( + codes.NotFound, + domain.ErrCodeApplicationNotFound, + fmt.Sprintf("application with id %d not found", req.AppId), + err, + ) + default: + return err + } +} diff --git a/controller/secure.go b/controller/secure.go index 5b5c0f0..aed11f8 100644 --- a/controller/secure.go +++ b/controller/secure.go @@ -10,7 +10,7 @@ import ( type SecureService interface { Authenticate(ctx context.Context, token string) (*domain.AuthData, error) - Authorize(ctx context.Context, appId int, endpoint string) (bool, error) + Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error) } type Secure struct { @@ -69,7 +69,7 @@ func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest // @Failure 500 {object} apierrors.Error // @Router /secure/authorize [POST] func (c Secure) Authorize(ctx context.Context, req domain.AuthorizeRequest) (*domain.AuthorizeResponse, error) { - result, err := c.service.Authorize(ctx, req.ApplicationId, req.Endpoint) + result, err := c.service.Authorize(ctx, req) switch { case errors.Is(err, domain.ErrAccessListNotFound): return &domain.AuthorizeResponse{ diff --git a/docs/swagger.yaml b/docs/swagger.yaml index ba2525c..15d7e3b 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -23,6 +23,19 @@ definitions: - appId - methods type: object + domain.AccessListDeleteV2ListRequest: + properties: + appId: + type: integer + methods: + items: + $ref: '#/definitions/domain.Method' + minItems: 1 + type: array + required: + - appId + - methods + type: object domain.AccessListSetListRequest: properties: appId: @@ -40,6 +53,8 @@ definitions: properties: appId: type: integer + httpMethod: + type: string method: type: string value: @@ -162,6 +177,8 @@ definitions: type: integer endpoint: type: string + httpMethod: + type: string required: - applicationId - endpoint @@ -276,8 +293,19 @@ definitions: required: - id type: object + domain.Method: + properties: + httpMethod: + type: string + method: + type: string + required: + - method + type: object domain.MethodInfo: properties: + httpMethod: + type: string method: type: string value: @@ -432,6 +460,34 @@ paths: summary: Удалить список доступных методов для приложения tags: - accessList + /access_list/delete_list_with_methods: + post: + consumes: + - application/json + description: Удаляет заданный список методов для приложения + parameters: + - description: тело запроса + in: body + name: body + schema: + $ref: '#/definitions/domain.AccessListDeleteV2ListRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: {} + "404": + description: Not Found + schema: + $ref: '#/definitions/apierrors.Error' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/apierrors.Error' + summary: Удалить список доступных методов для приложения + tags: + - accessList /access_list/get_by_id: post: consumes: diff --git a/domain/access_list.go b/domain/access_list.go index d822181..1610da9 100644 --- a/domain/access_list.go +++ b/domain/access_list.go @@ -1,9 +1,10 @@ package domain type AccessListSetOneRequest struct { - AppId int `validate:"required"` - Method string `validate:"required"` - Value bool + AppId int `validate:"required"` + HttpMethod string + Method string `validate:"required"` + Value bool } type AccessListSetOneResponse struct { @@ -17,11 +18,22 @@ type AccessListSetListRequest struct { } type MethodInfo struct { - Method string - Value bool + HttpMethod string + Method string + Value bool } type AccessListDeleteListRequest struct { AppId int `validate:"required"` Methods []string `validate:"required,min=1"` } + +type AccessListDeleteV2ListRequest struct { + AppId int `validate:"required"` + Methods []Method `validate:"required,min=1"` +} + +type Method struct { + HttpMethod string + Method string `validate:"required"` +} diff --git a/domain/secure.go b/domain/secure.go index a273bbf..18d1b47 100644 --- a/domain/secure.go +++ b/domain/secure.go @@ -19,7 +19,8 @@ type AuthData struct { } type AuthorizeRequest struct { - ApplicationId int `validate:"required"` + ApplicationId int `validate:"required"` + HttpMethod string Endpoint string `validate:"required"` } diff --git a/entity/access_list.go b/entity/access_list.go index c0fc80a..92af2c5 100644 --- a/entity/access_list.go +++ b/entity/access_list.go @@ -1,7 +1,13 @@ package entity type AccessList struct { - AppId int - Method string - Value bool + AppId int + HttpMethod string + Method string + Value bool +} + +type Method struct { + HttpMethod string + Method string } diff --git a/go.mod b/go.mod index 830b941..cdce8f6 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ require ( github.com/jackc/pgx/v5 v5.7.6 github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.11.1 - github.com/txix-open/isp-kit v1.62.0 + github.com/txix-open/isp-kit v1.64.6 github.com/txix-open/jsonschema v1.3.0 google.golang.org/grpc v1.75.1 ) @@ -69,11 +69,11 @@ require ( go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect - golang.org/x/crypto v0.42.0 // indirect - golang.org/x/net v0.44.0 // indirect - golang.org/x/sync v0.17.0 // indirect - golang.org/x/sys v0.36.0 // indirect - golang.org/x/text v0.29.0 // indirect + golang.org/x/crypto v0.45.0 // indirect + golang.org/x/net v0.47.0 // indirect + golang.org/x/sync v0.18.0 // indirect + golang.org/x/sys v0.38.0 // indirect + golang.org/x/text v0.31.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250908214217-97024824d090 // indirect google.golang.org/protobuf v1.36.9 // indirect diff --git a/go.sum b/go.sum index f8571b6..8a35b7b 100644 --- a/go.sum +++ b/go.sum @@ -68,8 +68,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= -github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/compress v1.18.1 h1:bcSGx7UbpBqMChDtsF28Lw6v/G94LPrrbMbdC3JH2co= +github.com/klauspost/compress v1.18.1/go.mod h1:ZQFFVG+MdnR0P+l6wpXgIL4NTtwiKIdBnrBd8Nrxr+0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -146,8 +146,8 @@ github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIg github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8= github.com/txix-open/grmq v1.9.0 h1:ArDbJJcFX9zXKEcPf49rp9nYiRyGMJxGKJAxdbSsfaM= github.com/txix-open/grmq v1.9.0/go.mod h1:EyFOP17KrwEFOUjR+PH8iH3LCtiN9TSQ8t0ysyk62po= -github.com/txix-open/isp-kit v1.62.0 h1:SfY8x5/3yYEicr5phGTJBaUwFvgktSIsD/NubrKYbg4= -github.com/txix-open/isp-kit v1.62.0/go.mod h1:hyCFmWF0qoVY2loTLyHJx8QPZJuULntG0JfthqFCdsA= +github.com/txix-open/isp-kit v1.64.6 h1:AXQ8/HQGG1VoJyiFvPqgPimPp5WJ4MrlWzPBxuxqhRs= +github.com/txix-open/isp-kit v1.64.6/go.mod h1:GvBsX5p2U3/ugK6PuWANYzSy/4YgawROm3eAKb35G6o= github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4= github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00= github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0= @@ -189,18 +189,18 @@ go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= -golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= -golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= +golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= +golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o= golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8= -golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I= -golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= -golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= -golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= -golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= -golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= -golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= +golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= +golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= +golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= +golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= +golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= +golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090 h1:d8Nakh1G+ur7+P3GcMjpRDEkoLUcLW2iU92XVqR+XMQ= diff --git a/migrations/20260121072119_recreate_access_list.sql b/migrations/20260121072119_recreate_access_list.sql new file mode 100644 index 0000000..4a89768 --- /dev/null +++ b/migrations/20260121072119_recreate_access_list.sql @@ -0,0 +1,36 @@ +-- +goose Up +CREATE TABLE access_list_new +( + app_id INT, + http_method VARCHAR(255) NOT NULL DEFAULT '', + method VARCHAR(255), + value BOOLEAN NOT NULL, + PRIMARY KEY (app_id, http_method, method), + CONSTRAINT FK_app_id__application_id FOREIGN KEY (app_id) REFERENCES application (id) ON DELETE CASCADE ON UPDATE CASCADE +); + +INSERT INTO access_list_new (app_id, method, value) +SELECT app_id, method, value +FROM access_list +WHERE value = true; + +DROP TABLE access_list; +ALTER TABLE access_list_new RENAME TO access_list; + +-- +goose Down +CREATE TABLE access_list_old +( + app_id INT, + method VARCHAR(255), + value BOOLEAN NOT NULL, + PRIMARY KEY (app_id, method), + CONSTRAINT FK_app_id__application_id FOREIGN KEY (app_id) REFERENCES application (id) ON DELETE CASCADE ON UPDATE CASCADE +); + +INSERT INTO access_list_old (app_id, method, value) +SELECT app_id, method, value +FROM access_list +WHERE value = true; + +DROP TABLE access_list; +ALTER TABLE access_list_old RENAME TO access_list; \ No newline at end of file diff --git a/repository/access_list.go b/repository/access_list.go index 6a33af1..14a5c22 100644 --- a/repository/access_list.go +++ b/repository/access_list.go @@ -11,6 +11,7 @@ import ( "github.com/pkg/errors" "github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/db/query" + "github.com/txix-open/isp-kit/metrics/sql_metrics" ) type AccessList struct { @@ -23,14 +24,20 @@ func NewAccessList(db db.DB) AccessList { } } -func (r AccessList) GetAccessListByAppIdAndMethod(ctx context.Context, appId int, method string) (*entity.AccessList, error) { +func (r AccessList) GetAccessListByAppIdAndMethod(ctx context.Context, appId int, httpMethod string, method string) (*entity.AccessList, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppIdAndMethod") + q := ` - SELECT app_id, method, value - FROM access_list - WHERE app_id = $1 AND method = $2 -` + SELECT app_id, http_method, method, value + FROM access_list + WHERE app_id = $1 + AND method = $2 + AND http_method IN ($3, '') + ORDER BY (http_method = $3) DESC + LIMIT 1; + ` result := entity.AccessList{} - err := r.db.SelectRow(ctx, &result, q, appId, method) + err := r.db.SelectRow(ctx, &result, q, appId, method, httpMethod) switch { case errors.Is(err, sql.ErrNoRows): return nil, domain.ErrAccessListNotFound @@ -42,11 +49,13 @@ func (r AccessList) GetAccessListByAppIdAndMethod(ctx context.Context, appId int } func (r AccessList) GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppId") + q := ` - SELECT app_id, method, value + SELECT app_id, http_method, method, value FROM access_list WHERE app_id = $1 -` + ` result := make([]entity.AccessList, 0) err := r.db.Select(ctx, &result, q, appId) if err != nil { @@ -57,8 +66,10 @@ func (r AccessList) GetAccessListByAppId(ctx context.Context, appId int) ([]enti } func (r AccessList) GetAccessListByAppIdList(ctx context.Context, appIdList []int) ([]entity.AccessList, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppIdList") + q, args, err := query.New(). - Select("app_id", "method", "value"). + Select("app_id", "http_method", "method", "value"). From("access_list"). Where(squirrel.Eq{"app_id": appIdList}). ToSql() @@ -76,11 +87,13 @@ func (r AccessList) GetAccessListByAppIdList(ctx context.Context, appIdList []in } func (r AccessList) InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error { + ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.InsertArrayAccessList") + qBuilder := query.New(). Insert("access_list"). - Columns("app_id", "method", "value") + Columns("app_id", "http_method", "method", "value") for _, e := range entity { - qBuilder = qBuilder.Values(e.AppId, e.Method, e.Value) + qBuilder = qBuilder.Values(e.AppId, e.HttpMethod, e.Method, e.Value) } q, args, err := qBuilder.ToSql() if err != nil { @@ -96,15 +109,17 @@ func (r AccessList) InsertArrayAccessList(ctx context.Context, entity []entity.A } func (r AccessList) UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.UpsertAccessList") + q := ` INSERT INTO access_list - (app_id, method, value) - VALUES ($1, $2, $3) - ON CONFLICT (app_id, method) + (app_id, http_method, method, value) + VALUES ($1, $2, $3, $4) + ON CONFLICT (app_id, http_method, method) DO UPDATE SET (value) = (SELECT EXCLUDED.value) -` - result, err := r.db.Exec(ctx, q, e.AppId, e.Method, e.Value) + ` + result, err := r.db.Exec(ctx, q, e.AppId, e.HttpMethod, e.Method, e.Value) if err != nil { return 0, errors.WithMessagef(err, "exec query %s", q) } @@ -117,14 +132,25 @@ func (r AccessList) UpsertAccessList(ctx context.Context, e entity.AccessList) ( return int(rowsAffected), nil } -func (r AccessList) DeleteAccessList(ctx context.Context, appId int, methods []string) error { +func (r AccessList) DeleteAccessList(ctx context.Context, appId int, methods []entity.Method) error { + ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.DeleteAccessList") + + methodsClause := squirrel.Or{} + for _, method := range methods { + methodsClause = append(methodsClause, squirrel.And{ + squirrel.Eq{"method": method.Method}, + squirrel.Eq{"http_method": method.HttpMethod}, + }) + } + q, args, err := query.New(). Delete("access_list"). - Where(squirrel.Eq{ - "app_id": appId, - "method": methods, + Where(squirrel.And{ + squirrel.Eq{ + "app_id": appId, + }, + methodsClause, }). - Suffix("RETURNING app_id, method, value"). ToSql() if err != nil { return errors.WithMessage(err, "build query") @@ -139,11 +165,13 @@ func (r AccessList) DeleteAccessList(ctx context.Context, appId int, methods []s } func (r AccessList) DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.DeleteAccessListByAppId") + q := ` DELETE FROM access_list WHERE app_id = $1 - RETURNING app_id, method, value -` + RETURNING app_id, http_method, method, value + ` result := make([]entity.AccessList, 0) err := r.db.Select(ctx, &result, q, appId) if err != nil { diff --git a/repository/app_group.go b/repository/app_group.go index 5ce5e30..1248ce1 100644 --- a/repository/app_group.go +++ b/repository/app_group.go @@ -12,6 +12,7 @@ import ( "github.com/pkg/errors" "github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/db/query" + "github.com/txix-open/isp-kit/metrics/sql_metrics" ) type AppGroup struct { @@ -25,11 +26,13 @@ func NewAppGroup(db db.DB) AppGroup { } func (r AppGroup) GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupById") + q := ` SELECT id, name, description, domain_id, created_at, updated_at FROM application_group WHERE id = $1 -` + ` result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, id) switch { @@ -43,6 +46,8 @@ func (r AppGroup) GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup } func (r AppGroup) GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByIdList") + q, arg, err := query.New(). Select("id", "name", "description", "domain_id", "created_at", "updated_at"). From("application_group"). @@ -63,6 +68,8 @@ func (r AppGroup) GetAppGroupByIdList(ctx context.Context, idList []int) ([]enti } func (r AppGroup) GetAppGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.AppGroup, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByDomainId") + q, arg, err := query.New(). Select("id", "name", "description", "domain_id", "created_at", "updated_at"). From("application_group"). @@ -83,11 +90,13 @@ func (r AppGroup) GetAppGroupByDomainId(ctx context.Context, domainIdList []int) } func (r AppGroup) GetAppGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.AppGroup, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByNameAndDomainId") + q := ` SELECT id, name, description, domain_id, created_at, updated_at FROM application_group WHERE name = $1 AND domain_id = $2 -` + ` result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, domainId) switch { @@ -101,13 +110,15 @@ func (r AppGroup) GetAppGroupByNameAndDomainId(ctx context.Context, name string, } func (r AppGroup) CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.CreateAppGroup") + q := ` INSERT INTO application_group (name, description, domain_id) VALUES ($1, $2, $3) ON CONFLICT (name, domain_id) DO NOTHING RETURNING id, name, description, domain_id, created_at, updated_at -` + ` result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, desc, domainId) switch { @@ -121,12 +132,14 @@ func (r AppGroup) CreateAppGroup(ctx context.Context, name string, desc string, } func (r AppGroup) UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.UpdateAppGroup") + q := ` UPDATE application_group SET name = $1, description = $2 WHERE id = $3 RETURNING id, name, description, domain_id, created_at, updated_at -` + ` result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, description, id) var pgErr *pgconn.PgError @@ -143,6 +156,8 @@ func (r AppGroup) UpdateAppGroup(ctx context.Context, id int, name string, descr } func (r AppGroup) DeleteAppGroup(ctx context.Context, idList []int) (int, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.DeleteAppGroup") + q, args, err := query.New(). Delete("application_group"). Where(squirrel.Eq{"id": idList}). @@ -165,6 +180,8 @@ func (r AppGroup) DeleteAppGroup(ctx context.Context, idList []int) (int, error) } func (r AppGroup) GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAllAppGroups") + q, arg, err := query.New(). Select("id", "name", "description", "domain_id", "created_at", "updated_at"). From("application_group"). diff --git a/repository/application.go b/repository/application.go index 32c94f7..dd3c4b2 100644 --- a/repository/application.go +++ b/repository/application.go @@ -12,6 +12,7 @@ import ( "github.com/pkg/errors" "github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/db/query" + "github.com/txix-open/isp-kit/metrics/sql_metrics" ) type Application struct { @@ -25,11 +26,13 @@ func NewApplication(db db.DB) Application { } func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Application, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationById") + q := ` SELECT id, name, description, application_group_id, type, created_at, updated_at FROM application WHERE id = $1 -` + ` result := entity.Application{} err := r.db.SelectRow(ctx, &result, q, id) switch { @@ -43,6 +46,8 @@ func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Ap } func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationByIdList") + q, args, err := query.New(). Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at"). From("application"). @@ -63,6 +68,8 @@ func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) ( } func (r Application) GetApplicationByAppGroupIdList(ctx context.Context, appGroupIdList []int) ([]entity.Application, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationByAppGroupIdList") + q, args, err := query.New(). Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at"). From("application"). @@ -83,11 +90,13 @@ func (r Application) GetApplicationByAppGroupIdList(ctx context.Context, appGrou } func (r Application) GetApplicationByNameAndAppGroupId(ctx context.Context, name string, serviceId int) (*entity.Application, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationByNameAndAppGroupId") + q := ` SELECT id, name, description, application_group_id, type, created_at, updated_at FROM application WHERE name = $1 AND application_group_id = $2 -` + ` result := entity.Application{} err := r.db.SelectRow(ctx, &result, q, name, serviceId) switch { @@ -100,14 +109,22 @@ func (r Application) GetApplicationByNameAndAppGroupId(ctx context.Context, name } } -func (r Application) CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) ( - *entity.Application, error) { +func (r Application) CreateApplication( + ctx context.Context, + id int, + name string, + desc string, + appGroupId int, + appType string, +) (*entity.Application, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Application.CreateApplication") + q := ` INSERT INTO application (id, name, description, application_group_id, type) VALUES ($1, $2, $3, $4, $5) RETURNING id, name, description, application_group_id, type, created_at, updated_at -` + ` result := entity.Application{} err := r.db.SelectRow(ctx, &result, q, id, name, desc, appGroupId, appType) if err != nil { @@ -122,13 +139,15 @@ func (r Application) UpdateApplication( name string, description string, ) (*entity.Application, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Application.UpdateApplication") + q := ` UPDATE application SET name = $2, description = $3 WHERE id = $1 RETURNING id, name, description, application_group_id, type, created_at, updated_at -` + ` result := entity.Application{} err := r.db.SelectRow(ctx, &result, q, id, name, description) if err != nil { @@ -144,6 +163,8 @@ func (r Application) UpdateApplicationWithNewId( name string, description string, ) (*entity.Application, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Application.UpdateApplicationWithNewId") + q := ` UPDATE application SET id = $2, @@ -151,7 +172,7 @@ func (r Application) UpdateApplicationWithNewId( description = $4 WHERE id = $1 RETURNING id, name, description, application_group_id, type, created_at, updated_at -` + ` result := entity.Application{} err := r.db.SelectRow(ctx, &result, q, oldId, newId, name, description) if err != nil { @@ -161,6 +182,8 @@ func (r Application) UpdateApplicationWithNewId( } func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Application.DeleteApplicationByIdList") + q, args, err := query.New(). Delete("application"). Where(squirrel.Eq{"id": idList}). @@ -183,6 +206,8 @@ func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int } func (r Application) NextApplicationId(ctx context.Context) (int, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Application.NextApplicationId") + q := `SELECT COALESCE(MAX(id)+1, 1) FROM application;` nextAppId := 0 err := r.db.SelectRow(ctx, &nextAppId, q) @@ -193,6 +218,8 @@ func (r Application) NextApplicationId(ctx context.Context) (int, error) { } func (r Application) GetAllApplications(ctx context.Context) ([]entity.Application, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetAllApplications") + q, args, err := query.New(). Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at"). From("application"). diff --git a/repository/domain.go b/repository/domain.go index 404543e..860f49a 100644 --- a/repository/domain.go +++ b/repository/domain.go @@ -11,6 +11,7 @@ import ( "github.com/pkg/errors" "github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/db/query" + "github.com/txix-open/isp-kit/metrics/sql_metrics" ) type Domain struct { @@ -24,11 +25,13 @@ func NewDomain(db db.DB) Domain { } func (r Domain) GetDomainById(ctx context.Context, id int) (*entity.Domain, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainById") + q := ` SELECT id, name, description, system_id, created_at, updated_at FROM domain WHERE id = $1 -` + ` result := entity.Domain{} err := r.db.SelectRow(ctx, &result, q, id) switch { @@ -42,6 +45,8 @@ func (r Domain) GetDomainById(ctx context.Context, id int) (*entity.Domain, erro } func (r Domain) GetDomainByIdList(ctx context.Context, idList []int) ([]entity.Domain, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainByIdList") + q, args, err := query.New(). Select("id", "name", "description", "system_id", "created_at", "updated_at"). From("domain"). @@ -61,12 +66,14 @@ func (r Domain) GetDomainByIdList(ctx context.Context, idList []int) ([]entity.D } func (r Domain) GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainBySystemId") + q := ` SELECT id, name, description, system_id, created_at, updated_at FROM domain WHERE system_id = $1 ORDER BY created_at DESC -` + ` result := make([]entity.Domain, 0) err := r.db.Select(ctx, &result, q, systemId) if err != nil { @@ -77,11 +84,13 @@ func (r Domain) GetDomainBySystemId(ctx context.Context, systemId int) ([]entity } func (r Domain) GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainByNameAndSystemId") + q := ` SELECT id, name, description, system_id, created_at, updated_at FROM domain WHERE name = $1 AND system_id = $2 -` + ` result := entity.Domain{} err := r.db.SelectRow(ctx, &result, q, name, systemId) switch { @@ -95,12 +104,14 @@ func (r Domain) GetDomainByNameAndSystemId(ctx context.Context, name string, sys } func (r Domain) CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.CreateDomain") + q := ` INSERT INTO domain (name, description, system_id) VALUES ($1, $2, $3) RETURNING id, name, description, system_id, created_at, updated_at -` + ` result := entity.Domain{} err := r.db.SelectRow(ctx, &result, q, name, desc, systemId) if err != nil { @@ -110,6 +121,8 @@ func (r Domain) CreateDomain(ctx context.Context, name string, desc string, syst } func (r Domain) UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.UpdateDomain") + q := ` UPDATE domain SET name = $1, description = $2 @@ -129,6 +142,8 @@ func (r Domain) UpdateDomain(ctx context.Context, id int, name string, descripti } func (r Domain) DeleteDomain(ctx context.Context, idList []int) (int, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.DeleteDomain") + q, args, err := query.New(). Delete("domain"). Where(squirrel.Eq{"id": idList}). diff --git a/repository/token.go b/repository/token.go index 95f58fc..413d594 100644 --- a/repository/token.go +++ b/repository/token.go @@ -11,6 +11,7 @@ import ( "github.com/pkg/errors" "github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/db/query" + "github.com/txix-open/isp-kit/metrics/sql_metrics" ) type Token struct { @@ -24,12 +25,14 @@ func NewToken(db db.DB) Token { } func (r Token) SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Token.SaveToken") + q := ` INSERT INTO token (token, app_id, expire_time) VALUES ($1, $2, $3) RETURNING token, app_id, expire_time, created_at -` + ` result := entity.Token{} err := r.db.SelectRow(ctx, &result, q, token, appId, expireTime) if err != nil { @@ -40,11 +43,13 @@ func (r Token) SaveToken(ctx context.Context, token string, appId int, expireTim } func (r Token) GetTokenById(ctx context.Context, token string) (*entity.Token, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Token.GetTokenById") + q := ` SELECT token, app_id, expire_time, created_at FROM token WHERE token = $1 -` + ` result := entity.Token{} err := r.db.SelectRow(ctx, &result, q, token) switch { @@ -58,6 +63,8 @@ func (r Token) GetTokenById(ctx context.Context, token string) (*entity.Token, e } func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Token.GetTokenByAppIdList") + q, args, err := query.New(). Select("token", "app_id", "expire_time", "created_at"). From("token"). @@ -78,6 +85,8 @@ func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]enti } func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Token.DeleteToken") + q, args, err := query.New(). Delete("token"). Where(squirrel.Eq{"token": tokens}). @@ -100,6 +109,8 @@ func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) { } func (r Token) AuthDataByToken(ctx context.Context, token string) (*entity.AuthData, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Token.AuthDataByToken") + q := ` SELECT system_id, domain_id, application_group_id, app_id, application.name AS app_name , token.expire_time, token.created_at FROM token diff --git a/routes/routes.go b/routes/routes.go index 2fb439a..e1eaf78 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -79,6 +79,11 @@ func accessListCluster(c Controllers) []cluster.EndpointDescriptor { Inner: true, Handler: c.AccessList.DeleteList, }, + { + Path: "system/access_list/delete_list_with_methods", + Inner: true, + Handler: c.AccessList.DeleteListWithMethods, + }, } } diff --git a/service/access_list.go b/service/access_list.go index c1157ca..765c8b3 100644 --- a/service/access_list.go +++ b/service/access_list.go @@ -11,7 +11,7 @@ import ( type AccessListRepo interface { GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) - DeleteAccessList(ctx context.Context, appId int, methods []string) error + DeleteAccessList(ctx context.Context, appId int, methods []entity.Method) error } type AccessListSetOneTx interface { @@ -21,7 +21,7 @@ type AccessListSetOneTx interface { type AccessListSetListTx interface { GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error - DeleteAccessList(ctx context.Context, appId int, methods []string) error + DeleteAccessList(ctx context.Context, appId int, methods []entity.Method) error DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) } @@ -79,9 +79,10 @@ func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneR var resp int err = s.tx.AccessListSetOneTx(ctx, func(ctx context.Context, tx AccessListSetOneTx) error { resp, err = tx.UpsertAccessList(ctx, entity.AccessList{ - AppId: request.AppId, - Method: request.Method, - Value: request.Value, + AppId: request.AppId, + HttpMethod: request.HttpMethod, + Method: request.Method, + Value: request.Value, }) if err != nil { return errors.WithMessage(err, "upsert access list") @@ -113,13 +114,17 @@ func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListReq } newAccessList := make([]entity.AccessList, len(req.Methods)) - updateMethods := make([]string, len(req.Methods)) + updateMethods := make([]entity.Method, len(req.Methods)) for i, m := range req.Methods { - updateMethods[i] = m.Method + updateMethods[i] = entity.Method{ + HttpMethod: m.HttpMethod, + Method: m.Method, + } newAccessList[i] = entity.AccessList{ - AppId: req.AppId, - Method: m.Method, - Value: m.Value, + AppId: req.AppId, + HttpMethod: m.HttpMethod, + Method: m.Method, + Value: m.Value, } } @@ -158,11 +163,27 @@ func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListReq } func (s AccessList) DeleteList(ctx context.Context, req domain.AccessListDeleteListRequest) error { + methods := make([]domain.Method, 0, len(req.Methods)) + for _, method := range req.Methods { + methods = append(methods, domain.Method{Method: method}) + } + return s.DeleteListWithMethods(ctx, domain.AccessListDeleteV2ListRequest{ + AppId: req.AppId, + Methods: methods, + }) +} + +func (s AccessList) DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) error { _, err := s.appRepo.GetApplicationById(ctx, req.AppId) if err != nil { return errors.WithMessage(err, "get application by id") } - err = s.accessListRepo.DeleteAccessList(ctx, req.AppId, req.Methods) + + methods := make([]entity.Method, 0, len(req.Methods)) + for _, method := range req.Methods { + methods = append(methods, entity.Method{Method: method.Method, HttpMethod: method.HttpMethod}) + } + err = s.accessListRepo.DeleteAccessList(ctx, req.AppId, methods) if err != nil { return errors.WithMessage(err, "delete access_list") } diff --git a/service/secure/service.go b/service/secure/service.go index 1be0219..e5c51a1 100644 --- a/service/secure/service.go +++ b/service/secure/service.go @@ -15,7 +15,7 @@ type TokenRep interface { } type AccessListRep interface { - GetAccessListByAppIdAndMethod(ctx context.Context, appId int, method string) (*entity.AccessList, error) + GetAccessListByAppIdAndMethod(ctx context.Context, appId int, httpMethod string, method string) (*entity.AccessList, error) } type Service struct { @@ -53,8 +53,13 @@ func (s Service) Authenticate(ctx context.Context, token string) (*domain.AuthDa }, nil } -func (s Service) Authorize(ctx context.Context, appId int, endpoint string) (bool, error) { - accessList, err := s.accessListRep.GetAccessListByAppIdAndMethod(ctx, appId, endpoint) +func (s Service) Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error) { + accessList, err := s.accessListRep.GetAccessListByAppIdAndMethod( + ctx, + req.ApplicationId, + req.HttpMethod, + req.Endpoint, + ) if err != nil { return false, errors.WithMessage(err, "get access list by app_id and method") } diff --git a/tests/secure_test.go b/tests/secure_test.go index d3a4afc..38b7353 100644 --- a/tests/secure_test.go +++ b/tests/secure_test.go @@ -1,6 +1,7 @@ package tests_test import ( + "net/http" "testing" "time" @@ -196,3 +197,26 @@ func (s *SecureSuite) TestAuthorize_NotFound() { Authorized: false, }, result) } + +func (s *SecureSuite) TestAuthorize_WithHttpMethod_Success_True() { + InsertAccessList(s.testDb, entity.AccessList{ + AppId: 7, + HttpMethod: http.MethodGet, + Method: "endpoint/available_http", + Value: true, + }) + + result := domain.AuthorizeResponse{} + err := s.api.Invoke("system/secure/authorize"). + JsonRequestBody(domain.AuthorizeRequest{ + ApplicationId: 7, + HttpMethod: http.MethodGet, + Endpoint: "endpoint/available_http", + }). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + s.Require().Equal(domain.AuthorizeResponse{ + Authorized: true, + }, result) +}