Testing gRPC Interceptors: Middleware, Auth, and Logging Patterns

Testing gRPC Interceptors: Middleware, Auth, and Logging Patterns

gRPC interceptors are middleware that wrap every RPC call — they're where authentication, logging, rate limiting, and distributed tracing live. But they're rarely tested in isolation. Most teams only discover interceptor bugs when they ship a service that ignores auth headers or double-logs requests.

This guide covers how to test gRPC interceptors independently of the service logic they wrap, in both Go and Python.

What Interceptors Do

In gRPC, interceptors sit between the transport layer and your service handler:

Client Request
    ↓
[Auth Interceptor]
    ↓
[Logging Interceptor]
    ↓
[Rate Limit Interceptor]
    ↓
Service Handler
    ↑
[Logging Interceptor]  (also wraps response)
    ↑
Client Response

Server-side interceptors come in two forms:

  • Unary interceptors — wrap single request/response RPCs
  • Stream interceptors — wrap streaming RPCs

Testing gRPC Interceptors in Go

The Interceptor Interface

A unary server interceptor in Go has this signature:

type UnaryServerInterceptor func(
    ctx context.Context,
    req interface{},
    info *grpc.UnaryServerInfo,
    handler grpc.UnaryHandler,
) (interface{}, error)

You can test it directly — no server required.

Testing an Auth Interceptor

// auth_interceptor.go
package interceptors

import (
    "context"
    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/metadata"
    "google.golang.org/grpc/status"
)

func AuthInterceptor(validToken string) grpc.UnaryServerInterceptor {
    return func(
        ctx context.Context,
        req interface{},
        info *grpc.UnaryServerInfo,
        handler grpc.UnaryHandler,
    ) (interface{}, error) {
        md, ok := metadata.FromIncomingContext(ctx)
        if !ok {
            return nil, status.Error(codes.Unauthenticated, "missing metadata")
        }
        
        tokens := md.Get("authorization")
        if len(tokens) == 0 {
            return nil, status.Error(codes.Unauthenticated, "missing authorization token")
        }
        
        if tokens[0] != "Bearer "+validToken {
            return nil, status.Error(codes.PermissionDenied, "invalid token")
        }
        
        return handler(ctx, req)
    }
}
// auth_interceptor_test.go
package interceptors_test

import (
    "context"
    "testing"
    
    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/metadata"
    "google.golang.org/grpc/status"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

// noopHandler is a handler that always succeeds
func noopHandler(_ context.Context, req interface{}) (interface{}, error) {
    return "ok", nil
}

func TestAuthInterceptor_ValidToken(t *testing.T) {
    interceptor := AuthInterceptor("secret-token")
    
    ctx := metadata.NewIncomingContext(
        context.Background(),
        metadata.Pairs("authorization", "Bearer secret-token"),
    )
    
    resp, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{}, noopHandler)
    
    require.NoError(t, err)
    assert.Equal(t, "ok", resp)
}

func TestAuthInterceptor_MissingToken(t *testing.T) {
    interceptor := AuthInterceptor("secret-token")
    
    ctx := metadata.NewIncomingContext(context.Background(), metadata.MD{})
    
    _, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{}, noopHandler)
    
    require.Error(t, err)
    st, _ := status.FromError(err)
    assert.Equal(t, codes.Unauthenticated, st.Code())
}

func TestAuthInterceptor_InvalidToken(t *testing.T) {
    interceptor := AuthInterceptor("secret-token")
    
    ctx := metadata.NewIncomingContext(
        context.Background(),
        metadata.Pairs("authorization", "Bearer wrong-token"),
    )
    
    _, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{}, noopHandler)
    
    require.Error(t, err)
    st, _ := status.FromError(err)
    assert.Equal(t, codes.PermissionDenied, st.Code())
}

func TestAuthInterceptor_MissingMetadata(t *testing.T) {
    interceptor := AuthInterceptor("secret-token")
    
    // Context with no metadata at all
    _, err := interceptor(context.Background(), nil, &grpc.UnaryServerInfo{}, noopHandler)
    
    require.Error(t, err)
    st, _ := status.FromError(err)
    assert.Equal(t, codes.Unauthenticated, st.Code())
}

