2024-01-22 17:22:41: merge [master:56d3e06e49d7a75f142424293788a4f3b6245430];
This commit is contained in:
1 parent
7014f56cbb
commit
2b91caece0
60 files changed
+3558
No files matched your search
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"isp-gate-service/domain"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
adminAuthHeader = "x-auth-admin"
|
||||
)
|
||||
|
||||
type AdminAuthenticator interface {
|
||||
AdminAuthenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error)
|
||||
}
|
||||
|
||||
func AdminAuthenticate(auth AdminAuthenticator) Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx *request.Context) error {
|
||||
adminToken := ctx.Param(adminAuthHeader)
|
||||
if adminToken == "" {
|
||||
return next.Handle(ctx)
|
||||
}
|
||||
resp, err := auth.AdminAuthenticate(ctx.Context(), adminToken)
|
||||
if err != nil {
|
||||
return httperrors.New(
|
||||
http.StatusUnauthorized,
|
||||
"invalid admin token",
|
||||
errors.WithMessage(err, "admin authenticate: authenticate"),
|
||||
)
|
||||
}
|
||||
if !resp.Authenticated {
|
||||
return httperrors.New(
|
||||
http.StatusUnauthorized,
|
||||
"invalid admin token",
|
||||
errors.WithMessage(errors.New(resp.ErrorReason), "admin authenticate: authenticate"),
|
||||
)
|
||||
}
|
||||
ctx.AuthenticateAdmin(resp.AdminId, adminToken)
|
||||
return next.Handle(ctx)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type AdminMethodStore interface {
|
||||
IsInnerEndpoint(path string) bool
|
||||
RequiredAdminPermission(path string) (string, bool)
|
||||
}
|
||||
|
||||
type AdminAuthorizer interface {
|
||||
AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error)
|
||||
}
|
||||
|
||||
func AdminAuthorize(store AdminMethodStore, authorizer AdminAuthorizer) Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx *request.Context) error {
|
||||
isInner := store.IsInnerEndpoint(ctx.Endpoint())
|
||||
if !isInner {
|
||||
return next.Handle(ctx)
|
||||
}
|
||||
|
||||
if !ctx.IsAdminAuthenticated() {
|
||||
return httperrors.New(
|
||||
http.StatusForbidden,
|
||||
"admin authentication required",
|
||||
errors.Errorf("admin authorization: admin authentication required for '%s'", ctx.Endpoint()),
|
||||
)
|
||||
}
|
||||
|
||||
requiredPerm, ok := store.RequiredAdminPermission(ctx.Endpoint())
|
||||
if !ok {
|
||||
return next.Handle(ctx)
|
||||
}
|
||||
|
||||
ok, err := authorizer.AdminAuthorize(ctx.Context(), ctx.AdminId(), requiredPerm)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "admin authorization: authorize")
|
||||
}
|
||||
if !ok {
|
||||
return httperrors.New(
|
||||
http.StatusForbidden,
|
||||
"endpoint is not allowed",
|
||||
errors.Errorf(
|
||||
"admin authorization: endpoint '%s' requires '%s' permission, but admin '%d' doesn't have it",
|
||||
ctx.Endpoint(), requiredPerm, ctx.AdminId(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
return next.Handle(ctx)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/domain"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
const (
|
||||
applicationTokenHeader = "x-application-token"
|
||||
)
|
||||
|
||||
type Authenticator interface {
|
||||
Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error)
|
||||
}
|
||||
|
||||
func Authenticate(authenticator Authenticator) Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx *request.Context) error {
|
||||
token := ctx.Param(applicationTokenHeader)
|
||||
if token == "" {
|
||||
return httperrors.New(
|
||||
http.StatusUnauthorized,
|
||||
"application token required",
|
||||
errors.New("authenticate: application token required"),
|
||||
)
|
||||
}
|
||||
|
||||
resp, err := authenticator.Authenticate(ctx.Context(), token)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "authenticate: authenticate")
|
||||
}
|
||||
if !resp.Authenticated {
|
||||
return httperrors.New(
|
||||
http.StatusUnauthorized,
|
||||
"invalid application token",
|
||||
errors.WithMessage(errors.New(resp.ErrorReason), "authenticate: authenticate"),
|
||||
)
|
||||
}
|
||||
ctx.Authenticate(request.AuthData(*resp.AuthData))
|
||||
|
||||
return next.Handle(ctx)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type Authorizer interface {
|
||||
Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error)
|
||||
}
|
||||
|
||||
func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx *request.Context) error {
|
||||
authData, err := ctx.GetAuthData()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "authorize: get auth data")
|
||||
}
|
||||
|
||||
ok, err := authorizer.Authorize(ctx.Context(), authData.ApplicationId, ctx.Endpoint())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "authorize: authorize")
|
||||
}
|
||||
if !ok && ctx.IsAdminAuthenticated() {
|
||||
logger.Info(
|
||||
ctx.Context(),
|
||||
"bypassing unauthorized request because it has admin privilege",
|
||||
log.Int("applicationId", authData.ApplicationId),
|
||||
log.Int("adminId", ctx.AdminId()),
|
||||
)
|
||||
return next.Handle(ctx)
|
||||
}
|
||||
if !ok {
|
||||
return httperrors.New(
|
||||
http.StatusForbidden,
|
||||
"endpoint is not allowed",
|
||||
errors.Errorf("authorize: endpoint '%s' is not allowed for application '%d'", ctx.Endpoint(), authData.ApplicationId),
|
||||
)
|
||||
}
|
||||
|
||||
return next.Handle(ctx)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type DailyLimitChecker interface {
|
||||
IncrementAndCheck(ctx context.Context, applicationId int) (bool, error)
|
||||
}
|
||||
|
||||
func DailyLimit(checker DailyLimitChecker) Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx *request.Context) error {
|
||||
authData, err := ctx.GetAuthData()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "daily limit: get auth data")
|
||||
}
|
||||
|
||||
ok, err := checker.IncrementAndCheck(ctx.Context(), authData.ApplicationId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "daily limit: increment and check")
|
||||
}
|
||||
if !ok {
|
||||
return httperrors.New(
|
||||
http.StatusTooManyRequests,
|
||||
"daily requests limit has been reached",
|
||||
errors.Errorf("daily limit: daily requests limit has been reached for application '%d'", authData.ApplicationId),
|
||||
)
|
||||
}
|
||||
|
||||
return next.Handle(ctx)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type EntryPointConfig struct {
|
||||
PathPrefix string
|
||||
WithPrefix bool
|
||||
}
|
||||
|
||||
func Entrypoint(maxReqBodySize int64, next Handler, logger log.Logger, cfg EntryPointConfig) http.Handler {
|
||||
return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
|
||||
req.Body = http.MaxBytesReader(writer, req.Body, maxReqBodySize)
|
||||
|
||||
endpoint := req.URL.Path
|
||||
if !cfg.WithPrefix {
|
||||
prefix := fmt.Sprintf("%s/", cfg.PathPrefix)
|
||||
endpoint = strings.TrimPrefix(req.URL.Path, prefix)
|
||||
}
|
||||
ctx := request.NewContext(req, writer, endpoint)
|
||||
|
||||
err := next.Handle(ctx)
|
||||
if err != nil {
|
||||
logger.Error(req.Context(), errors.WithMessage(err, "uncaught error"))
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type HttpError interface {
|
||||
WriteError(w http.ResponseWriter) error
|
||||
}
|
||||
|
||||
func ErrorHandler(logger log.Logger) Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx *request.Context) error {
|
||||
err := next.Handle(ctx)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Error(ctx.Context(), err)
|
||||
|
||||
httpErr, ok := err.(HttpError)
|
||||
if ok {
|
||||
return httpErr.WriteError(ctx.ResponseWriter())
|
||||
}
|
||||
|
||||
return httperrors.
|
||||
New(http.StatusInternalServerError, "internal service error", err).
|
||||
WriteError(ctx.ResponseWriter())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/integration-system/isp-kit/http/endpoint/buffer"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type scSource interface {
|
||||
StatusCode() int
|
||||
}
|
||||
|
||||
type writerWrapper struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *writerWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
upstream, ok := w.ResponseWriter.(http.Hijacker)
|
||||
if !ok {
|
||||
return nil, nil, errors.New("writerWrapper: upstream writer doesn't implement Hijack")
|
||||
}
|
||||
return upstream.Hijack()
|
||||
}
|
||||
|
||||
func (w *writerWrapper) StatusCode() int {
|
||||
if w.statusCode == 0 {
|
||||
return http.StatusOK
|
||||
}
|
||||
return w.statusCode
|
||||
}
|
||||
|
||||
func (w *writerWrapper) WriteHeader(statusCode int) {
|
||||
w.statusCode = statusCode
|
||||
w.ResponseWriter.WriteHeader(statusCode)
|
||||
}
|
||||
|
||||
func Logger(
|
||||
logger log.Logger,
|
||||
enableRequestLogging bool,
|
||||
enableBodyLogging bool,
|
||||
skipBodyLoggingEndpointPrefixes []string,
|
||||
) Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx *request.Context) error {
|
||||
if !enableRequestLogging {
|
||||
return next.Handle(ctx)
|
||||
}
|
||||
|
||||
r := ctx.Request()
|
||||
|
||||
logBodyFromCurrenRequest := enableBodyLogging
|
||||
if logBodyFromCurrenRequest {
|
||||
for _, prefix := range skipBodyLoggingEndpointPrefixes {
|
||||
if strings.HasPrefix(ctx.Endpoint(), prefix) {
|
||||
logBodyFromCurrenRequest = false
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var scSrc scSource
|
||||
var buf *buffer.Buffer
|
||||
if logBodyFromCurrenRequest {
|
||||
buf = buffer.Acquire(ctx.ResponseWriter())
|
||||
defer buffer.Release(buf)
|
||||
|
||||
err := buf.ReadRequestBody(r.Body)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "logger: read request body for logging")
|
||||
}
|
||||
err = r.Body.Close()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "logger: close request reader")
|
||||
}
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(buf.RequestBody()))
|
||||
|
||||
scSrc = buf
|
||||
ctx.SetResponseWriter(buf)
|
||||
} else {
|
||||
writer := &writerWrapper{ResponseWriter: ctx.ResponseWriter()}
|
||||
scSrc = writer
|
||||
ctx.SetResponseWriter(writer)
|
||||
}
|
||||
|
||||
originalPath := r.URL.Path //
|
||||
// can be changed in http proxy
|
||||
err := next.Handle(ctx)
|
||||
|
||||
authData, _ := ctx.GetAuthData()
|
||||
fields := []log.Field{
|
||||
log.String("http_method", r.Method),
|
||||
log.String("remote_addr", r.RemoteAddr),
|
||||
log.String("x_forwarded_for", r.Header.Get("X-Forwarded-For")),
|
||||
log.Int("status_code", scSrc.StatusCode()),
|
||||
log.String("path", originalPath),
|
||||
log.String("endpoint", ctx.Endpoint()),
|
||||
log.Int("application_id", authData.ApplicationId),
|
||||
log.Int("admin_id", ctx.AdminId()),
|
||||
}
|
||||
|
||||
if logBodyFromCurrenRequest {
|
||||
fields = append(fields,
|
||||
log.ByteString("request", buf.RequestBody()),
|
||||
log.ByteString("response", buf.ResponseBody()),
|
||||
)
|
||||
}
|
||||
logger.Debug(ctx.Context(), "log request", fields...)
|
||||
|
||||
return err
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type Handler interface {
|
||||
Handle(ctx *request.Context) error
|
||||
}
|
||||
|
||||
type HandlerFunc func(ctx *request.Context) error
|
||||
|
||||
func (f HandlerFunc) Handle(ctx *request.Context) error {
|
||||
return f(ctx)
|
||||
}
|
||||
|
||||
type Middleware func(next Handler) Handler
|
||||
|
||||
func Chain(root Handler, middlewares ...Middleware) Handler {
|
||||
for i := len(middlewares) - 1; i >= 0; i-- {
|
||||
root = middlewares[i](root)
|
||||
}
|
||||
return root
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/integration-system/isp-kit/requestid"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
const (
|
||||
requestIdHeader = "x-request-id"
|
||||
)
|
||||
|
||||
func RequestId() Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx *request.Context) error {
|
||||
requestId := strings.TrimSpace(ctx.Request().Header.Get(requestIdHeader))
|
||||
if requestId == "" {
|
||||
requestId = requestid.Next()
|
||||
}
|
||||
|
||||
context := requestid.ToContext(ctx.Context(), requestId)
|
||||
context = log.ToContext(context, log.String("requestId", requestId))
|
||||
|
||||
ctx.SetContext(context)
|
||||
|
||||
return next.Handle(ctx)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/domain"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type Throttler interface {
|
||||
AllowRateLimit(ctx context.Context, applicationId int) (*domain.RateLimitResult, error)
|
||||
}
|
||||
|
||||
func Throttling(throttler Throttler) Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx *request.Context) error {
|
||||
authData, err := ctx.GetAuthData()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "throttling: get auth data")
|
||||
}
|
||||
|
||||
result, err := throttler.AllowRateLimit(ctx.Context(), authData.ApplicationId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "throttling: allow rate limit")
|
||||
}
|
||||
if !result.Allow {
|
||||
return httperrors.New(
|
||||
http.StatusTooManyRequests,
|
||||
fmt.Sprintf("rate limit has been reached, try after %dms", result.RetryAfter.Milliseconds()),
|
||||
errors.Errorf("throttling: rate limit has been reached for application '%d'", authData.ApplicationId),
|
||||
)
|
||||
}
|
||||
|
||||
return next.Handle(ctx)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user