Compare commits

...
Author SHA1 Message Date
BaaRai a50008822f fix: reject malformed intercept domains and align the IDN profile
exact_domain and domain_suffix patterns are now checked before they are
stored: whitespace or control characters, empty labels (including more
than one trailing dot), a single label, an IP literal or all-digit last
label, and a non-ASCII or xn-- label the IDNA profile refuses are answered
400 on the global and task rule APIs. fuzzy_domain refuses whitespace,
control characters and a doubled dot. Valid domains keep the canonical
form they had, and CanonicalInterceptDomain stays lenient for matching.

intercept/target.go now uses idna.Lookup, the profile the rules use. The
previous profile had the same options in x/net v0.62.0; its comment said
it accepted underscore labels, which it did not.
2026-12-02 12:28:31 +01:00
9 changed files with 629 additions and 18 deletions
+1
View File
@@ -16,6 +16,7 @@ All notable changes to this project are documented in this file. The format is b
### Fixed
- **An `exact_ip` task allow rule grants sandbox egress**: the egress allowlist read task allow rules of kind `ip`, which the rule tables never store, so an `exact_ip` allow rule granted nothing. A task scoped to one private address (`10.0.0.5`) could not reach it from the sandbox, directly or through a name resolving only to it. `exact_ip` allow rules now join the allowed CIDRs as a host prefix, like `cidr` allow rules.
- **Malformed domain patterns are refused on asset interception rules.** `exact_domain` and `domain_suffix` patterns (global rules, task rules, task creation and task templates) are now answered 400 when they contain whitespace or a control character, an empty label (`a..example.com`, a leading dot, or more than one trailing dot: `example.com..` used to be stored as `example.com.`, which no target matches), a single label (`com`), an IP literal or an all-digit last label (`192.0.2.1`, `127.1`; use `exact_ip` or `cidr`), or a non-ASCII or `xn--` label the IDNA profile refuses (`_bücher.example`), which has no single canonical spelling. `fuzzy_domain` patterns refuse whitespace, control characters and a doubled dot, and keep leading and trailing dots and single labels (`.gov.cn`). Valid domains are stored exactly as before, and the matcher still canonicalizes targets leniently. Existing rows are not migrated. The intercept layer now uses `idna.Lookup` for target names, the profile the rules use; the previous profile had the same options, so target normalisation does not change, and its comment wrongly said it accepted underscore labels: both profiles refuse them, and such a name is compared lower-cased as written.
- **`GET /api/tasks/{id}/scope` reports scope approval**: the query behind it did not select `approved_by_operator` or `expanded`, so every row came back with `approved_by_operator: false` and `expanded: false`, including operator-approved rows that grant sandbox egress. The rows now carry both columns as stored, for the task's own scope and for its source tasks' scope.
- **The OpenAI Responses format no longer defaults to `gpt-5`**: OpenAI shuts `gpt-5` down on 2026-12-11 and lists `gpt-6.2-sol` as its replacement, so `ARTEX_LLM_PROVIDER=openai-responses` without `ARTEX_LLM_MODEL` (or a profile saved through the API without a model) would start failing then. The default is now `gpt-6.2-sol`; a model set in the profile or in `ARTEX_LLM_MODEL` is kept as is. A gateway set with `ARTEX_LLM_BASE_URL` that does not serve `gpt-6.2-sol` needs `ARTEX_LLM_MODEL` set explicitly.
- **`start.sh` stops during a crash backoff**: a SIGTERM or SIGINT that arrived while the supervisor slept before a restart was handled only after the sleep, and the loop then started `artex` again and waited on it, so `docker stop` waited out its grace period and SIGKILLed a freshly started server. The backoff sleep can now be interrupted, and the loop checks for a pending stop before each launch. `scripts/test-start-sh.sh` covers it in CI.
+45
View File
@@ -0,0 +1,45 @@
package db
import "testing"
// CanonicalInterceptDomain is the comparison form of both a stored rule and a
// target. Its output for valid names must not move, and it must stay lenient:
// a malformed target still has to meet the rules (the built-in fuzzy ".gov.cn"
// rule must still hit "x..gov.cn").
func TestCanonicalInterceptDomainUnchanged(t *testing.T) {
cases := []struct {
in string
want string
}{
{"example.com", "example.com"},
{"Example.COM.", "example.com"},
{" www.Example.com ", "www.example.com"},
{"bücher.example", "xn--bcher-kva.example"},
{"XN--BCHER-KVA.example", "xn--bcher-kva.example"},
{"example.com", "example.com"},
{"faß.de", "xn--fa-hia.de"},
{"_dmarc.Example.com", "_dmarc.example.com"},
{".gov.cn", ".gov.cn"},
{" .GOV.CN. ", ".gov.cn"},
// Not valid rule patterns, but still canonicalized (not emptied) as
// targets.
{"a..example.com", "a..example.com"},
{"example.com..", "example.com."},
{"com", "com"},
{"192.0.2.1", "192.0.2.1"},
{"_bücher.example.com", "_bücher.example.com"},
}
for _, c := range cases {
if got := CanonicalInterceptDomain(c.in); got != c.want {
t.Errorf("CanonicalInterceptDomain(%q) = %q, want %q", c.in, got, c.want)
}
}
rules := []AssetInterceptRule{rule("fuzzy_domain", ".gov.cn", true)}
if _, _, hit := MatchAssetInterceptRules(rules, []string{"x..gov.cn"}, nil, nil); !hit {
t.Fatal(`fuzzy ".gov.cn" no longer hits the malformed target "x..gov.cn"`)
}
rules = []AssetInterceptRule{rule("exact_domain", "example.com", true)}
if _, _, hit := MatchAssetInterceptRules(rules, []string{"EXAMPLE.com."}, nil, nil); !hit {
t.Fatal(`exact "example.com" no longer hits "EXAMPLE.com."`)
}
}
+184
View File
@@ -0,0 +1,184 @@
package db
import "testing"
// Malformed exact_domain / domain_suffix patterns are refused before they are
// stored instead of being kept in a form no target ever has.
func TestValidInterceptDomainRefuses(t *testing.T) {
cases := []struct {
name string
pattern string
}{
{"empty", ""},
{"blank", " "},
{"bare dot", "."},
{"two trailing dots", "example.com.."},
{"three trailing dots", "example.com..."},
{"doubled dot", "a..example.com"},
{"doubled dot before the TLD", "example..com"},
{"leading dot", ".example.com"},
{"space inside", "a b.example.com"},
{"tab inside", "a\tb.example.com"},
{"newline inside", "example.com\nevil.net"},
{"NUL inside", "a\x00b.example.com"},
{"DEL inside", "a\x7fb.example.com"},
{"C1 control inside", "a\u0085b.example.com"},
{"no-break space inside", "a b.example.com"},
{"NUL at the end", "example.com\x00"},
{"single label", "com"},
{"single label with trailing dot", "COM."},
{"single label host", "localhost"},
{"IPv4 literal", "192.0.2.1"},
{"IPv4 literal with trailing dot", "192.0.2.1."},
{"IPv6 literal", "2001:db8::1"},
{"IPv6 loopback", "::1"},
{"IPv6 with zone", "fe80::1%eth0"},
{"short IPv4 form", "127.1"},
{"all-digit last label", "1.2.3.4.5"},
{"underscore in a Unicode label", "_bücher.example.com"},
{"punycode of an underscore label", "xn--_bcher-4ya.example.com"},
{"invalid punycode label", "xn--zz.example.com"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got, err := ValidInterceptDomain(c.pattern); err == nil {
t.Fatalf("ValidInterceptDomain(%q) = %q, want an error", c.pattern, got)
}
// As a domain_suffix, one leading dot is the suffix spelling.
if c.pattern == ".example.com" {
return
}
if got, err := ValidDomainSuffixPattern(c.pattern); err == nil {
t.Fatalf("ValidDomainSuffixPattern(%q) = %q, want an error", c.pattern, got)
}
})
}
}
// A valid domain keeps exactly the canonical form it had before the check:
// ValidInterceptDomain returns what CanonicalInterceptDomain returns.
func TestValidInterceptDomainKeepsValidDomains(t *testing.T) {
cases := []struct {
pattern string
want string
}{
{"example.com", "example.com"},
{"Example.COM", "example.com"},
{"Example.COM.", "example.com"},
{" example.com ", "example.com"},
{"www.example.com", "www.example.com"},
{"a.b.c.example.co.uk", "a.b.c.example.co.uk"},
{"API.Example.Org.", "api.example.org"},
{"bücher.example", "xn--bcher-kva.example"},
{"BÜCHER.Example.", "xn--bcher-kva.example"},
{"xn--bcher-kva.example", "xn--bcher-kva.example"},
{"XN--BCHER-KVA.EXAMPLE", "xn--bcher-kva.example"},
{"shop.xn--bcher-kva.example", "shop.xn--bcher-kva.example"},
{"example.com", "example.com"},
{"faß.de", "xn--fa-hia.de"},
{"例え.テスト", "xn--r8jz45g.xn--zckzah"},
{"_dmarc.example.com", "_dmarc.example.com"},
{"_DMARC.Example.com.", "_dmarc.example.com"},
{"my_host.internal", "my_host.internal"},
{"rr1---sn-abc.googlevideo.com", "rr1---sn-abc.googlevideo.com"},
{"ab--c.example.com", "ab--c.example.com"},
{"-a.example.com", "-a.example.com"},
{"1.example.com", "1.example.com"},
{"123.example.com", "123.example.com"},
{"example.123a", "example.123a"},
}
for _, c := range cases {
t.Run(c.pattern, func(t *testing.T) {
got, err := ValidInterceptDomain(c.pattern)
if err != nil {
t.Fatalf("ValidInterceptDomain(%q) refused: %v", c.pattern, err)
}
if got != c.want {
t.Fatalf("ValidInterceptDomain(%q) = %q, want %q", c.pattern, got, c.want)
}
if canon := CanonicalInterceptDomain(c.pattern); canon != got {
t.Fatalf("ValidInterceptDomain(%q) = %q but CanonicalInterceptDomain = %q", c.pattern, got, canon)
}
})
}
}
func TestValidDomainSuffixPattern(t *testing.T) {
cases := []struct {
pattern string
want string
wantErr bool
}{
{"example.com", "example.com", false},
{"*.Example.COM.", "example.com", false},
{".example.com", "example.com", false},
{"*.bücher.example", "xn--bcher-kva.example", false},
{"*.com", "", true},
{".com", "", true},
{"*.example.com..", "", true},
{"..example.com", "", true},
{"*..example.com", "", true},
{"*.a b.example.com", "", true},
{"*.192.0.2.1", "", true},
{"*.", "", true},
}
for _, c := range cases {
t.Run(c.pattern, func(t *testing.T) {
got, err := ValidDomainSuffixPattern(c.pattern)
if c.wantErr {
if err == nil {
t.Fatalf("ValidDomainSuffixPattern(%q) = %q, want an error", c.pattern, got)
}
return
}
if err != nil {
t.Fatalf("ValidDomainSuffixPattern(%q) refused: %v", c.pattern, err)
}
if got != c.want || got != DomainSuffixPattern(c.pattern) {
t.Fatalf("ValidDomainSuffixPattern(%q) = %q, want %q (DomainSuffixPattern %q)", c.pattern, got, c.want, DomainSuffixPattern(c.pattern))
}
})
}
}
// A fuzzy pattern is a substring: leading/trailing dots and single labels stay
// valid, the built-in ".gov" rules included.
func TestValidFuzzyDomainPattern(t *testing.T) {
cases := []struct {
pattern string
want string
wantErr bool
}{
{".gov", ".gov", false},
{".gov.cn", ".gov.cn", false},
{" .GOV.CN. ", ".gov.cn", false},
{"example", "example", false},
{"EXAMPLE.COM.", "example.com", false},
{"bücher", "xn--bcher-kva", false},
{"", "", true},
{".", "", true},
{"a..b", "", true},
{"..gov", "", true},
{"example.com..", "", true},
{"a b", "", true},
{"gov\x00", "", true},
{"ex\tample", "", true},
}
for _, c := range cases {
t.Run(c.pattern, func(t *testing.T) {
got, err := ValidFuzzyDomainPattern(c.pattern)
if c.wantErr {
if err == nil {
t.Fatalf("ValidFuzzyDomainPattern(%q) = %q, want an error", c.pattern, got)
}
return
}
if err != nil {
t.Fatalf("ValidFuzzyDomainPattern(%q) refused: %v", c.pattern, err)
}
if got != c.want {
t.Fatalf("ValidFuzzyDomainPattern(%q) = %q, want %q", c.pattern, got, c.want)
}
})
}
}
+116 -8
View File
@@ -6,6 +6,7 @@ import (
"net/netip"
"net/url"
"strings"
"unicode"
"golang.org/x/net/idna"
)
@@ -20,28 +21,135 @@ import (
// map, such as a fuzzy pattern with a leading dot, is compared as written).
// Targets are canonicalized by the intercept layer with the same spelling, so a
// rule stored as "Example.COM." must still match "example.com".
//
// It never refuses a name: the matcher calls it on targets too, and a malformed
// target must still meet the rules. Patterns are checked before they are stored
// by ValidInterceptDomain.
//
// The IDNA profile is idna.Lookup, the one intercept.NormalizeTarget uses. It
// applies the STD3 rules, so a label with an underscore ("_dmarc.example.com")
// is refused by the profile and the name is compared lower-cased as written.
func CanonicalInterceptDomain(s string) string {
d := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(s)), ".")
d, _ := canonicalInterceptDomain(s)
return d
}
// canonicalInterceptDomain is CanonicalInterceptDomain; mapped is false when
// the IDNA profile refused the name and it was kept as written.
func canonicalInterceptDomain(s string) (d string, mapped bool) {
d = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(s)), ".")
if d == "" {
return ""
return "", false
}
if ascii, err := idna.Lookup.ToASCII(d); err == nil && ascii != "" {
return ascii
return ascii, true
}
return d
return d, false
}
// ValidInterceptDomain checks an exact_domain pattern (and the domain of a
// domain_suffix pattern) before it is stored, and returns the canonical form,
// which is always CanonicalInterceptDomain's. It refuses:
// - whitespace or a control character inside the name;
// - an empty label: a leading dot, "a..example.com", or more than one
// trailing dot ("example.com.." is refused, not shortened: one trailing
// dot is the DNS root, a second one is a typo, and the intercept layer
// drops only one);
// - a single label ("com"): it is not a host and would match nothing;
// - an IP literal, or a name whose last label is all digits: IPs are
// exact_ip or cidr rules, and the intercept layer reads such a host as
// an address;
// - a name with non-ASCII characters, or an "xn--" label, that the IDNA
// profile refuses (for example an underscore in an internationalized
// label): such a name has no single canonical spelling, so a rule written
// in Unicode would miss the punycode target and the reverse.
//
// An ASCII name without an "xn--" label that the profile refuses (an
// underscore, a leading or trailing hyphen, "--" in the third and fourth
// positions) is kept lower-cased as written, as before: lower-casing is all the
// profile would do to it, so the rule and the target spell it the same way.
func ValidInterceptDomain(s string) (string, error) {
for _, r := range strings.TrimSpace(s) {
if unicode.IsSpace(r) || unicode.IsControl(r) {
return "", fmt.Errorf("contains whitespace or a control character")
}
}
d, mapped := canonicalInterceptDomain(s)
if d == "" {
return "", fmt.Errorf("empty domain")
}
if _, err := netip.ParseAddr(d); err == nil {
return "", fmt.Errorf("is an IP address (use exact_ip or cidr)")
}
labels := strings.Split(d, ".")
for _, l := range labels {
if l == "" {
return "", fmt.Errorf("has an empty label (leading, doubled or extra trailing dot)")
}
}
if len(labels) < 2 {
return "", fmt.Errorf("is a single label, not a domain (e.g. example.com)")
}
if strings.Trim(labels[len(labels)-1], "0123456789") == "" {
return "", fmt.Errorf("looks like an IP address (use exact_ip or cidr)")
}
if !mapped {
for _, r := range d {
if r > unicode.MaxASCII {
return "", fmt.Errorf("is not a valid internationalized domain name")
}
}
for _, l := range labels {
if strings.HasPrefix(l, "xn--") {
return "", fmt.Errorf("has an invalid punycode label: %s", l)
}
}
}
return d, nil
}
// ValidFuzzyDomainPattern checks a fuzzy_domain pattern before it is stored and
// returns its canonical form. A fuzzy pattern is a substring, so a leading or
// trailing dot and a single label stay valid (".gov.cn", "example"); whitespace,
// control characters and an empty label inside it ("a..b") are refused.
func ValidFuzzyDomainPattern(s string) (string, error) {
t := strings.TrimSpace(s)
for _, r := range t {
if unicode.IsSpace(r) || unicode.IsControl(r) {
return "", fmt.Errorf("contains whitespace or a control character")
}
}
if strings.Contains(t, "..") {
return "", fmt.Errorf("has an empty label (doubled dot)")
}
d := CanonicalInterceptDomain(t)
if d == "" {
return "", fmt.Errorf("empty domain")
}
return d, nil
}
// DomainSuffixPattern canonicalizes a domain_suffix pattern: the domain itself,
// with one leading "*." or "." dropped, so "*.Example.com" and ".example.com"
// both mean example.com and its subdomains. Empty when nothing is left.
func DomainSuffixPattern(s string) string {
return CanonicalInterceptDomain(domainSuffixDomain(s))
}
// ValidDomainSuffixPattern is DomainSuffixPattern for a pattern about to be
// stored: the domain left once the prefix is dropped must pass
// ValidInterceptDomain.
func ValidDomainSuffixPattern(s string) (string, error) {
return ValidInterceptDomain(domainSuffixDomain(s))
}
// domainSuffixDomain drops one leading "*." or "." from a domain_suffix pattern.
func domainSuffixDomain(s string) string {
d := strings.TrimSpace(s)
if rest, ok := strings.CutPrefix(d, "*."); ok {
d = rest
} else {
d = strings.TrimPrefix(d, ".")
return rest
}
return CanonicalInterceptDomain(d)
return strings.TrimPrefix(d, ".")
}
// CanonicalInterceptIP canonicalizes one side of an IP comparison: IPv4-mapped
+6 -3
View File
@@ -29,9 +29,12 @@ type Target struct {
// with. A URL of another scheme without an explicit port has port 0.
var schemePorts = map[string]int{"http": 80, "https": 443, "ws": 80, "wss": 443, "ftp": 21}
// hostProfile maps a name the way a lookup does (case, width, punycode) without
// the strict rules that would refuse an underscore label.
var hostProfile = idna.New(idna.MapForLookup(), idna.BidiRule())
// hostProfile maps a name the way a lookup does (case, width, punycode). It is
// idna.Lookup, the profile db.CanonicalInterceptDomain applies to asset rules,
// so a target and a rule written the same way canonicalize the same way. It
// applies the STD3 rules: a label with an underscore is refused, and
// normalizeHost then keeps the name lower-cased as written.
var hostProfile = idna.Lookup
// NormalizeTarget parses one target written as a URL with a scheme, or as a
// host, host:port, [IPv6]:port, IP literal or CIDR. The name is lower-cased, its
+52
View File
@@ -0,0 +1,52 @@
package intercept
import (
"testing"
"github.com/Autumn-27/artex/db"
"golang.org/x/net/idna"
)
// The target side (NormalizeTarget) and the rule side
// (db.CanonicalInterceptDomain) map names with the same IDNA profile: same
// output and same refusals, underscores included.
func TestHostProfileMatchesRuleProfile(t *testing.T) {
names := []string{
"example.com", "Example.COM", "bücher.example", "BÜCHER.example",
"xn--bcher-kva.example", "XN--BCHER-KVA.example", "example.com",
"faß.de", "例え.テスト", "_dmarc.example.com", "my_host.internal",
"_bücher.example.com", "xn--_bcher-4ya.example.com", "xn--zz.example.com",
"-a.example.com", "ab--c.example.com", "a‍b.com",
}
for _, n := range names {
got, gotErr := hostProfile.ToASCII(n)
want, wantErr := idna.Lookup.ToASCII(n)
if got != want || (gotErr == nil) != (wantErr == nil) {
t.Errorf("%q: target profile %q (err %v), rule profile %q (err %v)", n, got, gotErr, want, wantErr)
}
}
}
// A rule stored in any spelling of a valid name blocks the target written in
// any other spelling of it.
func TestRuleAndTargetSpellingsMeet(t *testing.T) {
groups := [][]string{
{"example.com", "EXAMPLE.com.", "example.com"},
{"bücher.example", "BÜCHER.example", "xn--bcher-kva.example", "XN--BCHER-KVA.EXAMPLE."},
{"_dmarc.example.com", "_DMARC.Example.com."},
}
for _, g := range groups {
for _, ruleSpelling := range g {
rules := []db.AssetInterceptRule{{Enabled: true, Kind: "exact_domain", Pattern: db.CanonicalInterceptDomain(ruleSpelling)}}
for _, targetSpelling := range g {
tg, ok := NormalizeTarget("https://" + targetSpelling + "/")
if !ok || tg.Kind != TargetDomain {
t.Fatalf("NormalizeTarget(%q) = %+v, %v", targetSpelling, tg, ok)
}
if _, hit := blockRule(rules, &checkedTarget{Target: tg}); !hit {
t.Errorf("rule %q (stored %q) misses target %q (normalised %q)", ruleSpelling, rules[0].Pattern, targetSpelling, tg.Host)
}
}
}
}
}
+18 -7
View File
@@ -134,22 +134,33 @@ type assetInterceptRuleReq struct {
// against, so an equivalent variant cannot be stored and later fail to match a
// canonical target: domains are lower-cased, lose one trailing dot and are
// IDNA-mapped; IPs are unmapped/zone-stripped; CIDRs are masked. Malformed
// exact_ip/cidr values are rejected. URL patterns stay free text.
// exact_ip/cidr values are rejected, and so are malformed domains (see
// db.ValidInterceptDomain and db.ValidFuzzyDomainPattern). URL patterns stay
// free text.
func validateAssetInterceptRuleReq(req *assetInterceptRuleReq) error {
req.Pattern = strings.TrimSpace(req.Pattern)
if req.Pattern == "" {
return fmt.Errorf("pattern cannot be empty")
}
switch req.Kind {
case "exact_domain", "fuzzy_domain":
d := db.CanonicalInterceptDomain(req.Pattern)
if d == "" {
return fmt.Errorf("%s is not a valid domain: %s", req.Kind, req.Pattern)
case "exact_domain":
d, err := db.ValidInterceptDomain(req.Pattern)
if err != nil {
return fmt.Errorf("exact_domain is not a valid domain: %q %v", req.Pattern, err)
}
req.Pattern = d
case "fuzzy_domain":
d, err := db.ValidFuzzyDomainPattern(req.Pattern)
if err != nil {
return fmt.Errorf("fuzzy_domain is not a valid domain: %q %v", req.Pattern, err)
}
req.Pattern = d
case "domain_suffix":
d := db.DomainSuffixPattern(req.Pattern)
if d == "" || strings.ContainsAny(d, "*/:") || strings.HasPrefix(d, ".") {
d, err := db.ValidDomainSuffixPattern(req.Pattern)
if err != nil {
return fmt.Errorf("domain_suffix is not a valid domain (e.g. example.com): %q %v", req.Pattern, err)
}
if strings.ContainsAny(d, "*/:") {
return fmt.Errorf("domain_suffix is not a valid domain (e.g. example.com): %s", req.Pattern)
}
req.Pattern = d
+110
View File
@@ -0,0 +1,110 @@
package server
import (
"encoding/json"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/intercept"
)
// PG test: needs a PostgreSQL database (ARTEX_PG_DSN); skipped without one.
// A malformed domain pattern is answered 400 on the asset rule API and on the
// task rule API, and nothing is stored; a valid one is stored canonical.
func TestAssetInterceptRuleAPIRefusesMalformedDomainsPG(t *testing.T) {
dsn, _, err := db.DSN()
if err != nil {
db.SkipPGUnavailable(t, err)
}
d, err := db.Open(dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.Close() })
m := &Manager{pg: d, interceptor: intercept.New(d)}
s := &Server{m: m, jwtKey: []byte("asset-intercept-domain-test-key")}
h := s.Handler()
token, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
}
// Every pattern carries the marker label, so the rows this test could leave
// behind are easy to find and remove.
const marker = "ivx782"
stored := func() int {
t.Helper()
var n int
if err := d.QueryRow(`SELECT count(*) FROM asset_intercept_rules WHERE pattern LIKE '%' || $1 || '%'`, marker).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
t.Cleanup(func() {
_, _ = d.Exec(`DELETE FROM asset_intercept_rules WHERE pattern LIKE '%' || $1 || '%'`, marker)
})
send := func(method, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
ruleBody := func(kind, pattern string) string {
b, _ := json.Marshal(map[string]any{"enabled": true, "kind": kind, "pattern": pattern})
return string(b)
}
bad := []struct{ kind, pattern string }{
{"exact_domain", "ivx782.example.com.."},
{"exact_domain", "a..ivx782.example.com"},
{"exact_domain", "ivx782 .example.com"},
{"exact_domain", "ivx782\x00.example.com"},
{"exact_domain", "ivx782"},
{"domain_suffix", "*.ivx782.example.com.."},
{"domain_suffix", "ivx782"},
{"fuzzy_domain", "ivx782..example"},
}
before := stored()
for _, c := range bad {
rec := send("POST", "/api/asset-intercept/rules", ruleBody(c.kind, c.pattern))
if rec.Code != 400 {
t.Errorf("POST asset rule %s %q: %d %s, want 400", c.kind, c.pattern, rec.Code, rec.Body)
}
// Validation runs before the task is looked up: no task is needed.
rec = send("POST", "/api/tasks/999999999/intercept-rules", ruleBody(c.kind, c.pattern))
if rec.Code != 400 {
t.Errorf("POST task rule %s %q: %d %s, want 400", c.kind, c.pattern, rec.Code, rec.Body)
}
}
if n := stored(); n != before {
t.Fatalf("%d malformed rule(s) were stored", n-before)
}
rec := send("POST", "/api/asset-intercept/rules", ruleBody("exact_domain", "Ivx782.Example.COM."))
if rec.Code != 200 {
t.Fatalf("POST valid asset rule: %d %s", rec.Code, rec.Body)
}
var rule db.AssetInterceptRule
if err := json.Unmarshal(rec.Body.Bytes(), &rule); err != nil {
t.Fatal(err)
}
if rule.Pattern != "ivx782.example.com" {
t.Fatalf("valid rule stored as %q, want ivx782.example.com", rule.Pattern)
}
// An update with a malformed pattern is refused too, and leaves the row.
rec = send("PUT", "/api/asset-intercept/rules/"+strconv.FormatInt(rule.ID, 10), ruleBody("exact_domain", "ivx782.example.com.."))
if rec.Code != 400 {
t.Fatalf("PUT malformed asset rule: %d %s, want 400", rec.Code, rec.Body)
}
var pattern string
if err := d.QueryRow(`SELECT pattern FROM asset_intercept_rules WHERE id=$1`, rule.ID).Scan(&pattern); err != nil {
t.Fatal(err)
}
if pattern != "ivx782.example.com" {
t.Fatalf("refused update changed the row to %q", pattern)
}
}
+97
View File
@@ -55,3 +55,100 @@ func TestValidateAssetInterceptRuleCanonicalizes(t *testing.T) {
})
}
}
// Malformed domain patterns are refused at the API instead of being stored in
// a form no target has ("example.com.." used to be stored as "example.com.").
func TestValidateAssetInterceptRuleRefusesMalformedDomains(t *testing.T) {
cases := []struct {
name string
kind string
pattern string
}{
{"exact two trailing dots", "exact_domain", "example.com.."},
{"exact doubled dot", "exact_domain", "a..example.com"},
{"exact leading dot", "exact_domain", ".example.com"},
{"exact space inside", "exact_domain", "a b.example.com"},
{"exact tab inside", "exact_domain", "a\tb.example.com"},
{"exact NUL inside", "exact_domain", "a\x00b.example.com"},
{"exact newline inside", "exact_domain", "example.com\nevil.net"},
{"exact single label", "exact_domain", "com"},
{"exact single label with trailing dot", "exact_domain", "Com."},
{"exact IPv4 literal", "exact_domain", "192.0.2.1"},
{"exact IPv6 literal", "exact_domain", "2001:db8::1"},
{"exact short IPv4 form", "exact_domain", "127.1"},
{"exact underscore in a Unicode label", "exact_domain", "_bücher.example.com"},
{"exact invalid punycode label", "exact_domain", "xn--zz.example.com"},
{"suffix two trailing dots", "domain_suffix", "example.com.."},
{"suffix wildcard and two trailing dots", "domain_suffix", "*.example.com.."},
{"suffix doubled dot", "domain_suffix", "a..example.com"},
{"suffix space inside", "domain_suffix", "a b.example.com"},
{"suffix control inside", "domain_suffix", "example\x01.com"},
{"suffix single label", "domain_suffix", "com"},
{"suffix wildcard single label", "domain_suffix", "*.com"},
{"suffix IPv4 literal", "domain_suffix", "192.0.2.1"},
{"fuzzy doubled dot", "fuzzy_domain", "a..example.com"},
{"fuzzy two trailing dots", "fuzzy_domain", "example.com.."},
{"fuzzy space inside", "fuzzy_domain", ".gov .cn"},
{"fuzzy control inside", "fuzzy_domain", ".gov\x00"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
req := assetInterceptRuleReq{Enabled: true, Kind: c.kind, Pattern: c.pattern}
if err := validateAssetInterceptRuleReq(&req); err == nil {
t.Fatalf("%s %q was accepted as %q, want an error", c.kind, c.pattern, req.Pattern)
}
})
}
}
// Valid domains keep the canonical form they were stored with before.
func TestValidateAssetInterceptRuleKeepsValidDomains(t *testing.T) {
cases := []struct {
kind string
pattern string
want string
}{
{"exact_domain", "example.com", "example.com"},
{"exact_domain", "Example.COM.", "example.com"},
{"exact_domain", "api.v2.Example.co.uk", "api.v2.example.co.uk"},
{"exact_domain", "bücher.example", "xn--bcher-kva.example"},
{"exact_domain", "XN--BCHER-KVA.example", "xn--bcher-kva.example"},
{"exact_domain", "example.com", "example.com"},
{"exact_domain", "_dmarc.Example.com", "_dmarc.example.com"},
{"exact_domain", "my_host.internal", "my_host.internal"},
{"domain_suffix", "*.Example.COM.", "example.com"},
{"domain_suffix", ".shop.example.com", "shop.example.com"},
{"domain_suffix", "xn--bcher-kva.example", "xn--bcher-kva.example"},
{"fuzzy_domain", ".gov", ".gov"},
{"fuzzy_domain", ".edu.cn", ".edu.cn"},
{"fuzzy_domain", "Example", "example"},
{"fuzzy_domain", "EXAMPLE.COM.", "example.com"},
}
for _, c := range cases {
t.Run(c.kind+" "+c.pattern, func(t *testing.T) {
req := assetInterceptRuleReq{Enabled: true, Kind: c.kind, Pattern: c.pattern}
if err := validateAssetInterceptRuleReq(&req); err != nil {
t.Fatalf("%s %q was refused: %v", c.kind, c.pattern, err)
}
if req.Pattern != c.want {
t.Fatalf("%s %q normalized to %q, want %q", c.kind, c.pattern, req.Pattern, c.want)
}
})
}
}
// The task-level rules reuse the same validator (task create, rule create and
// update, templates).
func TestValidateTaskInterceptRuleRefusesMalformedDomains(t *testing.T) {
for _, p := range []string{"example.com..", "a..example.com", "com", "192.0.2.1", "a b.example.com"} {
for _, action := range []string{"block", "allow"} {
req := taskInterceptRuleReq{Enabled: true, Action: action, Kind: "domain_suffix", Pattern: p}
if err := validateTaskInterceptRuleReq(&req); err == nil {
t.Errorf("task %s domain_suffix %q was accepted as %q", action, p, req.Pattern)
}
}
}
if _, err := buildTaskInterceptRules([]taskInterceptRuleReq{{Enabled: true, Action: "allow", Kind: "exact_domain", Pattern: "example.com.."}}); err == nil {
t.Error("buildTaskInterceptRules accepted exact_domain example.com..")
}
}