package db import ( "database/sql" "encoding/base64" "errors" "fmt" "strings" "testing" ) // openProxyPool opens the test database with an empty proxy_pool, and empties // it again at the end. It skips when the table holds entries that are not // fixtures of this file: the limit test counts rows. func openProxyPool(t *testing.T) *DB { t.Helper() d, err := Open(testDSN(t)) if err != nil { SkipPGUnavailable(t, err) } clean := func() { d.Exec(`DELETE FROM proxy_pool WHERE label LIKE 't-pp-%'`) } clean() t.Cleanup(func() { clean(); d.Close() }) var others int if err := d.QueryRow(`SELECT count(*) FROM proxy_pool`).Scan(&others); err != nil { t.Fatal(err) } if others > 0 { t.Skipf("proxy_pool holds %d entr(ies) that are not test fixtures — skipping", others) } return d } func TestNormalizeProxyAddress(t *testing.T) { ok := map[string]string{ "http://proxy.example": "http://proxy.example:80", " HTTP://Proxy.Example:3128/ ": "http://proxy.example:3128", "https://u:p%40ss@proxy.example": "https://u:p%40ss@proxy.example:443", "socks5://user@10.0.0.1": "socks5://user@10.0.0.1:1080", "socks5://[2001:db8::1]:9050": "socks5://[2001:db8::1]:9050", "http://CaseUser:CasePass@h.example:8": "http://CaseUser:CasePass@h.example:8", "http://h.example:080": "http://h.example:80", } for in, want := range ok { got, err := NormalizeProxyAddress(in) if err != nil || got != want { t.Errorf("NormalizeProxyAddress(%q) = %q, %v; want %q", in, got, err, want) } } for _, in := range []string{"", "proxy.example:3128", "ftp://proxy.example", "socks4://p.example", "http://", "http://p.example/path", "http://p.example?x=1", "http://p.example#f", "http://p.example:", "http://p.example:0", "http://p.example:65536", "http://p.example:abc", "mailto:x@y"} { if got, err := NormalizeProxyAddress(in); !errors.Is(err, ErrProxyPoolInvalid) { t.Errorf("NormalizeProxyAddress(%q) = %q, %v; want ErrProxyPoolInvalid", in, got, err) } } } // The address is sealed at rest, never in clear in either column, and read // back in clear; an entry is created inactive. func TestProxyPoolCRUDSealed(t *testing.T) { d := openProxyPool(t) const secret = "pp-sealed-pass-0001" e, err := d.CreateProxyPoolEntry(" t-pp-one ", "HTTP://user:"+secret+"@Proxy.Example:3128", true) if err != nil { t.Fatal(err) } if e.Label != "t-pp-one" || e.Address != "http://user:"+secret+"@proxy.example:3128" || !e.Enabled || e.Active { t.Fatalf("created entry = %+v", e) } var addr, hash string if err := d.QueryRow(`SELECT address, address_hash FROM proxy_pool WHERE id=$1`, e.ID).Scan(&addr, &hash); err != nil { t.Fatal(err) } if !isEncrypted(addr) || strings.Contains(addr+hash, secret) || strings.Contains(hash, "proxy.example") { t.Fatalf("address not sealed at rest: address=%q hash=%q", addr, hash) } got, err := d.GetProxyPoolEntry(e.ID) if err != nil || got.Address != e.Address { t.Fatalf("get = %+v, %v", got, err) } label, other, off := "t-pp-renamed", "socks5://other.example:1080", false up, err := d.UpdateProxyPoolEntry(e.ID, ProxyPoolEdit{Label: &label}) if err != nil || up.Label != label || up.Address != e.Address { t.Fatalf("label-only update = %+v, %v", up, err) } up, err = d.UpdateProxyPoolEntry(e.ID, ProxyPoolEdit{Address: &other, Enabled: &off}) if err != nil || up.Address != other || up.Enabled || up.Label != label { t.Fatalf("address update = %+v, %v", up, err) } var newHash string if err := d.QueryRow(`SELECT address_hash FROM proxy_pool WHERE id=$1`, e.ID).Scan(&newHash); err != nil || newHash == hash { t.Fatalf("address change did not change the hash (%v)", err) } list, err := d.ListProxyPool() if err != nil || len(list) != 1 || list[0].ID != e.ID { t.Fatalf("list = %+v, %v", list, err) } if err := d.DeleteProxyPoolEntry(e.ID); err != nil { t.Fatal(err) } if _, err := d.GetProxyPoolEntry(e.ID); !errors.Is(err, sql.ErrNoRows) { t.Fatalf("get after delete: %v", err) } } // A never-checked entry scans its NULL check columns as nil; a checked one // reads them back. func TestProxyPoolNullCheckColumnsScan(t *testing.T) { d := openProxyPool(t) e, err := d.CreateProxyPoolEntry("t-pp-null", "http://null.example:3128", true) if err != nil { t.Fatal(err) } if e.EgressIP != nil || e.LastCheckAt != nil || e.LastCheckOK != nil { t.Fatalf("never-checked entry = %+v", e) } if _, err := d.Exec(`UPDATE proxy_pool SET egress_ip='203.0.113.7', last_check_at=now(), last_check_ok=true WHERE id=$1`, e.ID); err != nil { t.Fatal(err) } list, err := d.ListProxyPool() if err != nil || len(list) != 1 { t.Fatalf("list = %+v, %v", list, err) } if g := list[0]; g.EgressIP == nil || *g.EgressIP != "203.0.113.7" || g.LastCheckAt == nil || g.LastCheckOK == nil || !*g.LastCheckOK { t.Fatalf("checked entry = %+v", g) } } func TestProxyPoolUnknownIDs(t *testing.T) { d := openProxyPool(t) label := "t-pp-ghost" if _, err := d.UpdateProxyPoolEntry(1<<62, ProxyPoolEdit{Label: &label}); !errors.Is(err, sql.ErrNoRows) { t.Fatalf("update unknown id: %v", err) } if err := d.DeleteProxyPoolEntry(1 << 62); !errors.Is(err, sql.ErrNoRows) { t.Fatalf("delete unknown id: %v", err) } if _, err := d.GetProxyPoolEntry(1 << 62); !errors.Is(err, sql.ErrNoRows) { t.Fatalf("get unknown id: %v", err) } } // Uniqueness is on the normalized address, credentials included. func TestProxyPoolDuplicateAddress(t *testing.T) { d := openProxyPool(t) a, err := d.CreateProxyPoolEntry("t-pp-a", "http://u:p@dup.example", true) if err != nil { t.Fatal(err) } if _, err := d.CreateProxyPoolEntry("t-pp-b", "HTTP://u:p@DUP.example:80/", true); !errors.Is(err, ErrProxyPoolDuplicate) { t.Fatalf("same normalized address: %v", err) } if _, err := d.CreateProxyPoolEntry("t-pp-b2", "http://u:p@dup.example:0080", true); !errors.Is(err, ErrProxyPoolDuplicate) { t.Fatalf("same port spelled with leading zeros: %v", err) } b, err := d.CreateProxyPoolEntry("t-pp-c", "http://u:other@dup.example", true) if err != nil { t.Fatalf("other credentials are another entry: %v", err) } same := "http://u:p@dup.example:80" if _, err := d.UpdateProxyPoolEntry(b.ID, ProxyPoolEdit{Address: &same}); !errors.Is(err, ErrProxyPoolDuplicate) { t.Fatalf("update onto an existing address: %v", err) } if _, err := d.UpdateProxyPoolEntry(a.ID, ProxyPoolEdit{Address: &same}); err != nil { t.Fatalf("re-saving an entry's own address: %v", err) } } func TestProxyPoolValidation(t *testing.T) { d := openProxyPool(t) for _, c := range []struct{ label, addr string }{{"", "http://v.example"}, {" ", "http://v.example"}, {"t-pp-" + strings.Repeat("x", MaxProxyPoolLabelRunes), "http://v.example"}, {"t-pp-v", "v.example:3128"}} { if _, err := d.CreateProxyPoolEntry(c.label, c.addr, true); !errors.Is(err, ErrProxyPoolInvalid) { t.Errorf("create(%q, %q): %v", c.label, c.addr, err) } } } // The schema keeps at most one active entry, and only an enabled one; the // store refuses to disable or delete the active entry. func TestProxyPoolActiveConstraints(t *testing.T) { d := openProxyPool(t) a, err := d.CreateProxyPoolEntry("t-pp-act-a", "http://a.example", true) if err != nil { t.Fatal(err) } b, err := d.CreateProxyPoolEntry("t-pp-act-b", "http://b.example", true) if err != nil { t.Fatal(err) } c, err := d.CreateProxyPoolEntry("t-pp-act-c", "http://c.example", false) if err != nil { t.Fatal(err) } if _, err := d.Exec(`UPDATE proxy_pool SET active=true WHERE id=$1`, a.ID); err != nil { t.Fatal(err) } if _, err := d.Exec(`UPDATE proxy_pool SET active=true WHERE id=$1`, b.ID); err == nil { t.Fatal("a second active entry was accepted") } if _, err := d.Exec(`UPDATE proxy_pool SET active=true WHERE id=$1`, c.ID); err == nil { t.Fatal("a disabled entry was made active") } if _, err := d.Exec(`UPDATE proxy_pool SET enabled=false WHERE id=$1`, a.ID); err == nil { t.Fatal("the active entry was disabled") } off := false if _, err := d.UpdateProxyPoolEntry(a.ID, ProxyPoolEdit{Enabled: &off}); !errors.Is(err, ErrProxyPoolActive) { t.Fatalf("disable active entry: %v", err) } if err := d.DeleteProxyPoolEntry(a.ID); !errors.Is(err, ErrProxyPoolActive) { t.Fatalf("delete active entry: %v", err) } label := "t-pp-act-a2" if _, err := d.UpdateProxyPoolEntry(a.ID, ProxyPoolEdit{Label: &label}); err != nil { t.Fatalf("relabel active entry: %v", err) } } func TestProxyPoolLimit(t *testing.T) { d := openProxyPool(t) for i := 0; i < MaxProxyPoolEntries; i++ { if _, err := d.Exec(`INSERT INTO proxy_pool(label, address, address_hash) VALUES ('t-pp-lim', '', $1)`, fmt.Sprint("lim-", i)); err != nil { t.Fatal(err) } } if _, err := d.CreateProxyPoolEntry("t-pp-over", "http://over.example", true); !errors.Is(err, ErrProxyPoolLimit) { t.Fatalf("create past the limit: %v", err) } } // A pool address sealed under another key fails the startup key check. func TestProxyPoolAddressInStartupKeyCheck(t *testing.T) { d := openProxyPool(t) other, _ := newSecretBox([]byte("ffffffffffffffffffffffffffffffff")) v, err := other.encrypt(colProxyPoolAddress.aad(), "http://other.example:3128") if err != nil { t.Fatal(err) } if _, err := d.Exec(`INSERT INTO proxy_pool(label, address, address_hash) VALUES ('t-pp-wrongkey', $1, 'wrongkey')`, v); err != nil { t.Fatal(err) } t.Setenv(secretKeyEnv, base64.StdEncoding.EncodeToString(testSecretKey)) if err := d.InitSecrets(t.TempDir()); err == nil || !strings.Contains(err.Error(), "proxy_pool.address") { t.Fatalf("want a key-check failure on proxy_pool.address, got %v", err) } }