github.com/cilium/cilium@v1.16.2/pkg/hubble/metrics/policy/handler_test.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package policy
     5  
     6  import (
     7  	"context"
     8  	"strings"
     9  	"testing"
    10  
    11  	"github.com/prometheus/client_golang/prometheus"
    12  	"github.com/prometheus/client_golang/prometheus/testutil"
    13  	"github.com/stretchr/testify/assert"
    14  
    15  	flowpb "github.com/cilium/cilium/api/v1/flow"
    16  	"github.com/cilium/cilium/pkg/hubble/metrics/api"
    17  	"github.com/cilium/cilium/pkg/identity"
    18  	monitorAPI "github.com/cilium/cilium/pkg/monitor/api"
    19  )
    20  
    21  func TestPolicyHandler(t *testing.T) {
    22  	registry := prometheus.NewRegistry()
    23  	h := &policyHandler{}
    24  	assert.NoError(t, h.Init(registry, api.Options{}))
    25  	assert.NoError(t, testutil.CollectAndCompare(h.verdicts, strings.NewReader("")))
    26  	flow := flowpb.Flow{
    27  		EventType:        &flowpb.CiliumEventType{Type: monitorAPI.MessageTypePolicyVerdict},
    28  		TrafficDirection: flowpb.TrafficDirection_EGRESS,
    29  		PolicyMatchType:  monitorAPI.PolicyMatchNone,
    30  		Verdict:          flowpb.Verdict_DROPPED,
    31  	}
    32  
    33  	h.ProcessFlow(context.Background(), &flow)
    34  	flow.TrafficDirection = flowpb.TrafficDirection_INGRESS
    35  	flow.PolicyMatchType = monitorAPI.PolicyMatchL3L4
    36  	flow.Verdict = flowpb.Verdict_REDIRECTED
    37  	h.ProcessFlow(context.Background(), &flow)
    38  
    39  	// Policy verdicts from host shouldn't be counted.
    40  	flow.PolicyMatchType = monitorAPI.PolicyMatchAll
    41  	flow.Source = &flowpb.Endpoint{Identity: uint32(identity.ReservedIdentityHost)}
    42  	h.ProcessFlow(context.Background(), &flow)
    43  
    44  	// l7/http
    45  	flow.EventType = &flowpb.CiliumEventType{Type: monitorAPI.MessageTypeAccessLog}
    46  	flow.Verdict = flowpb.Verdict_DROPPED
    47  	flow.L7 = &flowpb.Layer7{
    48  		Record: &flowpb.Layer7_Http{Http: &flowpb.HTTP{
    49  			Code:     0,
    50  			Method:   "POST",
    51  			Url:      "http://myhost/some/path",
    52  			Protocol: "http/1.1",
    53  		}}}
    54  	h.ProcessFlow(context.Background(), &flow)
    55  
    56  	expected := strings.NewReader(`# HELP hubble_policy_verdicts_total Total number of Cilium network policy verdicts
    57  # TYPE hubble_policy_verdicts_total counter
    58  hubble_policy_verdicts_total{action="dropped",direction="egress",match="none"} 1
    59  hubble_policy_verdicts_total{action="redirected",direction="ingress",match="l3-l4"} 1
    60  hubble_policy_verdicts_total{action="dropped",direction="ingress",match="l7/http"} 1
    61  `)
    62  	assert.NoError(t, testutil.CollectAndCompare(h.verdicts, expected))
    63  }