Skip to content

Commit

Permalink
Iptables mock
Browse files Browse the repository at this point in the history
  • Loading branch information
Joseph Chen committed Dec 21, 2023
1 parent e0e0411 commit 6007b05
Show file tree
Hide file tree
Showing 2 changed files with 225 additions and 99 deletions.
24 changes: 22 additions & 2 deletions pkg/iptableswrapper/mocks/iptables_maps.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package mock_iptableswrapper
import (
"fmt"
"reflect"
"slices"
"strings"

"github.com/pkg/errors"
Expand Down Expand Up @@ -44,7 +45,12 @@ func (ipt *MockIptables) Insert(table, chain string, pos int, rulespec ...string
if ipt.DataplaneState[table] == nil {
ipt.DataplaneState[table] = map[string][][]string{}
}
ipt.DataplaneState[table][chain] = append(ipt.DataplaneState[table][chain], rulespec)
if len(ipt.DataplaneState[table][chain]) == pos-1 {
ipt.DataplaneState[table][chain] = append(ipt.DataplaneState[table][chain], rulespec)
} else {
ipt.DataplaneState[table][chain] = append(ipt.DataplaneState[table][chain][:pos], ipt.DataplaneState[table][chain][pos-1:]...)
ipt.DataplaneState[table][chain][pos] = rulespec
}
return nil
}

Expand Down Expand Up @@ -91,6 +97,10 @@ func (ipt *MockIptables) List(table, chain string) ([]string, error) {
var chains []string
chainContents := ipt.DataplaneState[table][chain]
for _, ruleSpec := range chainContents {
if slices.Contains(ruleSpec, "-N") {
chains = append(chains, strings.Join(ruleSpec, " "))
continue
}
sanitizedRuleSpec := []string{"-A", chain}
for _, item := range ruleSpec {
if strings.Contains(item, " ") {
Expand All @@ -101,10 +111,14 @@ func (ipt *MockIptables) List(table, chain string) ([]string, error) {
chains = append(chains, strings.Join(sanitizedRuleSpec, " "))
}
return chains, nil

}

func (ipt *MockIptables) NewChain(table, chain string) error {
exists, _ := ipt.ChainExists(table, chain)
if exists {
return errors.New("Chain already exists")
}
ipt.Append(table, chain, "-N", chain)
return nil
}

Expand All @@ -113,6 +127,12 @@ func (ipt *MockIptables) ClearChain(table, chain string) error {
}

func (ipt *MockIptables) DeleteChain(table, chain string) error {
// More than just the create chain rule
if len(ipt.DataplaneState[table][chain]) > 1 {
err := fmt.Sprintf("Chain %s is not empty", chain)
return errors.New(err)
}
delete(ipt.DataplaneState[table], chain)
return nil
}

Expand Down
Loading

0 comments on commit 6007b05

Please sign in to comment.