Use Trim(Prefix/Suffix) instead of Trim(Left/Right) in rewrite prefix plugin (#2364) (#2372)

This commit is contained in:
Daniel Garcia
2018-12-06 16:10:46 -06:00
committed by Miek Gieben
parent fc667b98e0
commit 4a3f5cc41e
2 changed files with 38 additions and 23 deletions

View File

@@ -80,7 +80,7 @@ func (rule *prefixNameRule) Rewrite(ctx context.Context, state request.Request)
// Rewrite rewrites the current request when the name ends with the matching string. // Rewrite rewrites the current request when the name ends with the matching string.
func (rule *suffixNameRule) Rewrite(ctx context.Context, state request.Request) Result { func (rule *suffixNameRule) Rewrite(ctx context.Context, state request.Request) Result {
if strings.HasSuffix(state.Name(), rule.Suffix) { if strings.HasSuffix(state.Name(), rule.Suffix) {
state.Req.Question[0].Name = strings.TrimRight(state.Name(), rule.Suffix) + rule.Replacement state.Req.Question[0].Name = strings.TrimSuffix(state.Name(), rule.Suffix) + rule.Replacement
return RewriteDone return RewriteDone
} }
return RewriteIgnored return RewriteIgnored

View File

@@ -32,8 +32,24 @@ func TestRewriteIllegalName(t *testing.T) {
} }
} }
func TestRewriteNamePrefix(t *testing.T) { func TestRewriteNamePrefixSuffix(t *testing.T) {
r, err := newNameRule("stop", "prefix", "test", "not-a-test")
ctx, close := context.WithCancel(context.TODO())
defer close()
tests := []struct {
next string
args []string
question string
expected string
}{
{"stop", []string{"prefix", "foo", "bar"}, "foo.example.com.", "bar.example.com."},
{"stop", []string{"prefix", "foo.", "bar."}, "foo.example.com.", "bar.example.com."},
{"stop", []string{"suffix", "com", "org"}, "foo.example.com.", "foo.example.org."},
{"stop", []string{"suffix", ".com", ".org"}, "foo.example.com.", "foo.example.org."},
}
for _, tc := range tests {
r, err := newNameRule(tc.next, tc.args...)
if err != nil { if err != nil {
t.Fatalf("Expected no error, got %s", err) t.Fatalf("Expected no error, got %s", err)
} }
@@ -44,19 +60,18 @@ func TestRewriteNamePrefix(t *testing.T) {
noRevert: true, noRevert: true,
} }
ctx := context.TODO()
m := new(dns.Msg) m := new(dns.Msg)
m.SetQuestion("test.example.org.", dns.TypeA) m.SetQuestion(tc.question, dns.TypeA)
rec := dnstest.NewRecorder(&test.ResponseWriter{}) rec := dnstest.NewRecorder(&test.ResponseWriter{})
_, err = rw.ServeDNS(ctx, rec, m) _, err = rw.ServeDNS(ctx, rec, m)
if err != nil { if err != nil {
t.Fatalf("Expected no error, got %s", err) t.Fatalf("Expected no error, got %s", err)
} }
expected := "not-a-test.example.org."
actual := rec.Msg.Question[0].Name actual := rec.Msg.Question[0].Name
if actual != expected { if actual != tc.expected {
t.Fatalf("Expected rewrite to %v, got %v", expected, actual) t.Fatalf("Expected rewrite to %v, got %v", tc.expected, actual)
}
} }
} }