2023-02-15 02:52:11 +01:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
|
|
|
|
"github.com/zitadel/zitadel/internal/api/authz"
|
|
|
|
"github.com/zitadel/zitadel/internal/errors"
|
|
|
|
"github.com/zitadel/zitadel/internal/logstore"
|
2023-09-15 16:58:45 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/logstore/record"
|
2023-02-15 02:52:11 +01:00
|
|
|
"github.com/zitadel/zitadel/internal/telemetry/tracing"
|
|
|
|
)
|
|
|
|
|
2023-09-15 16:58:45 +02:00
|
|
|
func QuotaExhaustedInterceptor(svc *logstore.Service[*record.AccessLog], ignoreService ...string) grpc.UnaryServerInterceptor {
|
2023-02-15 02:52:11 +01:00
|
|
|
for idx, service := range ignoreService {
|
|
|
|
if !strings.HasPrefix(service, "/") {
|
2023-09-15 16:58:45 +02:00
|
|
|
ignoreService[idx] = "/" + service
|
2023-02-15 02:52:11 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
|
|
|
|
if !svc.Enabled() {
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
interceptorCtx, span := tracing.NewServerInterceptorSpan(ctx)
|
|
|
|
defer func() { span.EndWithError(err) }()
|
|
|
|
|
2023-09-15 16:58:45 +02:00
|
|
|
// The auth interceptor will ensure that only authorized or public requests are allowed.
|
|
|
|
// So if there's no authorization context, we don't need to check for limitation
|
|
|
|
if authz.GetCtxData(ctx).IsZero() {
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, service := range ignoreService {
|
2023-02-15 02:52:11 +01:00
|
|
|
if strings.HasPrefix(info.FullMethod, service) {
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
instance := authz.GetInstance(ctx)
|
|
|
|
remaining := svc.Limit(interceptorCtx, instance.InstanceID())
|
|
|
|
if remaining != nil && *remaining == 0 {
|
|
|
|
return nil, errors.ThrowResourceExhausted(nil, "QUOTA-vjAy8", "Quota.Access.Exhausted")
|
|
|
|
}
|
|
|
|
span.End()
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
}
|