func TestAuthInterceptor_PassesRequestToHandler(t *testing.T) {
    interceptor := AuthInterceptor("secret-token")
    
    ctx := metadata.NewIncomingContext(
        context.Background(),
        metadata.Pairs("authorization", "Bearer secret-token"),
    )
    
    var receivedReq interface{}
    captureHandler := func(_ context.Context, req interface{}) (interface{}, error) {
        receivedReq = req
        return "response", nil
    }
    
    req := "test-request"
    _, err := interceptor(ctx, req, &grpc.UnaryServerInfo{}, captureHandler)
    
    require.NoError(t, err)
    assert.Equal(t, "test-request", receivedReq)
}

Testing a Logging Interceptor

// logging_interceptor_test.go
package interceptors_test

import (
    "bytes"
    "context"
    "testing"
    "log"
    
    "github.com/stretchr/testify/assert"
)

func TestLoggingInterceptor_LogsMethodName(t *testing.T) {
    var buf bytes.Buffer
    logger := log.New(&buf, "", 0)
    
    interceptor := LoggingInterceptor(logger)
    
    info := &grpc.UnaryServerInfo{FullMethod: "/mypackage.MyService/MyMethod"}
    _, err := interceptor(context.Background(), nil, info, noopHandler)
    
    assert.NoError(t, err)
    assert.Contains(t, buf.String(), "/mypackage.MyService/MyMethod")
}

func TestLoggingInterceptor_LogsErrorOnHandlerFailure(t *testing.T) {
    var buf bytes.Buffer
    logger := log.New(&buf, "", 0)
    
    interceptor := LoggingInterceptor(logger)
    
    errorHandler := func(_ context.Context, req interface{}) (interface{}, error) {
        return nil, status.Error(codes.NotFound, "resource not found")
    }
    
    info := &grpc.UnaryServerInfo{FullMethod: "/mypackage.MyService/GetItem"}
    _, err := interceptor(context.Background(), nil, info, errorHandler)
    
    assert.Error(t, err)
    assert.Contains(t, buf.String(), "NotFound")
}

Testing Interceptor Chaining

func TestInterceptorChain_ExecutesInOrder(t *testing.T) {
    var order []string
    
    first := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
        order = append(order, "first")
        resp, err := handler(ctx, req)
        order = append(order, "first-after")
        return resp, err
    }
    
    second := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
        order = append(order, "second")
        resp, err := handler(ctx, req)
        order = append(order, "second-after")
        return resp, err
    }
    
    chain := ChainUnaryInterceptors(first, second)
    chain(context.Background(), nil, &grpc.UnaryServerInfo{}, noopHandler)
    
    assert.Equal(t, []string{"first", "second", "first-after", "second-after"}, order)
}

Testing gRPC Interceptors in Python

Python uses the grpcio library. Interceptors implement the grpc.ServerInterceptor abstract class:

# auth_interceptor.py
import grpc
from typing import Callable, Any

class AuthInterceptor(grpc.ServerInterceptor):
    def __init__(self, valid_token: str):
        self._valid_token = valid_token
    
    def intercept_service(self, continuation: Callable, handler_call_details):
        metadata = dict(handler_call_details.invocation_metadata)
        auth = metadata.get("authorization", "")
        
        if not auth:
            def abort(request, context):
                context.abort(grpc.StatusCode.UNAUTHENTICATED, "missing authorization")
            return grpc.unary_unary_rpc_method_handler(abort)
        
        if auth != f"Bearer {self._valid_token}":
            def abort(request, context):
                context.abort(grpc.StatusCode.PERMISSION_DENIED, "invalid token")
            return grpc.unary_unary_rpc_method_handler(abort)
        
        return continuation(handler_call_details)
# test_auth_interceptor.py
import pytest
import grpc
from unittest.mock import MagicMock, patch
from auth_interceptor import AuthInterceptor

class MockHandlerCallDetails:
    def __init__(self, metadata: dict):
        self.method = "/test.Service/Method"
        self.invocation_metadata = list(metadata.items())

def make_continuation():
    """Return a continuation that passes through to a noop handler."""
    handler = grpc.unary_unary_rpc_method_handler(
        lambda request, context: "ok"
    )
    return lambda _: handler

