Security Resources

⌘K
  1. Home
  2. Security Resources
  3. Secure Code Explain
  4. gRPC Interceptor Authorization and Protobuf Validation

gRPC Interceptor Authorization and Protobuf Validation

Here is an example of a Go gRPC service implementation that performs authorization ad-hoc inside business handlers rather than enforcing uniform interceptor-level authorization:

🥺 Vulnerable Code

// Vulnerable: Ad-hoc authorization inside individual gRPC method handlers
package main

import (
    "context"
    "errors"
    pb "company.com/payment/proto"
)

type PaymentServer struct {
    pb.UnimplementedPaymentServiceServer
}

// Vulnerable: Developer forgot to check authorization tokens in this handler!
func (s *PaymentServer) TransferFunds(ctx context.Context, req *pb.TransferRequest) (*pb.TransferResponse, error) {
    // Missing auth check: directly processes payment transaction!
    return processTransfer(req.AccountID, req.Amount)
}

// In another handler, auth was remembered:
func (s *PaymentServer) RefundFunds(ctx context.Context, req *pb.RefundRequest) (*pb.RefundResponse, error) {
    token := extractToken(ctx)
    if !validateToken(token) {
        return nil, errors.New("unauthorized")
    }
    return processRefund(req.TransactionID)
}

Performing authorization manually inside individual gRPC RPC methods leads to authorization drift. When developers add new RPC endpoints or modify existing services, omitting a single authorization check exposes sensitive internal business methods directly to unauthenticated microservices or external clients. Additionally, lack of message validation allows malformed or negative financial amounts to enter processing logic.

😎 Secure Code

Here is the secure implementation enforcing centralized UnaryServerInterceptor authentication and Protobuf message validation:

// Secure: Centralized UnaryServerInterceptor enforcing uniform auth and Protobuf validation
package main

import (
    "context"
    "strings"
    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/metadata"
    "google.golang.org/grpc/status"
    pb "company.com/payment/proto"
)

// Explicit whitelist of public RPC methods that bypass authentication
var publicMethods = map[string]bool{
    "/payment.PaymentService/HealthCheck": true,
}

// AuthInterceptor enforces authentication uniformly across all RPC methods
func AuthInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    // Skip auth for explicitly registered public methods
    if publicMethods[info.FullMethod] {
        return handler(ctx, req)
    }

    md, ok := metadata.FromIncomingContext(ctx)
    if !ok {
        return nil, status.Errorf(codes.Unauthenticated, "metadata missing")
    }

    authHeader := md.Get("authorization")
    if len(authHeader) == 0 || !strings.HasPrefix(authHeader[0], "Bearer ") {
        return nil, status.Errorf(codes.Unauthenticated, "valid bearer token required")
    }

    token := strings.TrimPrefix(authHeader[0], "Bearer ")
    claims, err := validateJWT(token)
    if err != nil {
        return nil, status.Errorf(codes.Unauthenticated, "invalid token: %v", err)
    }

    // Attach validated identity to context
    newCtx := context.WithValue(ctx, "user_claims", claims)

    // Execute message-level Protobuf validation (e.g., protoc-gen-validate)
    if validator, ok := req.(interface{ Validate() error }); ok {
        if err := validator.Validate(); err != nil {
            return nil, status.Errorf(codes.InvalidArgument, "validation failed: %v", err)
        }
    }

    return handler(newCtx, req)
}

func main() {
    // Register interceptor globally on gRPC server
    server := grpc.NewServer(
        grpc.UnaryInterceptor(AuthInterceptor),
    )
    pb.RegisterPaymentServiceServer(server, &PaymentServer{})
}

The gRPC UnaryServerInterceptor centralizes authorization, executing before any business handler is reached. By implementing a default-deny architecture with an explicit public method whitelist, newly added RPC methods are protected by default. In addition, the interceptor automatically executes Protobuf validation rules, rejecting invalid or malicious payload parameters with codes.InvalidArgument before execution.