github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/caveats/types_test.go (about)

     1  package caveats
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/require"
     7  
     8  	"github.com/authzed/spicedb/pkg/caveats/types"
     9  )
    10  
    11  func TestIPAddress(t *testing.T) {
    12  	compiled, err := compileCaveat(MustEnvForVariables(map[string]types.VariableType{
    13  		"user_ip": types.IPAddressType,
    14  	}), "user_ip.in_cidr('192.168.0.0/16')")
    15  	require.NoError(t, err)
    16  
    17  	parsed, _ := types.ParseIPAddress("192.168.10.10")
    18  	result, err := EvaluateCaveat(compiled, map[string]any{
    19  		"user_ip": parsed,
    20  	})
    21  	require.NoError(t, err)
    22  	require.True(t, result.Value())
    23  
    24  	parsed, _ = types.ParseIPAddress("1.2.3.4")
    25  	result, err = EvaluateCaveat(compiled, map[string]any{
    26  		"user_ip": parsed,
    27  	})
    28  	require.NoError(t, err)
    29  	require.False(t, result.Value())
    30  }
    31  
    32  func TestIPAddressInvalidCIDR(t *testing.T) {
    33  	compiled, err := compileCaveat(MustEnvForVariables(map[string]types.VariableType{
    34  		"user_ip": types.IPAddressType,
    35  	}), "user_ip.in_cidr('invalidcidr')")
    36  	require.NoError(t, err)
    37  
    38  	parsed, _ := types.ParseIPAddress("192.168.10.10")
    39  	_, err = EvaluateCaveat(compiled, map[string]any{
    40  		"user_ip": parsed,
    41  	})
    42  	require.Error(t, err)
    43  	require.Equal(t, "invalid CIDR string: `invalidcidr`", err.Error())
    44  }