def test_valid_token_passes_to_handler():
    interceptor = AuthInterceptor("secret-token")
    details = MockHandlerCallDetails({"authorization": "Bearer secret-token"})
    continuation = make_continuation()
    
    result = interceptor.intercept_service(continuation, details)
    
    # Should return the original handler, not an abort handler
    assert result is not None
    mock_context = MagicMock()
    response = result.unary_unary(None, mock_context)
    assert response == "ok"

def test_missing_token_aborts():
    interceptor = AuthInterceptor("secret-token")
    details = MockHandlerCallDetails({})  # No auth header
    continuation = make_continuation()
    
    result = interceptor.intercept_service(continuation, details)
    
    mock_context = MagicMock()
    result.unary_unary(None, mock_context)
    
    mock_context.abort.assert_called_once_with(
        grpc.StatusCode.UNAUTHENTICATED,
        "missing authorization"
    )

def test_invalid_token_aborts():
    interceptor = AuthInterceptor("secret-token")
    details = MockHandlerCallDetails({"authorization": "Bearer wrong"})
    continuation = make_continuation()
    
    result = interceptor.intercept_service(continuation, details)
    
    mock_context = MagicMock()
    result.unary_unary(None, mock_context)
    
    mock_context.abort.assert_called_once_with(
        grpc.StatusCode.PERMISSION_DENIED,
        "invalid token"
    )

Integration Testing Interceptors with a Real Server

For end-to-end verification, spin up a minimal gRPC server with the interceptor and test against it:

// auth_interceptor_integration_test.go
package interceptors_test

import (
    "context"
    "net"
    "testing"
    
    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/metadata"
    "google.golang.org/grpc/status"
    pb "myproject/proto"
)

func TestAuthInterceptor_Integration(t *testing.T) {
    // Start a real gRPC server with the interceptor
    lis, err := net.Listen("tcp", "localhost:0")
    if err != nil {
        t.Fatal(err)
    }
    
    server := grpc.NewServer(
        grpc.UnaryInterceptor(AuthInterceptor("test-token")),
    )
    pb.RegisterGreeterServer(server, &mockGreeterServer{})
    
    go server.Serve(lis)
    defer server.Stop()
    
    // Connect a client
    conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
    if err != nil {
        t.Fatal(err)
    }
    defer conn.Close()
    
    client := pb.NewGreeterClient(conn)
    
    t.Run("valid token succeeds", func(t *testing.T) {
        ctx := metadata.AppendToOutgoingContext(
            context.Background(),
            "authorization", "Bearer test-token",
        )
        _, err := client.SayHello(ctx, &pb.HelloRequest{Name: "world"})
        require.NoError(t, err)
    })
    
    t.Run("no token fails with Unauthenticated", func(t *testing.T) {
        _, err := client.SayHello(context.Background(), &pb.HelloRequest{Name: "world"})
        require.Error(t, err)
        st, _ := status.FromError(err)
        assert.Equal(t, codes.Unauthenticated, st.Code())
    })
}

Testing Rate Limiting Interceptors

func TestRateLimitInterceptor_BlocksAfterLimit(t *testing.T) {
    interceptor := RateLimitInterceptor(3) // Allow 3 requests per second
    
    info := &grpc.UnaryServerInfo{FullMethod: "/test.Service/Method"}
    ctx := context.Background()
    
    // First 3 requests should succeed
    for i := 0; i < 3; i++ {
        _, err := interceptor(ctx, nil, info, noopHandler)
        assert.NoError(t, err, "request %d should succeed", i+1)
    }
    
    // 4th request should be rate limited
    _, err := interceptor(ctx, nil, info, noopHandler)
    require.Error(t, err)
    st, _ := status.FromError(err)
    assert.Equal(t, codes.ResourceExhausted, st.Code())
}

CI Configuration

# .github/workflows/grpc-tests.yml
- name: Test gRPC interceptors
  run: go test ./interceptors/... -v -race -count=1

The -race flag is important for interceptors — they run concurrently and race conditions are a common bug.

Conclusion

Testing gRPC interceptors in isolation is faster and more precise than testing them through full service integration tests. The key technique: pass a captured handler function to test what reaches (or doesn't reach) the service, and use real metadata contexts to test auth flows. Unit test the interceptor logic, then add one integration test that verifies the interceptor is wired correctly to the server.

Read more

Start now free