Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eea0382b37 | ||
|
|
641798bb22 | ||
|
|
28ef0275ba | ||
|
|
3204b7ee4b | ||
|
|
cf50d195ad |
No files matched your search
@@ -44,8 +44,7 @@ its abuse contact. RouteWatch keeps them in its database and fetches them again
|
||||
once they are 30 days old. An IP lookup answers from the stored details and
|
||||
never waits for WHOIS.
|
||||
|
||||
An IP lookup also says which public blocklists list the address (see
|
||||
Blocklists).
|
||||
An IP lookup also says which public IP lists hold the address (see IP lists).
|
||||
|
||||
## Getting started
|
||||
|
||||
@@ -65,7 +64,7 @@ docker run --memory=5g --memory-swap=5g -p 8080:8080 \
|
||||
```
|
||||
|
||||
The memory limit is explained in Memory. The volume holds the database and the
|
||||
copies of the blocklists.
|
||||
copies of the IP lists.
|
||||
|
||||
To run the binary on the host instead, build it with `make build`. The build
|
||||
needs Go and a C compiler, because the SQLite library is written in C:
|
||||
@@ -284,8 +283,16 @@ address. Every entry has the same fields:
|
||||
- `ip`: the address
|
||||
- `ptr`: the address's PTR names, the host names that DNS gives for it, or an
|
||||
empty list when it has none
|
||||
- `blocklists`: the public blocklists the address is on (see Blocklists), or an
|
||||
empty list when it is on none
|
||||
- `flags`: yes-or-no facts about the address:
|
||||
- `is_tor`: true when the address is on the `tor_exits` list
|
||||
- `is_vpn`: true when the address is on any list of VPN servers (see IP
|
||||
lists)
|
||||
- `is_bogon`: true when the address is reserved, so that no network should
|
||||
announce it on the internet
|
||||
- `vpn_providers`: the names of the lists of VPN servers the address is on, or
|
||||
an empty list when it is on none
|
||||
- `ip_lists`: the public IP lists the address is on (see IP lists), or an empty
|
||||
list when it is on none
|
||||
|
||||
Every other field is about the prefix in the routing table that holds the
|
||||
address. Each is null when no prefix in the routing table holds the address:
|
||||
@@ -331,7 +338,7 @@ Each PTR lookup gets 2 seconds. An address whose lookup takes longer is answered
|
||||
without PTR names.
|
||||
|
||||
A successful answer carries `Cache-Control` with a `max-age` of 15 minutes, the
|
||||
shortest blocklist interval. The answer for the caller's own address (`/ip/`) is
|
||||
shortest IP list interval. The answer for the caller's own address (`/ip/`) is
|
||||
`private`, and the others are `public`.
|
||||
|
||||
### Errors
|
||||
@@ -391,10 +398,10 @@ inline `<style>` and `<script>` blocks. Each answer's policy names a random
|
||||
value, a nonce, made for that answer. The browser applies or runs only the
|
||||
blocks that carry it.
|
||||
|
||||
## Blocklists
|
||||
## IP lists
|
||||
|
||||
An IP lookup reports which public blocklists list each address. Each entry in
|
||||
`blocklists` has:
|
||||
An IP lookup reports which public IP lists hold each address. Each entry in
|
||||
`ip_lists` has:
|
||||
|
||||
- `name`: the list's name, from the lists below
|
||||
- `description`: what being on the list means
|
||||
@@ -417,13 +424,35 @@ The lists:
|
||||
last 30 days. From
|
||||
[FireHOL](https://iplists.firehol.org/?ipset=firehol_level3), downloaded every
|
||||
3 hours.
|
||||
- `ivpn`: VPN servers run by IVPN. From
|
||||
[IVPN](https://api.ivpn.net/v5/servers.json), downloaded once a day.
|
||||
- `mullvad`: VPN servers run by Mullvad. From
|
||||
[Mullvad](https://api.mullvad.net/www/relays/all/), downloaded once a day.
|
||||
- `nordvpn`: VPN servers run by NordVPN. From
|
||||
[NordVPN](https://api.nordvpn.com/v1/servers?limit=0&fields[servers.station]&fields[servers.ipv6_station]&fields[servers.hostname]),
|
||||
downloaded once a day.
|
||||
- `pia`: VPN servers run by Private Internet Access. From
|
||||
[Private Internet Access](https://serverlist.piaservers.net/vpninfo/servers/v6),
|
||||
downloaded once a day.
|
||||
- `protonvpn`: the /24 networks that hold ProtonVPN servers. The whole /24 is
|
||||
listed because the ProtonVPN-IPs README says traffic leaves from unpublished
|
||||
addresses in it. From the public
|
||||
[ProtonVPN-IPs](https://github.com/tn3w/ProtonVPN-IPs) mirror of Proton's
|
||||
server list, downloaded once a day.
|
||||
- `protonvpn_entry`: the IPv4 and IPv6 addresses of ProtonVPN servers. From the
|
||||
same [ProtonVPN-IPs](https://github.com/tn3w/ProtonVPN-IPs) mirror, downloaded
|
||||
once a day.
|
||||
- `spamhaus_drop` and `spamhaus_dropv6`: IPv4 and IPv6 networks hijacked or
|
||||
leased by spammers or cyber criminals, according to Spamhaus. From
|
||||
[Spamhaus DROP](https://www.spamhaus.org/blocklists/do-not-route-or-peer/),
|
||||
downloaded once a day.
|
||||
- `tor_exits`: Tor exit nodes, where traffic from the Tor network leaves. From
|
||||
the [Tor Project](https://check.torproject.org/torbulkexitlist), downloaded
|
||||
- `tor_exits`: the IPv4 and IPv6 addresses of Tor exit nodes, where traffic from
|
||||
the Tor network leaves. From the Tor Project's
|
||||
[Onionoo](https://metrics.torproject.org/onionoo.html) service, downloaded
|
||||
every hour.
|
||||
- `x4bnet` and `x4bnet_v6`: IPv4 and IPv6 networks of VPN services, according to
|
||||
a community list that names no service. From
|
||||
[X4BNet](https://github.com/X4BNet/lists_vpn), downloaded once a day.
|
||||
|
||||
No list is downloaded more often than its publisher updates it or allows. Each
|
||||
can be downloaded whole without an account or a key.
|
||||
@@ -431,8 +460,8 @@ can be downloaded whole without an account or a key.
|
||||
How RouteWatch keeps the lists:
|
||||
|
||||
- It holds each list in memory, so a lookup makes no outside request.
|
||||
- It keeps a copy of each list in the `blocklists` directory of the state
|
||||
directory (see Configuration). Each copy is a file named after its list.
|
||||
- It keeps a copy of each list in the `iplists` directory of the state directory
|
||||
(see Configuration). Each copy is a file named after its list.
|
||||
- Beside each copy, a file ending in `.validators` keeps the `Last-Modified` and
|
||||
`ETag` headers the publisher sent with that copy.
|
||||
- At startup it loads each list from its copy. It downloads a list at once when
|
||||
@@ -440,7 +469,7 @@ How RouteWatch keeps the lists:
|
||||
- A download sends the copy's `Last-Modified` as `If-Modified-Since` and its
|
||||
`ETag` as `If-None-Match`. The publisher then sends the list only when it has
|
||||
changed.
|
||||
- A download fails when it takes over a minute or its file is over 16 MiB.
|
||||
- A download fails when it takes over a minute or its file is over 200 MiB.
|
||||
- When a download fails, or its file does not parse, RouteWatch keeps the
|
||||
previous copy and logs the failure. It tries again one interval later.
|
||||
|
||||
@@ -492,7 +521,7 @@ by the client. For a request from any other address, they use the address the
|
||||
request came from, whatever headers it carries. `X-Real-IP` and `True-Client-IP`
|
||||
are not read.
|
||||
|
||||
The state directory holds the database, `db.sqlite`, and the blocklist copies:
|
||||
The state directory holds the database, `db.sqlite`, and the IP list copies:
|
||||
|
||||
- macOS: `~/Library/Application Support/berlin.sneak.app.routewatch/`
|
||||
- Linux and the BSDs, as root: `/var/lib/berlin.sneak.app.routewatch/`
|
||||
@@ -647,7 +676,7 @@ The parts:
|
||||
wait starts at 15 seconds. It halves after a success, down to 1 second, and
|
||||
grows by half after a failure, up to a minute. An IP lookup that finds an AS
|
||||
with old or missing details asks the fetcher for it at once, without the wait.
|
||||
- The blocklists part downloads the blocklists and answers which lists hold an
|
||||
- The IP lists part downloads the IP lists and answers which lists hold an
|
||||
address.
|
||||
- The database maintainer checkpoints the database every 5 seconds: it folds the
|
||||
write-ahead log, where SQLite first writes changes, into the database file. It
|
||||
@@ -756,7 +785,7 @@ On `SIGTERM` or `SIGINT` the daemon stops its parts in this order:
|
||||
2. the handlers, each of which writes what it holds
|
||||
3. the WHOIS fetcher
|
||||
4. the database maintainer
|
||||
5. the blocklist downloads
|
||||
5. the IP list downloads
|
||||
6. the HTTP server
|
||||
|
||||
Last, the daemon checkpoints and closes the database. It gives all this 8
|
||||
@@ -790,10 +819,10 @@ routewatch/
|
||||
├── docs/
|
||||
│ └── message-examples.json # Examples of RIS Live messages
|
||||
├── internal/
|
||||
│ ├── blocklist/ # Public IP blocklists: downloads and lookups
|
||||
│ ├── bogon/ # Reserved prefixes and AS numbers
|
||||
│ ├── config/ # Settings from the environment
|
||||
│ ├── database/ # SQLite storage
|
||||
│ ├── iplist/ # Public IP lists: downloads and lookups
|
||||
│ ├── logger/ # Structured logging
|
||||
│ ├── metrics/ # Feed and route update figures
|
||||
│ ├── ristypes/ # The RIS Live message types
|
||||
|
||||
@@ -41,9 +41,6 @@ https://git.eeqj.de/sneak/routewatch/issues/225, also on `next`, takes the peers
|
||||
whose sessions go down together out of the table in one walk. A 24-hour run of
|
||||
`9bd0e91` on the live feed is checking whether any handler still drops updates.
|
||||
|
||||
One question waits for sneak: which fields the IP lookup answer gains
|
||||
(https://git.eeqj.de/sneak/routewatch/issues/203).
|
||||
|
||||
The order of the project's remaining work is kept on
|
||||
https://git.eeqj.de/sneak/routewatch/issues/86.
|
||||
|
||||
@@ -56,6 +53,25 @@ problem the run finds.
|
||||
|
||||
# Completed Steps
|
||||
|
||||
- 2026-11-10: the IP lookup checks the `protonvpn` list of ProtonVPN's /24
|
||||
networks and the `protonvpn_entry` list of its servers' IPv4 and IPv6
|
||||
addresses, from a public mirror of Proton's server list (closes
|
||||
https://git.eeqj.de/sneak/routewatch/issues/236).
|
||||
- 2026-11-10: the tests no longer fail when a busy host stalls for several
|
||||
seconds. Most such waits are now 15 seconds. The test of the stream's idle
|
||||
timeout runs on a fake clock (closes #240)
|
||||
- 2026-11-10: the IP lookup checks the public VPN server lists of Mullvad,
|
||||
NordVPN, Private Internet Access and IVPN, and X4BNet's community list. Each
|
||||
result has `flags.is_vpn` and `vpn_providers` (closes
|
||||
https://git.eeqj.de/sneak/routewatch/issues/235).
|
||||
- 2026-11-10: `tor_exits` comes from Onionoo, so it holds IPv6 exits and
|
||||
`is_tor` is true for them (closes
|
||||
https://git.eeqj.de/sneak/routewatch/issues/234).
|
||||
- 2026-11-10: each result of the IP lookup has a `flags` object with `is_tor`
|
||||
and `is_bogon`. The public IP lists are named `ip_lists` in the answer,
|
||||
`internal/iplist` in the code and `iplists` in the state directory. A list
|
||||
file may be up to 200 MiB (closes
|
||||
https://git.eeqj.de/sneak/routewatch/issues/233).
|
||||
- 2026-11-05: the prefix page lists the prefix's origin changes, newest first.
|
||||
The routing table records each change, and the prefix handler writes them to a
|
||||
new `origin_changes` table. The database maintainer prunes each prefix to its
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
// parseTimeLimit is how long a test waits for parseCSV to return before it
|
||||
// fails.
|
||||
const parseTimeLimit = 2 * time.Second
|
||||
const parseTimeLimit = 15 * time.Second
|
||||
|
||||
// TestParseCSVReadsTodaysLayout parses an as.csv with the country code column
|
||||
// that the source added after the description. It expects each AS with its
|
||||
|
||||
@@ -1,494 +0,0 @@
|
||||
package blocklist
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The test list's name and description, the address its good version lists,
|
||||
// and the address a newer version lists instead.
|
||||
const (
|
||||
testListName = "test_list"
|
||||
testListDescription = "On the test list"
|
||||
listedAddr = "192.0.2.1"
|
||||
goodListBody = "# A test list\n" + listedAddr + "\n"
|
||||
newListedAddr = "192.0.2.2"
|
||||
newListBody = "# A test list\n" + newListedAddr + "\n"
|
||||
)
|
||||
|
||||
// testETag is the ETag a publisher sends with a version of the test list.
|
||||
const testETag = `"v1"`
|
||||
|
||||
// maxWait is how long a test waits for the download goroutine.
|
||||
const maxWait = 10 * time.Second
|
||||
|
||||
// publisher stands in for a list's publisher. It answers every request with
|
||||
// its status and body, and keeps the headers of each request. A 200 answer
|
||||
// carries lastModified and etag, when set, as Last-Modified and ETag. As
|
||||
// from a real publisher, a request whose If-None-Match or If-Modified-Since
|
||||
// matches them is answered "not modified".
|
||||
type publisher struct {
|
||||
mu sync.Mutex
|
||||
status int
|
||||
body string
|
||||
lastModified time.Time
|
||||
etag string
|
||||
headers []http.Header
|
||||
}
|
||||
|
||||
// newPublisher starts a publisher that answers 200 with body, and returns it
|
||||
// and its URL.
|
||||
func newPublisher(t *testing.T, body string) (*publisher, string) {
|
||||
t.Helper()
|
||||
|
||||
p := &publisher{status: http.StatusOK, body: body}
|
||||
srv := httptest.NewServer(p)
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
return p, srv.URL
|
||||
}
|
||||
|
||||
func (p *publisher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
p.headers = append(p.headers, r.Header.Clone())
|
||||
|
||||
if p.status != http.StatusOK {
|
||||
w.WriteHeader(p.status)
|
||||
_, _ = io.WriteString(w, p.body)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if p.etag != "" {
|
||||
w.Header().Set(etagHeader, p.etag)
|
||||
}
|
||||
|
||||
// ServeContent sends Last-Modified unless lastModified is zero, and
|
||||
// answers "not modified" when the request's conditions match.
|
||||
http.ServeContent(w, r, testListName, p.lastModified,
|
||||
strings.NewReader(p.body))
|
||||
}
|
||||
|
||||
// answer makes the publisher answer later requests with status and body.
|
||||
func (p *publisher) answer(status int, body string) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
p.status, p.body = status, body
|
||||
}
|
||||
|
||||
// publish makes the publisher answer later requests with a version of the
|
||||
// list: body, with lastModified and etag. A zero lastModified or an empty
|
||||
// etag is not sent.
|
||||
func (p *publisher) publish(body string, lastModified time.Time, etag string) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
p.status, p.body = http.StatusOK, body
|
||||
p.lastModified, p.etag = lastModified, etag
|
||||
}
|
||||
|
||||
// requests returns the headers of the requests the publisher has had.
|
||||
func (p *publisher) requests() []http.Header {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
return append([]http.Header(nil), p.headers...)
|
||||
}
|
||||
|
||||
// testList returns a list served at url, written in format.
|
||||
func testList(url string, format Format) List {
|
||||
return List{
|
||||
Name: testListName,
|
||||
Description: testListDescription,
|
||||
URL: url,
|
||||
Interval: time.Hour,
|
||||
Format: format,
|
||||
}
|
||||
}
|
||||
|
||||
func newTestBlocklists(dir string, list List) *Blocklists {
|
||||
return New(Params{
|
||||
Dir: dir,
|
||||
Lists: []List{list},
|
||||
Logger: slog.New(slog.DiscardHandler),
|
||||
})
|
||||
}
|
||||
|
||||
// lookup looks addr up in b.
|
||||
func lookup(t *testing.T, b *Blocklists, addr string) []Listing {
|
||||
t.Helper()
|
||||
|
||||
return b.Lookup(netip.MustParseAddr(addr))
|
||||
}
|
||||
|
||||
// TestLookupFindsListedAddresses downloads a list in each format and looks
|
||||
// up addresses on it, inside its networks, and off it, in IPv4 and IPv6.
|
||||
// A listed address has one listing that names the list; any other has an
|
||||
// empty list of listings.
|
||||
func TestLookupFindsListedAddresses(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
format Format
|
||||
body string
|
||||
listed []string
|
||||
unlisted []string
|
||||
}{
|
||||
{
|
||||
name: "single addresses",
|
||||
format: FormatLines,
|
||||
body: "# comment\n192.0.2.1\n\n2001:db8::1\n",
|
||||
listed: []string{"192.0.2.1", "::ffff:192.0.2.1", "2001:db8::1"},
|
||||
unlisted: []string{"192.0.2.2", "2001:db8::2"},
|
||||
},
|
||||
{
|
||||
name: "networks",
|
||||
format: FormatLines,
|
||||
body: "# comment\n198.51.100.0/24\n2001:db8:1::/48\n",
|
||||
listed: []string{"198.51.100.0", "198.51.100.255", "2001:db8:1::5"},
|
||||
unlisted: []string{"198.51.101.0", "2001:db8:2::1"},
|
||||
},
|
||||
{
|
||||
name: "Spamhaus networks",
|
||||
format: FormatSpamhausJSON,
|
||||
body: `{"cidr":"203.0.113.0/25","sblid":"SBL1","rir":"arin"}` + "\n" +
|
||||
`{"cidr":"2001:db8:3::/48","sblid":"SBL2","rir":"ripencc"}` + "\n" +
|
||||
`{"type":"metadata","timestamp":1793074442,"records":2}` + "\n",
|
||||
listed: []string{"203.0.113.1", "2001:db8:3::1"},
|
||||
unlisted: []string{"203.0.113.200", "2001:db8:4::1"},
|
||||
},
|
||||
{
|
||||
name: "DShield networks",
|
||||
format: FormatDShield,
|
||||
body: "# DShield.org Recommended Block List\n" +
|
||||
"192.0.2.0\t192.0.2.255\t24\t327\tEXAMPLE\tUS\tNone\n",
|
||||
listed: []string{"192.0.2.0", "192.0.2.77"},
|
||||
unlisted: []string{"192.0.3.1", "2001:db8::1"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, url := newPublisher(t, tt.body)
|
||||
b := newTestBlocklists(t.TempDir(), testList(url, tt.format))
|
||||
|
||||
err := b.download(t.Context(), b.lists[0])
|
||||
if err != nil {
|
||||
t.Fatalf("download: %v", err)
|
||||
}
|
||||
|
||||
for _, addr := range tt.listed {
|
||||
listings := lookup(t, b, addr)
|
||||
if len(listings) != 1 || listings[0].Name != testListName ||
|
||||
listings[0].Description != testListDescription ||
|
||||
listings[0].Updated.IsZero() {
|
||||
t.Errorf("%s: listings %+v, want one for %s", addr,
|
||||
listings, testListName)
|
||||
}
|
||||
}
|
||||
|
||||
for _, addr := range tt.unlisted {
|
||||
listings := lookup(t, b, addr)
|
||||
if listings == nil || len(listings) != 0 {
|
||||
t.Errorf("%s: listings %#v, want an empty list", addr, listings)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFailedDownloadKeepsThePreviousCopy downloads a good version of a list,
|
||||
// then one that fails. The good copy stays in memory and on disk, and no
|
||||
// part of the failed download is left beside it.
|
||||
func TestFailedDownloadKeepsThePreviousCopy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{"server error", http.StatusInternalServerError, "unavailable"},
|
||||
{"not a list", http.StatusOK, "<!DOCTYPE html>\n<html></html>\n"},
|
||||
{
|
||||
"over the size limit", http.StatusOK,
|
||||
strings.Repeat(listedAddr+"\n", maxDownloadSize/len(listedAddr)),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
p, url := newPublisher(t, goodListBody)
|
||||
b := newTestBlocklists(dir, testList(url, FormatLines))
|
||||
|
||||
err := b.download(t.Context(), b.lists[0])
|
||||
if err != nil {
|
||||
t.Fatalf("first download: %v", err)
|
||||
}
|
||||
|
||||
before := lookup(t, b, listedAddr)
|
||||
|
||||
p.answer(tt.status, tt.body)
|
||||
|
||||
err = b.download(t.Context(), b.lists[0])
|
||||
if err == nil {
|
||||
t.Fatal("second download returned no error")
|
||||
}
|
||||
|
||||
after := lookup(t, b, listedAddr)
|
||||
if len(after) != 1 || len(before) != 1 ||
|
||||
!after[0].Updated.Equal(before[0].Updated) {
|
||||
t.Errorf("listings %+v after the failure, want %+v", after, before)
|
||||
}
|
||||
|
||||
copies := os.DirFS(dir)
|
||||
|
||||
onDisk, err := fs.ReadFile(copies, testListName)
|
||||
if err != nil || string(onDisk) != goodListBody {
|
||||
t.Errorf("copy on disk %q (%v), want %q", onDisk, err, goodListBody)
|
||||
}
|
||||
|
||||
_, err = fs.Stat(copies, testListName+downloadSuffix)
|
||||
if !errors.Is(err, fs.ErrNotExist) {
|
||||
t.Errorf("the failed download's file is still there (%v)", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRestartLoadsCopiesFromDisk downloads a list, then starts a new
|
||||
// Blocklists on the same directory, as a restart does. The new one answers
|
||||
// from the copy on disk at once, and does not download the list again while
|
||||
// the copy is younger than the list's interval.
|
||||
func TestRestartLoadsCopiesFromDisk(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
p, url := newPublisher(t, goodListBody)
|
||||
list := testList(url, FormatLines)
|
||||
|
||||
first := newTestBlocklists(dir, list)
|
||||
|
||||
err := first.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("download: %v", err)
|
||||
}
|
||||
|
||||
downloaded := lookup(t, first, listedAddr)[0].Updated
|
||||
|
||||
second := newTestBlocklists(dir, list)
|
||||
second.Start(t.Context())
|
||||
second.Stop(t.Context())
|
||||
|
||||
listings := lookup(t, second, listedAddr)
|
||||
if len(listings) != 1 ||
|
||||
listings[0].Updated.Sub(downloaded).Abs() > time.Second {
|
||||
t.Errorf("after the restart, listings %+v, want one updated at %s",
|
||||
listings, downloaded)
|
||||
}
|
||||
|
||||
if got := len(p.requests()); got != 1 {
|
||||
t.Errorf("the publisher had %d requests, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartRefreshesAnOldCopy starts on a copy older than its list's
|
||||
// interval. The list is downloaded at once, with routewatch's User-Agent and
|
||||
// the Last-Modified and ETag the publisher sent with the copy, kept on disk.
|
||||
// The publisher answers that the copy is still current, so the copy is kept
|
||||
// and marked as updated now.
|
||||
func TestStartRefreshesAnOldCopy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
p, url := newPublisher(t, goodListBody)
|
||||
list := testList(url, FormatLines)
|
||||
|
||||
lastModified := time.Now().Add(-3 * list.Interval).UTC().Truncate(time.Second)
|
||||
p.publish(goodListBody, lastModified, testETag)
|
||||
|
||||
err := newTestBlocklists(dir, list).download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("download: %v", err)
|
||||
}
|
||||
|
||||
old := time.Now().Add(-2 * list.Interval).UTC().Truncate(time.Second)
|
||||
|
||||
err = os.Chtimes(filepath.Join(dir, testListName), old, old)
|
||||
if err != nil {
|
||||
t.Fatalf("Chtimes: %v", err)
|
||||
}
|
||||
|
||||
b := newTestBlocklists(dir, list)
|
||||
b.Start(t.Context())
|
||||
|
||||
deadline := time.Now().Add(maxWait)
|
||||
for !lookup(t, b, listedAddr)[0].Updated.After(old) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("the copy was not marked updated within %s", maxWait)
|
||||
}
|
||||
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
|
||||
b.Stop(t.Context())
|
||||
|
||||
requests := p.requests()
|
||||
last := requests[len(requests)-1]
|
||||
|
||||
want := lastModified.Format(http.TimeFormat)
|
||||
if got := last.Get(ifModifiedSinceHeader); got != want {
|
||||
t.Errorf("If-Modified-Since %q, want %q", got, want)
|
||||
}
|
||||
|
||||
if got := last.Get(ifNoneMatchHeader); got != testETag {
|
||||
t.Errorf("If-None-Match %q, want %q", got, testETag)
|
||||
}
|
||||
|
||||
if got := last.Get(userAgentHeader); got != userAgent {
|
||||
t.Errorf("User-Agent %q, want %q", got, userAgent)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewVersionOlderThanTheLastDownloadReplacesTheCopy downloads a list.
|
||||
// The publisher then puts out a new version whose Last-Modified is earlier
|
||||
// than that download, as when a cache in front of the publisher passes the
|
||||
// version on late. The next download sends the Last-Modified of the copy,
|
||||
// not the time of the download, so it gets the new version.
|
||||
func TestNewVersionOlderThanTheLastDownloadReplacesTheCopy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
p, url := newPublisher(t, goodListBody)
|
||||
list := testList(url, FormatLines)
|
||||
b := newTestBlocklists(t.TempDir(), list)
|
||||
|
||||
firstVersion := time.Now().Add(-2 * list.Interval).UTC().Truncate(time.Second)
|
||||
p.publish(goodListBody, firstVersion, "")
|
||||
|
||||
err := b.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("first download: %v", err)
|
||||
}
|
||||
|
||||
p.publish(newListBody, firstVersion.Add(list.Interval), "")
|
||||
|
||||
err = b.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("second download: %v", err)
|
||||
}
|
||||
|
||||
if listings := lookup(t, b, newListedAddr); len(listings) != 1 {
|
||||
t.Errorf("%s: listings %+v, want one from the new version",
|
||||
newListedAddr, listings)
|
||||
}
|
||||
|
||||
want := firstVersion.Format(http.TimeFormat)
|
||||
if got := p.requests()[1].Get(ifModifiedSinceHeader); got != want {
|
||||
t.Errorf("If-Modified-Since %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDownloadWithoutLastModifiedOrETagSendsNoCondition downloads a list
|
||||
// twice from a publisher that sends neither Last-Modified nor ETag. Neither
|
||||
// request carries If-Modified-Since or If-None-Match, so the second download
|
||||
// gets the whole list again.
|
||||
func TestDownloadWithoutLastModifiedOrETagSendsNoCondition(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
p, url := newPublisher(t, goodListBody)
|
||||
list := testList(url, FormatLines)
|
||||
b := newTestBlocklists(t.TempDir(), list)
|
||||
|
||||
err := b.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("first download: %v", err)
|
||||
}
|
||||
|
||||
err = b.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("second download: %v", err)
|
||||
}
|
||||
|
||||
for i, request := range p.requests() {
|
||||
if request.Get(ifModifiedSinceHeader) != "" ||
|
||||
request.Get(ifNoneMatchHeader) != "" {
|
||||
t.Errorf("request %d has a condition: %v", i, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestStopCancelsADownloadInProgress stops while the publisher has not
|
||||
// answered. Stop cancels the download and returns once the download
|
||||
// goroutine has stopped.
|
||||
func TestStopCancelsADownloadInProgress(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
arrived := make(chan struct{})
|
||||
|
||||
var once sync.Once
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(
|
||||
func(_ http.ResponseWriter, r *http.Request) {
|
||||
once.Do(func() { close(arrived) })
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
b := newTestBlocklists(t.TempDir(), testList(srv.URL, FormatLines))
|
||||
b.Start(t.Context())
|
||||
|
||||
select {
|
||||
case <-arrived:
|
||||
case <-time.After(maxWait):
|
||||
t.Fatalf("no download began within %s", maxWait)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), maxWait)
|
||||
defer cancel()
|
||||
|
||||
b.Stop(ctx)
|
||||
|
||||
select {
|
||||
case <-b.done:
|
||||
default:
|
||||
t.Error("Stop returned before the download goroutine stopped")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublicListsAreComplete checks that every public list has what a
|
||||
// download and a lookup answer need, and a unique name.
|
||||
func TestPublicListsAreComplete(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
names := make(map[string]bool)
|
||||
|
||||
for _, list := range Lists() {
|
||||
if list.Name == "" || list.Description == "" || list.URL == "" ||
|
||||
list.Interval <= 0 || names[list.Name] {
|
||||
t.Errorf("list %+v is incomplete or has a name used before", list)
|
||||
}
|
||||
|
||||
names[list.Name] = true
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package blocklist
|
||||
|
||||
import "time"
|
||||
|
||||
// How often each list is downloaded. No list is downloaded more often than
|
||||
// its publisher updates it or allows.
|
||||
const (
|
||||
// DShield asks that its feeds be downloaded at most once an hour:
|
||||
// https://isc.sans.edu/feeds_doc.html
|
||||
dshieldInterval = time.Hour
|
||||
|
||||
// abuse.ch makes the list every 5 minutes and recommends a download at
|
||||
// least every 15: https://feodotracker.abuse.ch/blocklist/
|
||||
feodoTrackerInterval = 15 * time.Minute
|
||||
|
||||
// FireHOL's page for each list gives how often the list changes on
|
||||
// average: about every 5 hours for abusers and every 3 hours for level
|
||||
// 3. FireHOL sets no download limit.
|
||||
// https://iplists.firehol.org/?ipset=firehol_abusers_30d
|
||||
// https://iplists.firehol.org/?ipset=firehol_level3
|
||||
fireHOLAbusersInterval = 5 * time.Hour
|
||||
fireHOLLevel3Interval = 3 * time.Hour
|
||||
|
||||
// Spamhaus asks that DROP be downloaded at most once a day:
|
||||
// https://www.spamhaus.org/blocklists/do-not-route-or-peer/
|
||||
spamhausDROPInterval = 24 * time.Hour
|
||||
|
||||
// Tor publishes a new exit list every hour and sets no download limit:
|
||||
// https://collector.torproject.org/recent/exit-lists/
|
||||
torExitsInterval = time.Hour
|
||||
)
|
||||
|
||||
// Lists returns the public blocklists routewatch downloads. Each can be
|
||||
// downloaded whole without an account or a key. Spamhaus merged its EDROP
|
||||
// list into DROP, so DROP covers both.
|
||||
func Lists() []List {
|
||||
return []List{
|
||||
{
|
||||
Name: "dshield",
|
||||
Description: "In one of the 20 networks that DShield saw scan " +
|
||||
"the most targets in the last three days",
|
||||
URL: "https://feeds.dshield.org/block.txt",
|
||||
Interval: dshieldInterval,
|
||||
Format: FormatDShield,
|
||||
},
|
||||
{
|
||||
Name: "feodo_tracker",
|
||||
Description: "A botnet command-and-control server",
|
||||
URL: "https://feodotracker.abuse.ch/downloads/ipblocklist.txt",
|
||||
Interval: feodoTrackerInterval,
|
||||
Format: FormatLines,
|
||||
},
|
||||
{
|
||||
Name: "firehol_abusers_30d",
|
||||
Description: "Reported for comment, form or forum spam in the " +
|
||||
"last 30 days",
|
||||
URL: "https://iplists.firehol.org/files/firehol_abusers_30d.netset",
|
||||
Interval: fireHOLAbusersInterval,
|
||||
Format: FormatLines,
|
||||
},
|
||||
{
|
||||
Name: "firehol_level3",
|
||||
Description: "Reported for attacks, spyware or viruses in the " +
|
||||
"last 30 days",
|
||||
URL: "https://iplists.firehol.org/files/firehol_level3.netset",
|
||||
Interval: fireHOLLevel3Interval,
|
||||
Format: FormatLines,
|
||||
},
|
||||
{
|
||||
Name: "spamhaus_drop",
|
||||
Description: "In an IPv4 network that Spamhaus says spammers " +
|
||||
"or cyber criminals have hijacked or lease",
|
||||
URL: "https://www.spamhaus.org/drop/drop_v4.json",
|
||||
Interval: spamhausDROPInterval,
|
||||
Format: FormatSpamhausJSON,
|
||||
},
|
||||
{
|
||||
Name: "spamhaus_dropv6",
|
||||
Description: "In an IPv6 network that Spamhaus says spammers " +
|
||||
"or cyber criminals have hijacked or lease",
|
||||
URL: "https://www.spamhaus.org/drop/drop_v6.json",
|
||||
Interval: spamhausDROPInterval,
|
||||
Format: FormatSpamhausJSON,
|
||||
},
|
||||
{
|
||||
Name: "tor_exits",
|
||||
Description: "A Tor exit node, where traffic from the Tor network leaves",
|
||||
URL: "https://check.torproject.org/torbulkexitlist",
|
||||
Interval: torExitsInterval,
|
||||
Format: FormatLines,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package blocklist
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/netip"
|
||||
"strings"
|
||||
|
||||
"go4.org/netipx"
|
||||
)
|
||||
|
||||
const (
|
||||
// commentPrefix starts a comment line in a list file.
|
||||
commentPrefix = "#"
|
||||
|
||||
// networkSeparator separates the address and the mask length of a
|
||||
// network, as in 192.0.2.0/24.
|
||||
networkSeparator = "/"
|
||||
|
||||
// dshieldFieldSeparator separates the fields of a DShield line.
|
||||
dshieldFieldSeparator = "\t"
|
||||
|
||||
// spamhausMetadataType is the type of the line that ends a Spamhaus
|
||||
// file. That line holds the file's metadata and no network.
|
||||
spamhausMetadataType = "metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
errUnknownFormat = errors.New("unknown list format")
|
||||
errNoNetwork = errors.New("no network on the line")
|
||||
errBadRange = errors.New("first and last address make no range")
|
||||
)
|
||||
|
||||
// parse reads a list file written in format and returns the addresses it
|
||||
// holds. A line it cannot read fails the whole file, so a file that is not
|
||||
// the list, such as an error page, never replaces a good copy.
|
||||
func parse(r io.Reader, format Format) (*netipx.IPSet, error) {
|
||||
var builder netipx.IPSetBuilder
|
||||
|
||||
scanner := bufio.NewScanner(r)
|
||||
|
||||
for lineNumber := 1; scanner.Scan(); lineNumber++ {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" || strings.HasPrefix(line, commentPrefix) {
|
||||
continue
|
||||
}
|
||||
|
||||
err := addLine(&builder, line, format)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("line %d: %w", lineNumber, err)
|
||||
}
|
||||
}
|
||||
|
||||
err := scanner.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return builder.IPSet()
|
||||
}
|
||||
|
||||
// addLine adds the address or network on one line of a list file to builder.
|
||||
func addLine(builder *netipx.IPSetBuilder, line string, format Format) error {
|
||||
switch format {
|
||||
case FormatLines:
|
||||
return addAddressOrNetwork(builder, line)
|
||||
case FormatSpamhausJSON:
|
||||
return addSpamhausNetwork(builder, line)
|
||||
case FormatDShield:
|
||||
return addDShieldNetwork(builder, line)
|
||||
default:
|
||||
return errUnknownFormat
|
||||
}
|
||||
}
|
||||
|
||||
// addAddressOrNetwork adds an address, such as 192.0.2.1, or a network, such
|
||||
// as 192.0.2.0/24, to builder.
|
||||
func addAddressOrNetwork(builder *netipx.IPSetBuilder, text string) error {
|
||||
if strings.Contains(text, networkSeparator) {
|
||||
network, err := netip.ParsePrefix(text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
builder.AddPrefix(network)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
addr, err := netip.ParseAddr(text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
builder.Add(addr)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// addSpamhausNetwork adds the network on a line of a Spamhaus file to
|
||||
// builder. The metadata line adds nothing.
|
||||
func addSpamhausNetwork(builder *netipx.IPSetBuilder, line string) error {
|
||||
var entry struct {
|
||||
CIDR string `json:"cidr"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
err := json.Unmarshal([]byte(line), &entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if entry.Type == spamhausMetadataType {
|
||||
return nil
|
||||
}
|
||||
|
||||
network, err := netip.ParsePrefix(entry.CIDR)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
builder.AddPrefix(network)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// addDShieldNetwork adds the network on a line of a DShield file to builder.
|
||||
// The line's first two fields are the network's first and last address.
|
||||
func addDShieldNetwork(builder *netipx.IPSetBuilder, line string) error {
|
||||
firstField, rest, found := strings.Cut(line, dshieldFieldSeparator)
|
||||
if !found {
|
||||
return errNoNetwork
|
||||
}
|
||||
|
||||
lastField, _, _ := strings.Cut(rest, dshieldFieldSeparator)
|
||||
|
||||
first, err := netip.ParseAddr(firstField)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
last, err := netip.ParseAddr(lastField)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
network := netipx.IPRangeFrom(first, last)
|
||||
if !network.IsValid() {
|
||||
return errBadRange
|
||||
}
|
||||
|
||||
builder.AddRange(network)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -72,17 +72,34 @@ const (
|
||||
// lockTestPrefix is the prefix the batch writes in the checkpoint tests
|
||||
// store.
|
||||
lockTestPrefix = "192.0.2.0/24"
|
||||
// longBusyTimeoutMs is the busy timeout setLongBusyTimeout gives the
|
||||
// writing connection. A checkpoint that waits for an open read takes this
|
||||
// long.
|
||||
longBusyTimeoutMs = 30000
|
||||
// readerCheckpointLimit is how long a checkpoint, and a batch write
|
||||
// waiting for it, may take while a reader is open: well under the busy
|
||||
// timeout, which a checkpoint that waits for the reader takes.
|
||||
readerCheckpointLimit = time.Second
|
||||
// waiting for it, may take while a reader is open: well under
|
||||
// longBusyTimeoutMs, with room for a stall on a busy host.
|
||||
readerCheckpointLimit = 15 * time.Second
|
||||
// truncateCheckpointLimit is how long a checkpoint of a WAL file over
|
||||
// sqliteWALSizeLimitBytes may take to give up while a reader is open: its
|
||||
// wait for the reader plus a second, well under the busy timeout.
|
||||
// wait for the reader plus readerCheckpointLimit.
|
||||
truncateCheckpointLimit = truncateBusyTimeoutMs*time.Millisecond +
|
||||
time.Second
|
||||
readerCheckpointLimit
|
||||
)
|
||||
|
||||
// setLongBusyTimeout gives the writing connection of db longBusyTimeoutMs, so
|
||||
// that a checkpoint that waits for an open read takes far longer than a stall
|
||||
// on a busy host.
|
||||
func setLongBusyTimeout(ctx context.Context, t *testing.T, db *Database) {
|
||||
t.Helper()
|
||||
|
||||
_, err := db.writer.ExecContext(ctx,
|
||||
fmt.Sprintf("PRAGMA busy_timeout=%d", longBusyTimeoutMs))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to set the busy timeout: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConnectionPoolPragmas holds several pooled connections open at once and
|
||||
// checks each one carries the per-connection settings from the DSN, plus the
|
||||
// process-wide heap limits, and sees the new file with auto_vacuum
|
||||
@@ -579,6 +596,8 @@ func TestCheckpointDoesNotWaitForReader(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ts := time.Now().UTC()
|
||||
|
||||
setLongBusyTimeout(ctx, t, db)
|
||||
|
||||
err = db.UpdatePrefixesBatch(map[string]time.Time{"198.51.100.0/24": ts})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to store the prefix the reader reads: %v", err)
|
||||
@@ -690,6 +709,7 @@ func TestCheckpointEmptiesWALOnceNoReadIsOpen(t *testing.T) {
|
||||
}
|
||||
|
||||
fillWALPastLimit(ctx, t, db)
|
||||
setLongBusyTimeout(ctx, t, db)
|
||||
|
||||
started := time.Now()
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package blocklist
|
||||
package iplist
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -22,7 +22,7 @@ const (
|
||||
|
||||
// maxDownloadSize is the size of the largest list file accepted, in
|
||||
// bytes. The largest list, FireHOL abusers, is about 2.5 MiB.
|
||||
maxDownloadSize = 16 << 20
|
||||
maxDownloadSize = 200 << 20
|
||||
)
|
||||
|
||||
// The request headers a download sets.
|
||||
@@ -78,10 +78,10 @@ var (
|
||||
// downloads each list once its copy is older than its Interval, and a list
|
||||
// with no copy at once. The goroutine runs until Stop: the end of ctx does
|
||||
// not stop it.
|
||||
func (b *Blocklists) Start(ctx context.Context) {
|
||||
func (b *IPLists) Start(ctx context.Context) {
|
||||
err := os.MkdirAll(b.dir, dirPermissions)
|
||||
if err != nil {
|
||||
b.logger.Error("Failed to create the blocklists directory",
|
||||
b.logger.Error("Failed to create the IP lists directory",
|
||||
"dir", b.dir, "error", err)
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ func (b *Blocklists) Start(ctx context.Context) {
|
||||
for i, list := range b.lists {
|
||||
loadErr := b.loadCopy(list)
|
||||
if loadErr != nil && !errors.Is(loadErr, fs.ErrNotExist) {
|
||||
b.logger.Error("Failed to load a blocklist copy",
|
||||
b.logger.Error("Failed to load an IP list copy",
|
||||
"list", list.Name, "error", loadErr)
|
||||
}
|
||||
|
||||
@@ -104,20 +104,20 @@ func (b *Blocklists) Start(ctx context.Context) {
|
||||
b.run(ctx, nextDownload)
|
||||
}()
|
||||
|
||||
b.logger.Info("Blocklist downloads started", "dir", b.dir)
|
||||
b.logger.Info("IP list downloads started", "dir", b.dir)
|
||||
}
|
||||
|
||||
// Stop stops the downloads, cancelling one in progress, and waits until the
|
||||
// goroutine has returned or ctx ends. The copies in memory stay, so Lookup
|
||||
// still answers.
|
||||
func (b *Blocklists) Stop(ctx context.Context) {
|
||||
func (b *IPLists) Stop(ctx context.Context) {
|
||||
b.stop()
|
||||
|
||||
select {
|
||||
case <-b.done:
|
||||
b.logger.Info("Blocklist downloads stopped")
|
||||
b.logger.Info("IP list downloads stopped")
|
||||
case <-ctx.Done():
|
||||
b.logger.Warn("Stop deadline passed before the blocklist downloads " +
|
||||
b.logger.Warn("Stop deadline passed before the IP list downloads " +
|
||||
"stopped")
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,7 @@ func (b *Blocklists) Stop(ctx context.Context) {
|
||||
// run downloads each list when nextDownload says, until ctx ends. After each
|
||||
// try, whether it worked or not, the list's next download is an Interval
|
||||
// later.
|
||||
func (b *Blocklists) run(ctx context.Context, nextDownload []time.Time) {
|
||||
func (b *IPLists) run(ctx context.Context, nextDownload []time.Time) {
|
||||
defer close(b.done)
|
||||
|
||||
if len(nextDownload) == 0 {
|
||||
@@ -155,7 +155,7 @@ func (b *Blocklists) run(ctx context.Context, nextDownload []time.Time) {
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
b.logger.Error("Blocklist download failed; keeping the "+
|
||||
b.logger.Error("IP list download failed; keeping the "+
|
||||
"previous copy", "list", list.Name, "error", err)
|
||||
}
|
||||
|
||||
@@ -169,7 +169,7 @@ func (b *Blocklists) run(ctx context.Context, nextDownload []time.Time) {
|
||||
// on disk and in memory. An answer that the copy is still current marks the
|
||||
// copy as updated now. Anything else leaves the copy as it is and returns an
|
||||
// error.
|
||||
func (b *Blocklists) download(ctx context.Context, list List) error {
|
||||
func (b *IPLists) download(ctx context.Context, list List) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, downloadTimeout)
|
||||
defer cancel()
|
||||
|
||||
@@ -212,7 +212,7 @@ func (b *Blocklists) download(ctx context.Context, list List) error {
|
||||
// replaceCopy writes a new version of list, read from body, beside the list's
|
||||
// copy. Only when it parses does it replace the copy, on disk and in memory.
|
||||
// sent are the validators the publisher sent with the new version.
|
||||
func (b *Blocklists) replaceCopy(list List, body io.Reader, sent validators) error {
|
||||
func (b *IPLists) replaceCopy(list List, body io.Reader, sent validators) error {
|
||||
root, err := os.OpenRoot(b.dir)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -244,13 +244,13 @@ func (b *Blocklists) replaceCopy(list List, body io.Reader, sent validators) err
|
||||
b.setCopy(list.Name, listCopy{
|
||||
addresses: addresses, updated: time.Now().UTC(), validators: sent,
|
||||
})
|
||||
b.logger.Info("Downloaded a new version of a blocklist", "list", list.Name)
|
||||
b.logger.Info("Downloaded a new version of an IP list", "list", list.Name)
|
||||
|
||||
// Without this file, the first download after a restart asks for the
|
||||
// whole list.
|
||||
err = writeValidators(root, list.Name, sent)
|
||||
if err != nil {
|
||||
b.logger.Error("Failed to keep the validators of a blocklist copy",
|
||||
b.logger.Error("Failed to keep the validators of an IP list copy",
|
||||
"list", list.Name, "error", err)
|
||||
}
|
||||
|
||||
@@ -288,7 +288,7 @@ func writeAndParse(
|
||||
|
||||
// markCurrent records that the publisher says the list's copy is still
|
||||
// current: the copy, on disk and in memory, is marked as updated now.
|
||||
func (b *Blocklists) markCurrent(list List) error {
|
||||
func (b *IPLists) markCurrent(list List) error {
|
||||
root, err := os.OpenRoot(b.dir)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -304,7 +304,7 @@ func (b *Blocklists) markCurrent(list List) error {
|
||||
}
|
||||
|
||||
b.setUpdated(list.Name, now)
|
||||
b.logger.Debug("Blocklist copy is still current", "list", list.Name)
|
||||
b.logger.Debug("IP list copy is still current", "list", list.Name)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -312,7 +312,7 @@ func (b *Blocklists) markCurrent(list List) error {
|
||||
// loadCopy makes the list's copy on disk, with the validators kept beside it,
|
||||
// its copy in memory. The file's modification time is when the copy was
|
||||
// updated.
|
||||
func (b *Blocklists) loadCopy(list List) error {
|
||||
func (b *IPLists) loadCopy(list List) error {
|
||||
root, err := os.OpenRoot(b.dir)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package blocklist downloads public IP blocklists on a schedule, keeps the
|
||||
// last good copy of each on disk and in memory, and answers which lists
|
||||
// contain an address.
|
||||
package blocklist
|
||||
// Package iplist downloads public IP lists on a schedule, keeps the last good
|
||||
// copy of each on disk and in memory, and answers which lists contain an
|
||||
// address.
|
||||
package iplist
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -29,9 +29,36 @@ const (
|
||||
// start with the network's first and last address. Lines that start
|
||||
// with # are comments.
|
||||
FormatDShield
|
||||
|
||||
// FormatOnionooJSON is one Onionoo details document. Its relays have
|
||||
// addresses in two fields: exit_addresses, which has IPv4 only, and
|
||||
// or_addresses, which has IPv4 and IPv6, each with a port.
|
||||
FormatOnionooJSON
|
||||
|
||||
// FormatMullvadJSON is Mullvad's JSON list of relays. A relay's addresses
|
||||
// are in ipv4_addr_in, ipv6_addr_in and ipv4_v2ray.
|
||||
FormatMullvadJSON
|
||||
|
||||
// FormatNordVPNJSON is NordVPN's JSON list of servers. A server's
|
||||
// addresses are in station and ipv6_station.
|
||||
FormatNordVPNJSON
|
||||
|
||||
// FormatPIAJSON is Private Internet Access's JSON server list, then a
|
||||
// blank line and a signature. Each region's servers has lists of servers
|
||||
// by protocol, and each server has its address in ip.
|
||||
FormatPIAJSON
|
||||
|
||||
// FormatIVPNJSON is IVPN's JSON server list. The hosts of its wireguard
|
||||
// and openvpn gateways have their addresses in host and v2ray.
|
||||
FormatIVPNJSON
|
||||
|
||||
// FormatProtonVPN has one address or network per line, with comment lines
|
||||
// that start with #. Unlike FormatLines, a file with no addresses or
|
||||
// networks fails.
|
||||
FormatProtonVPN
|
||||
)
|
||||
|
||||
// List is one public blocklist.
|
||||
// List is one public IP list.
|
||||
type List struct {
|
||||
// Name names the list in lookup answers, and names its copy on disk.
|
||||
Name string
|
||||
@@ -48,6 +75,9 @@ type List struct {
|
||||
|
||||
// Format is how the list's file is written.
|
||||
Format Format
|
||||
|
||||
// VPN says that the list holds servers of VPN services.
|
||||
VPN bool
|
||||
}
|
||||
|
||||
// Listing says that a list contains an address.
|
||||
@@ -58,6 +88,10 @@ type Listing struct {
|
||||
// Updated is when routewatch last downloaded the list, or last heard from
|
||||
// its publisher that its copy was still current.
|
||||
Updated time.Time `json:"updated"`
|
||||
|
||||
// VPN says that the list holds servers of VPN services. A lookup answer
|
||||
// reports it through is_vpn and vpn_providers.
|
||||
VPN bool `json:"-"`
|
||||
}
|
||||
|
||||
// listCopy is a list's last good copy in memory.
|
||||
@@ -80,9 +114,9 @@ type Params struct {
|
||||
Logger *slog.Logger
|
||||
}
|
||||
|
||||
// Blocklists keeps a copy of each list and answers which lists contain an
|
||||
// IPLists keeps a copy of each list and answers which lists contain an
|
||||
// address. Start loads the copies from disk and starts downloading the lists.
|
||||
type Blocklists struct {
|
||||
type IPLists struct {
|
||||
dir string
|
||||
lists []List
|
||||
logger *slog.Logger
|
||||
@@ -97,12 +131,12 @@ type Blocklists struct {
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// New returns a Blocklists with no copies. Start loads them.
|
||||
func New(params Params) *Blocklists {
|
||||
return &Blocklists{
|
||||
// New returns an IPLists with no copies. Start loads them.
|
||||
func New(params Params) *IPLists {
|
||||
return &IPLists{
|
||||
dir: params.Dir,
|
||||
lists: params.Lists,
|
||||
logger: params.Logger.With("component", "blocklists"),
|
||||
logger: params.Logger.With("component", "iplists"),
|
||||
copies: make(map[string]listCopy),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
@@ -111,7 +145,7 @@ func New(params Params) *Blocklists {
|
||||
// Lookup returns a Listing for each list whose copy contains addr, in the
|
||||
// order of the lists given to New. It makes no outside request. When no list
|
||||
// contains addr, it returns an empty list, not nil.
|
||||
func (b *Blocklists) Lookup(addr netip.Addr) []Listing {
|
||||
func (b *IPLists) Lookup(addr netip.Addr) []Listing {
|
||||
b.mu.RLock()
|
||||
defer b.mu.RUnlock()
|
||||
|
||||
@@ -124,6 +158,7 @@ func (b *Blocklists) Lookup(addr netip.Addr) []Listing {
|
||||
Name: list.Name,
|
||||
Description: list.Description,
|
||||
Updated: c.updated,
|
||||
VPN: list.VPN,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -133,7 +168,7 @@ func (b *Blocklists) Lookup(addr netip.Addr) []Listing {
|
||||
|
||||
// ShortestInterval returns the shortest Interval of the lists. That is the
|
||||
// soonest a copy can change, and so how long a lookup answer stays current.
|
||||
func (b *Blocklists) ShortestInterval() time.Duration {
|
||||
func (b *IPLists) ShortestInterval() time.Duration {
|
||||
var shortest time.Duration
|
||||
|
||||
for i, list := range b.lists {
|
||||
@@ -147,7 +182,7 @@ func (b *Blocklists) ShortestInterval() time.Duration {
|
||||
|
||||
// updated returns when the named list's copy was last downloaded or found
|
||||
// current, or the zero time when the list has no copy.
|
||||
func (b *Blocklists) updated(name string) time.Time {
|
||||
func (b *IPLists) updated(name string) time.Time {
|
||||
b.mu.RLock()
|
||||
defer b.mu.RUnlock()
|
||||
|
||||
@@ -156,7 +191,7 @@ func (b *Blocklists) updated(name string) time.Time {
|
||||
|
||||
// copyValidators returns the validators of the named list's copy. They are
|
||||
// empty when the list has no copy.
|
||||
func (b *Blocklists) copyValidators(name string) validators {
|
||||
func (b *IPLists) copyValidators(name string) validators {
|
||||
b.mu.RLock()
|
||||
defer b.mu.RUnlock()
|
||||
|
||||
@@ -164,7 +199,7 @@ func (b *Blocklists) copyValidators(name string) validators {
|
||||
}
|
||||
|
||||
// setCopy makes c the named list's copy.
|
||||
func (b *Blocklists) setCopy(name string, c listCopy) {
|
||||
func (b *IPLists) setCopy(name string, c listCopy) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
@@ -172,7 +207,7 @@ func (b *Blocklists) setCopy(name string, c listCopy) {
|
||||
}
|
||||
|
||||
// setUpdated records that the named list's copy was found current at t.
|
||||
func (b *Blocklists) setUpdated(name string, t time.Time) {
|
||||
func (b *IPLists) setUpdated(name string, t time.Time) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
@@ -0,0 +1,925 @@
|
||||
package iplist
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The test list's name and description, the address its good version lists,
|
||||
// and the address a newer version lists instead.
|
||||
const (
|
||||
testListName = "test_list"
|
||||
testListDescription = "On the test list"
|
||||
listedAddr = "192.0.2.1"
|
||||
goodListBody = "# A test list\n" + listedAddr + "\n"
|
||||
newListedAddr = "192.0.2.2"
|
||||
newListBody = "# A test list\n" + newListedAddr + "\n"
|
||||
)
|
||||
|
||||
// A small Onionoo details document: a relay with an exit address and IPv4 and
|
||||
// IPv6 relay addresses, one without exit addresses, and one with a list of
|
||||
// ports.
|
||||
const (
|
||||
onionooExitAddr = "192.0.2.10"
|
||||
onionooIPv6ExitAddr = "2001:db8::1"
|
||||
onionooBody = `{"version":"8.0","relays":[
|
||||
{"exit_addresses":["` + onionooExitAddr + `"],
|
||||
"or_addresses":["192.0.2.11:443","[` + onionooIPv6ExitAddr + `]:9001"]},
|
||||
{"or_addresses":["192.0.2.20:443"]},
|
||||
{"or_addresses":["192.0.2.30:80,443"]}
|
||||
],"bridges":[]}`
|
||||
)
|
||||
|
||||
// Small documents in the VPN services' formats. PIA's and IVPN's have no
|
||||
// public IPv6 addresses, and IVPN's holds addresses that are not its servers,
|
||||
// which must not be read.
|
||||
const (
|
||||
mullvadBody = `[
|
||||
{"hostname":"a-wg-001","ipv4_addr_in":"192.0.2.40","ipv6_addr_in":"2001:db8::40"},
|
||||
{"hostname":"a-br-001","ipv4_addr_in":"192.0.2.41","ipv6_addr_in":null,
|
||||
"ipv4_v2ray":"192.0.2.42"}
|
||||
]`
|
||||
nordVPNBody = `[
|
||||
{"hostname":"a1.example.com","station":"192.0.2.50","ipv6_station":""},
|
||||
{"hostname":"a2.example.com","station":"192.0.2.51","ipv6_station":"2001:db8::51"}
|
||||
]`
|
||||
piaBody = `{"groups":{"wg":[{"name":"wireguard","ports":[1337]}]},"regions":[
|
||||
{"id":"a","servers":{
|
||||
"wg":[{"ip":"192.0.2.60","cn":"a1"}],
|
||||
"ikev2":[{"ip":"192.0.2.61","cn":"a1"}]}},
|
||||
{"id":"b","servers":{"meta":[{"ip":"192.0.2.62","cn":"b1","van":true}]}}
|
||||
]}` + "\n\nc2lnbmF0dXJl\nbGluZSB0d28=\n"
|
||||
ivpnBody = `{"wireguard":[{"gateway":"a.wg.example.com","hosts":[
|
||||
{"hostname":"a1","host":"192.0.2.70","v2ray":"192.0.2.71",
|
||||
"ipv6":{"local_ip":"2001:db8::70/96"}}]}],
|
||||
"openvpn":[{"gateway":"a.gw.example.com","hosts":[
|
||||
{"hostname":"a1","host":"192.0.2.72"}]}],
|
||||
"config":{"api":{"ips":["192.0.2.73"]}}}`
|
||||
)
|
||||
|
||||
// protonVPNBody is a small file in the format of the ProtonVPN-IPs list.
|
||||
const protonVPNBody = "#\n# protonvpn_ip_ranges.txt\n" +
|
||||
"# https://github.com/tn3w/ProtonVPN-IPs\n#\n" +
|
||||
"# The /24 block of every advertised IPv4.\n#\n" +
|
||||
"192.0.2.0/24\n198.51.100.0/24\n"
|
||||
|
||||
// protonVPNEntryBody is a small file in the format of the ProtonVPN-IPs list
|
||||
// of server addresses.
|
||||
const protonVPNEntryBody = "#\n# protonvpn_entry_ips.txt\n" +
|
||||
"# https://github.com/tn3w/ProtonVPN-IPs\n#\n" +
|
||||
"# Entry IPs clients connect to, resolved from ProtonVPN hostnames.\n#\n" +
|
||||
"192.0.2.80\n2001:db8::80\n"
|
||||
|
||||
// errorPage is a file that is no list, as a publisher's error page is.
|
||||
const errorPage = "<!DOCTYPE html>\n<html></html>\n"
|
||||
|
||||
// testETag is the ETag a publisher sends with a version of the test list.
|
||||
const testETag = `"v1"`
|
||||
|
||||
// maxWait is how long a test waits for the download goroutine.
|
||||
const maxWait = 10 * time.Second
|
||||
|
||||
// publisher stands in for a list's publisher. It answers every request with
|
||||
// its status and body, and keeps the headers of each request. A 200 answer
|
||||
// carries lastModified and etag, when set, as Last-Modified and ETag. As
|
||||
// from a real publisher, a request whose If-None-Match or If-Modified-Since
|
||||
// matches them is answered "not modified".
|
||||
type publisher struct {
|
||||
mu sync.Mutex
|
||||
status int
|
||||
body string
|
||||
lastModified time.Time
|
||||
etag string
|
||||
headers []http.Header
|
||||
}
|
||||
|
||||
// newPublisher starts a publisher that answers 200 with body, and returns it
|
||||
// and its URL.
|
||||
func newPublisher(t *testing.T, body string) (*publisher, string) {
|
||||
t.Helper()
|
||||
|
||||
p := &publisher{status: http.StatusOK, body: body}
|
||||
srv := httptest.NewServer(p)
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
return p, srv.URL
|
||||
}
|
||||
|
||||
func (p *publisher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
p.headers = append(p.headers, r.Header.Clone())
|
||||
|
||||
if p.status != http.StatusOK {
|
||||
w.WriteHeader(p.status)
|
||||
_, _ = io.WriteString(w, p.body)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if p.etag != "" {
|
||||
w.Header().Set(etagHeader, p.etag)
|
||||
}
|
||||
|
||||
// ServeContent sends Last-Modified unless lastModified is zero, and
|
||||
// answers "not modified" when the request's conditions match.
|
||||
http.ServeContent(w, r, testListName, p.lastModified,
|
||||
strings.NewReader(p.body))
|
||||
}
|
||||
|
||||
// answer makes the publisher answer later requests with status and body.
|
||||
func (p *publisher) answer(status int, body string) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
p.status, p.body = status, body
|
||||
}
|
||||
|
||||
// publish makes the publisher answer later requests with a version of the
|
||||
// list: body, with lastModified and etag. A zero lastModified or an empty
|
||||
// etag is not sent.
|
||||
func (p *publisher) publish(body string, lastModified time.Time, etag string) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
p.status, p.body = http.StatusOK, body
|
||||
p.lastModified, p.etag = lastModified, etag
|
||||
}
|
||||
|
||||
// requests returns the headers of the requests the publisher has had.
|
||||
func (p *publisher) requests() []http.Header {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
return append([]http.Header(nil), p.headers...)
|
||||
}
|
||||
|
||||
// testList returns a list served at url, written in format.
|
||||
func testList(url string, format Format) List {
|
||||
return List{
|
||||
Name: testListName,
|
||||
Description: testListDescription,
|
||||
URL: url,
|
||||
Interval: time.Hour,
|
||||
Format: format,
|
||||
}
|
||||
}
|
||||
|
||||
func newTestIPLists(dir string, list List) *IPLists {
|
||||
return New(Params{
|
||||
Dir: dir,
|
||||
Lists: []List{list},
|
||||
Logger: slog.New(slog.DiscardHandler),
|
||||
})
|
||||
}
|
||||
|
||||
// lookup looks addr up in b.
|
||||
func lookup(t *testing.T, b *IPLists, addr string) []Listing {
|
||||
t.Helper()
|
||||
|
||||
return b.Lookup(netip.MustParseAddr(addr))
|
||||
}
|
||||
|
||||
// TestLookupFindsListedAddresses downloads a list in each format and looks
|
||||
// up addresses on it, inside its networks, and off it, in IPv4 and IPv6.
|
||||
// A listed address has one listing that names the list; any other has an
|
||||
// empty list of listings.
|
||||
func TestLookupFindsListedAddresses(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
runLookupCases(t, []lookupCase{
|
||||
{
|
||||
name: "single addresses",
|
||||
format: FormatLines,
|
||||
body: "# comment\n192.0.2.1\n\n2001:db8::1\n",
|
||||
listed: []string{"192.0.2.1", "::ffff:192.0.2.1", "2001:db8::1"},
|
||||
unlisted: []string{"192.0.2.2", "2001:db8::2"},
|
||||
},
|
||||
{
|
||||
name: "networks",
|
||||
format: FormatLines,
|
||||
body: "# comment\n198.51.100.0/24\n2001:db8:1::/48\n",
|
||||
listed: []string{"198.51.100.0", "198.51.100.255", "2001:db8:1::5"},
|
||||
unlisted: []string{"198.51.101.0", "2001:db8:2::1"},
|
||||
},
|
||||
{
|
||||
name: "Spamhaus networks",
|
||||
format: FormatSpamhausJSON,
|
||||
body: `{"cidr":"203.0.113.0/25","sblid":"SBL1","rir":"arin"}` + "\n" +
|
||||
`{"cidr":"2001:db8:3::/48","sblid":"SBL2","rir":"ripencc"}` + "\n" +
|
||||
`{"type":"metadata","timestamp":1793074442,"records":2}` + "\n",
|
||||
listed: []string{"203.0.113.1", "2001:db8:3::1"},
|
||||
unlisted: []string{"203.0.113.200", "2001:db8:4::1"},
|
||||
},
|
||||
{
|
||||
name: "DShield networks",
|
||||
format: FormatDShield,
|
||||
body: "# DShield.org Recommended Block List\n" +
|
||||
"192.0.2.0\t192.0.2.255\t24\t327\tEXAMPLE\tUS\tNone\n",
|
||||
listed: []string{"192.0.2.0", "192.0.2.77"},
|
||||
unlisted: []string{"192.0.3.1", "2001:db8::1"},
|
||||
},
|
||||
{
|
||||
name: "Onionoo relays",
|
||||
format: FormatOnionooJSON,
|
||||
body: onionooBody,
|
||||
listed: []string{
|
||||
onionooExitAddr, "192.0.2.11", "192.0.2.20", "192.0.2.30",
|
||||
onionooIPv6ExitAddr,
|
||||
},
|
||||
unlisted: []string{"192.0.2.12", "2001:db8::2"},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// TestLookupFindsVPNServers downloads a list in each VPN service's format and
|
||||
// looks up addresses on it and off it.
|
||||
func TestLookupFindsVPNServers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
runLookupCases(t, []lookupCase{
|
||||
{
|
||||
name: "Mullvad relays",
|
||||
format: FormatMullvadJSON,
|
||||
body: mullvadBody,
|
||||
listed: []string{"192.0.2.40", "192.0.2.41", "192.0.2.42", "2001:db8::40"},
|
||||
unlisted: []string{"192.0.2.43", "2001:db8::41"},
|
||||
},
|
||||
{
|
||||
name: "NordVPN servers",
|
||||
format: FormatNordVPNJSON,
|
||||
body: nordVPNBody,
|
||||
listed: []string{"192.0.2.50", "192.0.2.51", "2001:db8::51"},
|
||||
unlisted: []string{"192.0.2.52", "2001:db8::50"},
|
||||
},
|
||||
{
|
||||
name: "PIA servers, with the signature after the JSON",
|
||||
format: FormatPIAJSON,
|
||||
body: piaBody,
|
||||
listed: []string{"192.0.2.60", "192.0.2.61", "192.0.2.62"},
|
||||
unlisted: []string{"192.0.2.63", "2001:db8::60"},
|
||||
},
|
||||
{
|
||||
name: "IVPN hosts",
|
||||
format: FormatIVPNJSON,
|
||||
body: ivpnBody,
|
||||
listed: []string{"192.0.2.70", "192.0.2.71", "192.0.2.72"},
|
||||
unlisted: []string{"192.0.2.73", "2001:db8::70"},
|
||||
},
|
||||
{
|
||||
name: "ProtonVPN networks",
|
||||
format: FormatProtonVPN,
|
||||
body: protonVPNBody,
|
||||
listed: []string{"192.0.2.0", "192.0.2.255", "198.51.100.7"},
|
||||
unlisted: []string{"192.0.3.1", "2001:db8::90"},
|
||||
},
|
||||
{
|
||||
name: "ProtonVPN server addresses",
|
||||
format: FormatProtonVPN,
|
||||
body: protonVPNEntryBody,
|
||||
listed: []string{"192.0.2.80", "2001:db8::80"},
|
||||
unlisted: []string{"192.0.2.81", "2001:db8::81"},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// lookupCase is a list file, the addresses it holds and some it does not.
|
||||
type lookupCase struct {
|
||||
name string
|
||||
format Format
|
||||
body string
|
||||
listed []string
|
||||
unlisted []string
|
||||
}
|
||||
|
||||
// runLookupCases downloads each case's list file and checks its addresses.
|
||||
func runLookupCases(t *testing.T, cases []lookupCase) {
|
||||
t.Helper()
|
||||
|
||||
for _, tt := range cases {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, url := newPublisher(t, tt.body)
|
||||
b := newTestIPLists(t.TempDir(), testList(url, tt.format))
|
||||
|
||||
err := b.download(t.Context(), b.lists[0])
|
||||
if err != nil {
|
||||
t.Fatalf("download: %v", err)
|
||||
}
|
||||
|
||||
checkLookups(t, b, tt.listed, tt.unlisted)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// checkLookups checks that each of listed has one listing that names the test
|
||||
// list, and each of unlisted has an empty list of listings.
|
||||
func checkLookups(t *testing.T, b *IPLists, listed, unlisted []string) {
|
||||
t.Helper()
|
||||
|
||||
for _, addr := range listed {
|
||||
listings := lookup(t, b, addr)
|
||||
if len(listings) != 1 || listings[0].Name != testListName ||
|
||||
listings[0].Description != testListDescription ||
|
||||
listings[0].Updated.IsZero() {
|
||||
t.Errorf("%s: listings %+v, want one for %s", addr,
|
||||
listings, testListName)
|
||||
}
|
||||
}
|
||||
|
||||
for _, addr := range unlisted {
|
||||
listings := lookup(t, b, addr)
|
||||
if listings == nil || len(listings) != 0 {
|
||||
t.Errorf("%s: listings %#v, want an empty list", addr, listings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFailedDownloadKeepsThePreviousCopy downloads a good version of a list,
|
||||
// then one that fails. The good copy stays in memory and on disk, and no
|
||||
// part of the failed download is left beside it.
|
||||
func TestFailedDownloadKeepsThePreviousCopy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{"server error", http.StatusInternalServerError, "unavailable"},
|
||||
{"not a list", http.StatusOK, errorPage},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
p, url := newPublisher(t, goodListBody)
|
||||
b := newTestIPLists(dir, testList(url, FormatLines))
|
||||
|
||||
err := b.download(t.Context(), b.lists[0])
|
||||
if err != nil {
|
||||
t.Fatalf("first download: %v", err)
|
||||
}
|
||||
|
||||
before := lookup(t, b, listedAddr)
|
||||
|
||||
p.answer(tt.status, tt.body)
|
||||
|
||||
err = b.download(t.Context(), b.lists[0])
|
||||
if err == nil {
|
||||
t.Fatal("second download returned no error")
|
||||
}
|
||||
|
||||
after := lookup(t, b, listedAddr)
|
||||
if len(after) != 1 || len(before) != 1 ||
|
||||
!after[0].Updated.Equal(before[0].Updated) {
|
||||
t.Errorf("listings %+v after the failure, want %+v", after, before)
|
||||
}
|
||||
|
||||
checkGoodCopyOnDisk(t, dir)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFileThatIsNotAnOnionooDocumentKeepsThePreviousCopy downloads a good
|
||||
// Onionoo document, then files that are not one. Each fails the parse, and
|
||||
// the good copy stays.
|
||||
func TestFileThatIsNotAnOnionooDocumentKeepsThePreviousCopy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
}{
|
||||
{"not JSON", errorPage},
|
||||
{"other JSON", `{"status":"ok","data":{"relays_count":1}}`},
|
||||
{"JSON array", `[{"or_addresses":["192.0.2.1:443"]}]`},
|
||||
{"no relays", `{"relays":[],"bridges":[]}`},
|
||||
{"relays without addresses", `{"relays":[{"nickname":"example"}]}`},
|
||||
{"relay address without a port", `{"relays":[{"or_addresses":["192.0.2.1"]}]}`},
|
||||
{"exit address that is not one", `{"relays":[{"exit_addresses":["example"]}]}`},
|
||||
{"text after the document", `{"relays":[{"or_addresses":["192.0.2.1:1"]}]} x`},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
p, url := newPublisher(t, onionooBody)
|
||||
b := newTestIPLists(dir, testList(url, FormatOnionooJSON))
|
||||
|
||||
err := b.download(t.Context(), b.lists[0])
|
||||
if err != nil {
|
||||
t.Fatalf("first download: %v", err)
|
||||
}
|
||||
|
||||
p.answer(http.StatusOK, tt.body)
|
||||
|
||||
err = b.download(t.Context(), b.lists[0])
|
||||
if err == nil {
|
||||
t.Fatal("second download returned no error")
|
||||
}
|
||||
|
||||
if len(lookup(t, b, onionooExitAddr)) != 1 {
|
||||
t.Errorf("%s is no longer listed", onionooExitAddr)
|
||||
}
|
||||
|
||||
onDisk, err := fs.ReadFile(os.DirFS(dir), testListName)
|
||||
if err != nil || string(onDisk) != onionooBody {
|
||||
t.Errorf("copy on disk %q (%v), want the good version", onDisk, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestWrongVPNDocumentFailsToParse parses documents that are not a VPN
|
||||
// service's list. Each fails, so none can replace a good copy.
|
||||
func TestWrongVPNDocumentFailsToParse(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
formats := []struct {
|
||||
name string
|
||||
format Format
|
||||
good string
|
||||
empty string
|
||||
badAddress string
|
||||
}{
|
||||
{
|
||||
"Mullvad", FormatMullvadJSON, mullvadBody,
|
||||
`[{"hostname":"a"}]`, `[{"ipv4_addr_in":"example"}]`,
|
||||
},
|
||||
{
|
||||
"NordVPN", FormatNordVPNJSON, nordVPNBody,
|
||||
`[{"hostname":"a","station":"","ipv6_station":""}]`,
|
||||
`[{"station":"example"}]`,
|
||||
},
|
||||
{
|
||||
"PIA", FormatPIAJSON, piaBody,
|
||||
`{"regions":[{"id":"a","servers":{}}]}`,
|
||||
`{"regions":[{"servers":{"wg":[{"ip":"example"}]}}]}`,
|
||||
},
|
||||
{
|
||||
"IVPN", FormatIVPNJSON, ivpnBody,
|
||||
`{"wireguard":[{"hosts":[]}],"openvpn":[]}`,
|
||||
`{"wireguard":[{"hosts":[{"host":"example"}]}]}`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, f := range formats {
|
||||
bodies := map[string]string{
|
||||
"not JSON": errorPage,
|
||||
"other JSON": `{"status":"ok","data":{"count":1}}`,
|
||||
"no addresses": f.empty,
|
||||
"bad address": f.badAddress,
|
||||
"cut off": f.good[:len(f.good)/2],
|
||||
"an empty file": "",
|
||||
}
|
||||
|
||||
for name, body := range bodies {
|
||||
t.Run(f.name+" "+name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
addresses, err := parse(strings.NewReader(body), f.format)
|
||||
if err == nil {
|
||||
t.Errorf("parse returned %v and no error", addresses.Ranges())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestWrongProtonVPNDocumentFailsToParse parses documents that are not a
|
||||
// ProtonVPN-IPs list. Each fails, so none can replace a good copy.
|
||||
func TestWrongProtonVPNDocumentFailsToParse(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
bodies := map[string]string{
|
||||
"error page": errorPage,
|
||||
"JSON": `{"status":"ok"}`,
|
||||
"comments only": "#\n# protonvpn_ip_ranges.txt\n#\n",
|
||||
"bad network": "192.0.2.0/24\nexample\n",
|
||||
"an empty file": "",
|
||||
}
|
||||
|
||||
for name, body := range bodies {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
addresses, err := parse(strings.NewReader(body), FormatProtonVPN)
|
||||
if err == nil {
|
||||
t.Errorf("parse returned %v and no error", addresses.Ranges())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLookupMarksVPNLists looks up an address on a VPN list and on another
|
||||
// list. Only the VPN list's listing says it is one.
|
||||
func TestLookupMarksVPNLists(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, url := newPublisher(t, goodListBody)
|
||||
vpnList := testList(url, FormatLines)
|
||||
vpnList.Name = "test_vpn_list"
|
||||
vpnList.VPN = true
|
||||
otherList := testList(url, FormatLines)
|
||||
|
||||
b := New(Params{
|
||||
Dir: t.TempDir(),
|
||||
Lists: []List{vpnList, otherList},
|
||||
Logger: slog.New(slog.DiscardHandler),
|
||||
})
|
||||
|
||||
for _, list := range b.lists {
|
||||
err := b.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("download of %s: %v", list.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
listings := lookup(t, b, listedAddr)
|
||||
if len(listings) != 2 || !listings[0].VPN || listings[1].VPN {
|
||||
t.Errorf("listings %+v, want the first of two marked as a VPN list",
|
||||
listings)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublicListsMarkTheVPNLists checks which public lists are VPN lists,
|
||||
// since their names are what vpn_providers reports.
|
||||
func TestPublicListsMarkTheVPNLists(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var got []string
|
||||
|
||||
for _, list := range Lists() {
|
||||
if list.VPN {
|
||||
got = append(got, list.Name)
|
||||
}
|
||||
}
|
||||
|
||||
want := []string{
|
||||
"ivpn", "mullvad", "nordvpn", "pia", "protonvpn", "protonvpn_entry",
|
||||
"x4bnet", "x4bnet_v6",
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("VPN lists %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// checkGoodCopyOnDisk checks that dir holds the good version of the test list
|
||||
// and no part of a failed download.
|
||||
func checkGoodCopyOnDisk(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
|
||||
copies := os.DirFS(dir)
|
||||
|
||||
onDisk, err := fs.ReadFile(copies, testListName)
|
||||
if err != nil || string(onDisk) != goodListBody {
|
||||
t.Errorf("copy on disk %q (%v), want %q", onDisk, err, goodListBody)
|
||||
}
|
||||
|
||||
_, err = fs.Stat(copies, testListName+downloadSuffix)
|
||||
if !errors.Is(err, fs.ErrNotExist) {
|
||||
t.Errorf("the failed download's file is still there (%v)", err)
|
||||
}
|
||||
}
|
||||
|
||||
// commentLines is an endless io.Reader of comment lines. It lets a test send
|
||||
// a large list file without holding the file in memory.
|
||||
type commentLines struct {
|
||||
offset int
|
||||
}
|
||||
|
||||
func (c *commentLines) Read(p []byte) (int, error) {
|
||||
const line = "# a comment line that pads a large list file\n"
|
||||
|
||||
for filled := 0; filled < len(p); {
|
||||
copied := copy(p[filled:], line[c.offset:])
|
||||
filled += copied
|
||||
c.offset = (c.offset + copied) % len(line)
|
||||
}
|
||||
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// largeListFile returns a reader of a list file of size bytes: comment lines,
|
||||
// then newListedAddr on the last line.
|
||||
func largeListFile(size int64) io.Reader {
|
||||
lastLine := "\n" + newListedAddr + "\n"
|
||||
|
||||
return io.MultiReader(
|
||||
io.LimitReader(&commentLines{}, size-int64(len(lastLine))),
|
||||
strings.NewReader(lastLine),
|
||||
)
|
||||
}
|
||||
|
||||
// TestLargeFileUnderTheSizeLimitIsAccepted replaces a list with a 199 MiB
|
||||
// file. The address on its last line is listed, so the whole file was read.
|
||||
func TestLargeFileUnderTheSizeLimitIsAccepted(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const size = 199 << 20
|
||||
|
||||
b := newTestIPLists(t.TempDir(), testList("", FormatLines))
|
||||
|
||||
err := b.replaceCopy(b.lists[0], largeListFile(size), validators{})
|
||||
if err != nil {
|
||||
t.Fatalf("replaceCopy: %v", err)
|
||||
}
|
||||
|
||||
if listings := lookup(t, b, newListedAddr); len(listings) != 1 {
|
||||
t.Errorf("listings %+v, want one", listings)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFileOverTheSizeLimitKeepsThePreviousCopy downloads a good version of a
|
||||
// list, then replaces it with a file one byte over the limit. The attempt
|
||||
// fails, and the good copy stays in memory and on disk.
|
||||
func TestFileOverTheSizeLimitKeepsThePreviousCopy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
_, url := newPublisher(t, goodListBody)
|
||||
b := newTestIPLists(dir, testList(url, FormatLines))
|
||||
|
||||
err := b.download(t.Context(), b.lists[0])
|
||||
if err != nil {
|
||||
t.Fatalf("download: %v", err)
|
||||
}
|
||||
|
||||
err = b.replaceCopy(b.lists[0], largeListFile(maxDownloadSize+1), validators{})
|
||||
if !errors.Is(err, errTooLarge) {
|
||||
t.Fatalf("replaceCopy: %v, want %v", err, errTooLarge)
|
||||
}
|
||||
|
||||
if listings := lookup(t, b, listedAddr); len(listings) != 1 {
|
||||
t.Errorf("listings of %s %+v, want one", listedAddr, listings)
|
||||
}
|
||||
|
||||
checkGoodCopyOnDisk(t, dir)
|
||||
}
|
||||
|
||||
// TestRestartLoadsCopiesFromDisk downloads a list, then starts a new
|
||||
// IPLists on the same directory, as a restart does. The new one answers
|
||||
// from the copy on disk at once, and does not download the list again while
|
||||
// the copy is younger than the list's interval.
|
||||
func TestRestartLoadsCopiesFromDisk(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
p, url := newPublisher(t, goodListBody)
|
||||
list := testList(url, FormatLines)
|
||||
|
||||
first := newTestIPLists(dir, list)
|
||||
|
||||
err := first.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("download: %v", err)
|
||||
}
|
||||
|
||||
downloaded := lookup(t, first, listedAddr)[0].Updated
|
||||
|
||||
second := newTestIPLists(dir, list)
|
||||
second.Start(t.Context())
|
||||
second.Stop(t.Context())
|
||||
|
||||
// The download takes its time after writing the file, and the restart
|
||||
// reads the file's time. A busy host can put seconds between the two.
|
||||
const maxUpdatedDifference = 15 * time.Second
|
||||
|
||||
listings := lookup(t, second, listedAddr)
|
||||
if len(listings) != 1 ||
|
||||
listings[0].Updated.Sub(downloaded).Abs() > maxUpdatedDifference {
|
||||
t.Errorf("after the restart, listings %+v, want one updated at %s",
|
||||
listings, downloaded)
|
||||
}
|
||||
|
||||
if got := len(p.requests()); got != 1 {
|
||||
t.Errorf("the publisher had %d requests, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartRefreshesAnOldCopy starts on a copy older than its list's
|
||||
// interval. The list is downloaded at once, with routewatch's User-Agent and
|
||||
// the Last-Modified and ETag the publisher sent with the copy, kept on disk.
|
||||
// The publisher answers that the copy is still current, so the copy is kept
|
||||
// and marked as updated now.
|
||||
func TestStartRefreshesAnOldCopy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
p, url := newPublisher(t, goodListBody)
|
||||
list := testList(url, FormatLines)
|
||||
|
||||
lastModified := time.Now().Add(-3 * list.Interval).UTC().Truncate(time.Second)
|
||||
p.publish(goodListBody, lastModified, testETag)
|
||||
|
||||
err := newTestIPLists(dir, list).download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("download: %v", err)
|
||||
}
|
||||
|
||||
old := time.Now().Add(-2 * list.Interval).UTC().Truncate(time.Second)
|
||||
|
||||
err = os.Chtimes(filepath.Join(dir, testListName), old, old)
|
||||
if err != nil {
|
||||
t.Fatalf("Chtimes: %v", err)
|
||||
}
|
||||
|
||||
b := newTestIPLists(dir, list)
|
||||
b.Start(t.Context())
|
||||
|
||||
deadline := time.Now().Add(maxWait)
|
||||
for !lookup(t, b, listedAddr)[0].Updated.After(old) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("the copy was not marked updated within %s", maxWait)
|
||||
}
|
||||
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
|
||||
b.Stop(t.Context())
|
||||
|
||||
requests := p.requests()
|
||||
last := requests[len(requests)-1]
|
||||
|
||||
want := lastModified.Format(http.TimeFormat)
|
||||
if got := last.Get(ifModifiedSinceHeader); got != want {
|
||||
t.Errorf("If-Modified-Since %q, want %q", got, want)
|
||||
}
|
||||
|
||||
if got := last.Get(ifNoneMatchHeader); got != testETag {
|
||||
t.Errorf("If-None-Match %q, want %q", got, testETag)
|
||||
}
|
||||
|
||||
if got := last.Get(userAgentHeader); got != userAgent {
|
||||
t.Errorf("User-Agent %q, want %q", got, userAgent)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewVersionOlderThanTheLastDownloadReplacesTheCopy downloads a list.
|
||||
// The publisher then puts out a new version whose Last-Modified is earlier
|
||||
// than that download, as when a cache in front of the publisher passes the
|
||||
// version on late. The next download sends the Last-Modified of the copy,
|
||||
// not the time of the download, so it gets the new version.
|
||||
func TestNewVersionOlderThanTheLastDownloadReplacesTheCopy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
p, url := newPublisher(t, goodListBody)
|
||||
list := testList(url, FormatLines)
|
||||
b := newTestIPLists(t.TempDir(), list)
|
||||
|
||||
firstVersion := time.Now().Add(-2 * list.Interval).UTC().Truncate(time.Second)
|
||||
p.publish(goodListBody, firstVersion, "")
|
||||
|
||||
err := b.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("first download: %v", err)
|
||||
}
|
||||
|
||||
p.publish(newListBody, firstVersion.Add(list.Interval), "")
|
||||
|
||||
err = b.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("second download: %v", err)
|
||||
}
|
||||
|
||||
if listings := lookup(t, b, newListedAddr); len(listings) != 1 {
|
||||
t.Errorf("%s: listings %+v, want one from the new version",
|
||||
newListedAddr, listings)
|
||||
}
|
||||
|
||||
want := firstVersion.Format(http.TimeFormat)
|
||||
if got := p.requests()[1].Get(ifModifiedSinceHeader); got != want {
|
||||
t.Errorf("If-Modified-Since %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDownloadWithoutLastModifiedOrETagSendsNoCondition downloads a list
|
||||
// twice from a publisher that sends neither Last-Modified nor ETag. Neither
|
||||
// request carries If-Modified-Since or If-None-Match, so the second download
|
||||
// gets the whole list again.
|
||||
func TestDownloadWithoutLastModifiedOrETagSendsNoCondition(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
p, url := newPublisher(t, goodListBody)
|
||||
list := testList(url, FormatLines)
|
||||
b := newTestIPLists(t.TempDir(), list)
|
||||
|
||||
err := b.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("first download: %v", err)
|
||||
}
|
||||
|
||||
err = b.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("second download: %v", err)
|
||||
}
|
||||
|
||||
for i, request := range p.requests() {
|
||||
if request.Get(ifModifiedSinceHeader) != "" ||
|
||||
request.Get(ifNoneMatchHeader) != "" {
|
||||
t.Errorf("request %d has a condition: %v", i, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestStopCancelsADownloadInProgress stops while the publisher has not
|
||||
// answered. Stop cancels the download and returns once the download
|
||||
// goroutine has stopped.
|
||||
func TestStopCancelsADownloadInProgress(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
arrived := make(chan struct{})
|
||||
|
||||
var once sync.Once
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(
|
||||
func(_ http.ResponseWriter, r *http.Request) {
|
||||
once.Do(func() { close(arrived) })
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
b := newTestIPLists(t.TempDir(), testList(srv.URL, FormatLines))
|
||||
b.Start(t.Context())
|
||||
|
||||
select {
|
||||
case <-arrived:
|
||||
case <-time.After(maxWait):
|
||||
t.Fatalf("no download began within %s", maxWait)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), maxWait)
|
||||
defer cancel()
|
||||
|
||||
b.Stop(ctx)
|
||||
|
||||
select {
|
||||
case <-b.done:
|
||||
default:
|
||||
t.Error("Stop returned before the download goroutine stopped")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTorExitsListHoldsIPv6Exits downloads an Onionoo document as the public
|
||||
// Tor exit list, which is what an IPv6 address's is_tor answer comes from.
|
||||
func TestTorExitsListHoldsIPv6Exits(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
index := slices.IndexFunc(Lists(), func(list List) bool {
|
||||
return list.Name == TorExitsList
|
||||
})
|
||||
if index < 0 {
|
||||
t.Fatalf("no list named %s", TorExitsList)
|
||||
}
|
||||
|
||||
list := Lists()[index]
|
||||
_, list.URL = newPublisher(t, onionooBody)
|
||||
b := newTestIPLists(t.TempDir(), list)
|
||||
|
||||
err := b.download(t.Context(), list)
|
||||
if err != nil {
|
||||
t.Fatalf("download: %v", err)
|
||||
}
|
||||
|
||||
listings := lookup(t, b, onionooIPv6ExitAddr)
|
||||
if len(listings) != 1 || listings[0].Name != TorExitsList {
|
||||
t.Errorf("listings %+v, want one for %s", listings, TorExitsList)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublicListsAreComplete checks that every public list has what a
|
||||
// download and a lookup answer need, and a unique name.
|
||||
func TestPublicListsAreComplete(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
names := make(map[string]bool)
|
||||
|
||||
for _, list := range Lists() {
|
||||
if list.Name == "" || list.Description == "" || list.URL == "" ||
|
||||
list.Interval <= 0 || names[list.Name] {
|
||||
t.Errorf("list %+v is incomplete or has a name used before", list)
|
||||
}
|
||||
|
||||
names[list.Name] = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package iplist
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TorExitsList is the name of the list of Tor exit nodes.
|
||||
const TorExitsList = "tor_exits"
|
||||
|
||||
// protonVPNIPsURL is where the ProtonVPN-IPs mirror publishes its files.
|
||||
const protonVPNIPsURL = "https://raw.githubusercontent.com/tn3w/ProtonVPN-IPs/master/"
|
||||
|
||||
// How often each list is downloaded. No list is downloaded more often than
|
||||
// its publisher updates it or allows.
|
||||
const (
|
||||
// DShield asks that its feeds be downloaded at most once an hour:
|
||||
// https://isc.sans.edu/feeds_doc.html
|
||||
dshieldInterval = time.Hour
|
||||
|
||||
// abuse.ch makes the list every 5 minutes and recommends a download at
|
||||
// least every 15: https://feodotracker.abuse.ch/blocklist/
|
||||
feodoTrackerInterval = 15 * time.Minute
|
||||
|
||||
// FireHOL's page for each list gives how often the list changes on
|
||||
// average: about every 5 hours for abusers and every 3 hours for level
|
||||
// 3. FireHOL sets no download limit.
|
||||
// https://iplists.firehol.org/?ipset=firehol_abusers_30d
|
||||
// https://iplists.firehol.org/?ipset=firehol_level3
|
||||
fireHOLAbusersInterval = 5 * time.Hour
|
||||
fireHOLLevel3Interval = 3 * time.Hour
|
||||
|
||||
// Spamhaus asks that DROP be downloaded at most once a day:
|
||||
// https://www.spamhaus.org/blocklists/do-not-route-or-peer/
|
||||
spamhausDROPInterval = 24 * time.Hour
|
||||
|
||||
// Onionoo's relay data follows Tor's hourly network consensus, and
|
||||
// Onionoo sets no download limit:
|
||||
// https://metrics.torproject.org/onionoo.html
|
||||
torExitsInterval = time.Hour
|
||||
|
||||
// A VPN service's servers change slowly, so once a day is enough.
|
||||
vpnListInterval = 24 * time.Hour
|
||||
)
|
||||
|
||||
// Lists returns the public IP lists routewatch downloads. Each can be
|
||||
// downloaded whole without an account or a key. Spamhaus merged its EDROP
|
||||
// list into DROP, so DROP covers both.
|
||||
func Lists() []List {
|
||||
return slices.Concat(nonVPNLists(), vpnLists())
|
||||
}
|
||||
|
||||
// nonVPNLists returns the public lists that are not lists of VPN servers.
|
||||
func nonVPNLists() []List {
|
||||
return []List{
|
||||
{
|
||||
Name: "dshield",
|
||||
Description: "In one of the 20 networks that DShield saw scan " +
|
||||
"the most targets in the last three days",
|
||||
URL: "https://feeds.dshield.org/block.txt",
|
||||
Interval: dshieldInterval,
|
||||
Format: FormatDShield,
|
||||
},
|
||||
{
|
||||
Name: "feodo_tracker",
|
||||
Description: "A botnet command-and-control server",
|
||||
URL: "https://feodotracker.abuse.ch/downloads/ipblocklist.txt",
|
||||
Interval: feodoTrackerInterval,
|
||||
Format: FormatLines,
|
||||
},
|
||||
{
|
||||
Name: "firehol_abusers_30d",
|
||||
Description: "Reported for comment, form or forum spam in the " +
|
||||
"last 30 days",
|
||||
URL: "https://iplists.firehol.org/files/firehol_abusers_30d.netset",
|
||||
Interval: fireHOLAbusersInterval,
|
||||
Format: FormatLines,
|
||||
},
|
||||
{
|
||||
Name: "firehol_level3",
|
||||
Description: "Reported for attacks, spyware or viruses in the " +
|
||||
"last 30 days",
|
||||
URL: "https://iplists.firehol.org/files/firehol_level3.netset",
|
||||
Interval: fireHOLLevel3Interval,
|
||||
Format: FormatLines,
|
||||
},
|
||||
{
|
||||
Name: "spamhaus_drop",
|
||||
Description: "In an IPv4 network that Spamhaus says spammers " +
|
||||
"or cyber criminals have hijacked or lease",
|
||||
URL: "https://www.spamhaus.org/drop/drop_v4.json",
|
||||
Interval: spamhausDROPInterval,
|
||||
Format: FormatSpamhausJSON,
|
||||
},
|
||||
{
|
||||
Name: "spamhaus_dropv6",
|
||||
Description: "In an IPv6 network that Spamhaus says spammers " +
|
||||
"or cyber criminals have hijacked or lease",
|
||||
URL: "https://www.spamhaus.org/drop/drop_v6.json",
|
||||
Interval: spamhausDROPInterval,
|
||||
Format: FormatSpamhausJSON,
|
||||
},
|
||||
{
|
||||
Name: TorExitsList,
|
||||
Description: "A Tor exit node, where traffic from the Tor network leaves",
|
||||
URL: "https://onionoo.torproject.org/details?" +
|
||||
"flag=Exit&running=true&fields=exit_addresses,or_addresses",
|
||||
Interval: torExitsInterval,
|
||||
Format: FormatOnionooJSON,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// vpnLists returns the public lists of VPN servers. Their names are what
|
||||
// vpn_providers reports.
|
||||
func vpnLists() []List {
|
||||
return []List{
|
||||
{
|
||||
Name: "ivpn",
|
||||
Description: "A server of the IVPN service",
|
||||
URL: "https://api.ivpn.net/v5/servers.json",
|
||||
Interval: vpnListInterval,
|
||||
Format: FormatIVPNJSON,
|
||||
VPN: true,
|
||||
},
|
||||
{
|
||||
Name: "mullvad",
|
||||
Description: "A server of the Mullvad VPN service",
|
||||
URL: "https://api.mullvad.net/www/relays/all/",
|
||||
Interval: vpnListInterval,
|
||||
Format: FormatMullvadJSON,
|
||||
VPN: true,
|
||||
},
|
||||
{
|
||||
Name: "nordvpn",
|
||||
Description: "A server of the NordVPN service",
|
||||
URL: "https://api.nordvpn.com/v1/servers?limit=0" +
|
||||
"&fields[servers.station]&fields[servers.ipv6_station]" +
|
||||
"&fields[servers.hostname]",
|
||||
Interval: vpnListInterval,
|
||||
Format: FormatNordVPNJSON,
|
||||
VPN: true,
|
||||
},
|
||||
{
|
||||
Name: "pia",
|
||||
Description: "A server of the Private Internet Access VPN service",
|
||||
URL: "https://serverlist.piaservers.net/vpninfo/servers/v6",
|
||||
Interval: vpnListInterval,
|
||||
Format: FormatPIAJSON,
|
||||
VPN: true,
|
||||
},
|
||||
{
|
||||
// Proton's own server list needs a logged-in session, so this is
|
||||
// the public ProtonVPN-IPs mirror of it. Proton publishes only
|
||||
// the addresses clients connect to. The mirror's README says
|
||||
// traffic leaves from others in the same /24, so this file of
|
||||
// /24 networks is the one it says to use for detecting exits.
|
||||
Name: "protonvpn",
|
||||
Description: "In a /24 network that holds a server of the " +
|
||||
"ProtonVPN service",
|
||||
URL: protonVPNIPsURL + "protonvpn_ip_ranges.txt",
|
||||
Interval: vpnListInterval,
|
||||
Format: FormatProtonVPN,
|
||||
VPN: true,
|
||||
},
|
||||
{
|
||||
Name: "protonvpn_entry",
|
||||
Description: "A server of the ProtonVPN service",
|
||||
URL: protonVPNIPsURL + "protonvpn_entry_ips.txt",
|
||||
Interval: vpnListInterval,
|
||||
Format: FormatProtonVPN,
|
||||
VPN: true,
|
||||
},
|
||||
{
|
||||
Name: "x4bnet",
|
||||
Description: "In an IPv4 network of a VPN service, according to " +
|
||||
"X4BNet's community list",
|
||||
URL: "https://raw.githubusercontent.com/X4BNet/lists_vpn/main/" +
|
||||
"output/vpn/ipv4.txt",
|
||||
Interval: vpnListInterval,
|
||||
Format: FormatLines,
|
||||
VPN: true,
|
||||
},
|
||||
{
|
||||
Name: "x4bnet_v6",
|
||||
Description: "In an IPv6 network of a VPN service, according to " +
|
||||
"X4BNet's community list",
|
||||
URL: "https://raw.githubusercontent.com/X4BNet/lists_vpn/main/" +
|
||||
"output/vpn/ipv6.txt",
|
||||
Interval: vpnListInterval,
|
||||
Format: FormatLines,
|
||||
VPN: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
package iplist
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"go4.org/netipx"
|
||||
)
|
||||
|
||||
const (
|
||||
// commentPrefix starts a comment line in a list file.
|
||||
commentPrefix = "#"
|
||||
|
||||
// networkSeparator separates the address and the mask length of a
|
||||
// network, as in 192.0.2.0/24.
|
||||
networkSeparator = "/"
|
||||
|
||||
// dshieldFieldSeparator separates the fields of a DShield line.
|
||||
dshieldFieldSeparator = "\t"
|
||||
|
||||
// spamhausMetadataType is the type of the line that ends a Spamhaus
|
||||
// file. That line holds the file's metadata and no network.
|
||||
spamhausMetadataType = "metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
errUnknownFormat = errors.New("unknown list format")
|
||||
errNoNetwork = errors.New("no network on the line")
|
||||
errBadRange = errors.New("first and last address make no range")
|
||||
errNoAddresses = errors.New("no addresses in the document")
|
||||
)
|
||||
|
||||
// parse reads a list file written in format and returns the addresses it
|
||||
// holds. Anything it cannot read fails the whole file, so a file that is not
|
||||
// the list, such as an error page, never replaces a good copy.
|
||||
func parse(r io.Reader, format Format) (*netipx.IPSet, error) {
|
||||
switch format {
|
||||
case FormatLines:
|
||||
return parseLines(r, addAddressOrNetwork)
|
||||
case FormatSpamhausJSON:
|
||||
return parseLines(r, addSpamhausNetwork)
|
||||
case FormatDShield:
|
||||
return parseLines(r, addDShieldNetwork)
|
||||
case FormatOnionooJSON:
|
||||
return parseOnionoo(r)
|
||||
case FormatMullvadJSON:
|
||||
return parseMullvad(r)
|
||||
case FormatNordVPNJSON:
|
||||
return parseNordVPN(r)
|
||||
case FormatPIAJSON:
|
||||
return parsePIA(r)
|
||||
case FormatIVPNJSON:
|
||||
return parseIVPN(r)
|
||||
case FormatProtonVPN:
|
||||
return parseProtonVPN(r)
|
||||
default:
|
||||
return nil, errUnknownFormat
|
||||
}
|
||||
}
|
||||
|
||||
// parseLines reads a list file line by line, skipping blank lines and
|
||||
// comments, and calls addLine with each other line.
|
||||
func parseLines(
|
||||
r io.Reader, addLine func(*netipx.IPSetBuilder, string) error,
|
||||
) (*netipx.IPSet, error) {
|
||||
var builder netipx.IPSetBuilder
|
||||
|
||||
scanner := bufio.NewScanner(r)
|
||||
|
||||
for lineNumber := 1; scanner.Scan(); lineNumber++ {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" || strings.HasPrefix(line, commentPrefix) {
|
||||
continue
|
||||
}
|
||||
|
||||
err := addLine(&builder, line)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("line %d: %w", lineNumber, err)
|
||||
}
|
||||
}
|
||||
|
||||
err := scanner.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return builder.IPSet()
|
||||
}
|
||||
|
||||
// addAddressOrNetwork adds an address, such as 192.0.2.1, or a network, such
|
||||
// as 192.0.2.0/24, to builder.
|
||||
func addAddressOrNetwork(builder *netipx.IPSetBuilder, text string) error {
|
||||
if strings.Contains(text, networkSeparator) {
|
||||
network, err := netip.ParsePrefix(text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
builder.AddPrefix(network)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
addr, err := netip.ParseAddr(text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
builder.Add(addr)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// addSpamhausNetwork adds the network on a line of a Spamhaus file to
|
||||
// builder. The metadata line adds nothing.
|
||||
func addSpamhausNetwork(builder *netipx.IPSetBuilder, line string) error {
|
||||
var entry struct {
|
||||
CIDR string `json:"cidr"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
err := json.Unmarshal([]byte(line), &entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if entry.Type == spamhausMetadataType {
|
||||
return nil
|
||||
}
|
||||
|
||||
network, err := netip.ParsePrefix(entry.CIDR)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
builder.AddPrefix(network)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// addDShieldNetwork adds the network on a line of a DShield file to builder.
|
||||
// The line's first two fields are the network's first and last address.
|
||||
func addDShieldNetwork(builder *netipx.IPSetBuilder, line string) error {
|
||||
firstField, rest, found := strings.Cut(line, dshieldFieldSeparator)
|
||||
if !found {
|
||||
return errNoNetwork
|
||||
}
|
||||
|
||||
lastField, _, _ := strings.Cut(rest, dshieldFieldSeparator)
|
||||
|
||||
first, err := netip.ParseAddr(firstField)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
last, err := netip.ParseAddr(lastField)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
network := netipx.IPRangeFrom(first, last)
|
||||
if !network.IsValid() {
|
||||
return errBadRange
|
||||
}
|
||||
|
||||
builder.AddRange(network)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseOnionoo returns every address in the exit_addresses and or_addresses
|
||||
// fields of the relays in an Onionoo details document. A document with no
|
||||
// addresses fails, because the Tor network always has relays.
|
||||
func parseOnionoo(r io.Reader) (*netipx.IPSet, error) {
|
||||
//nolint:tagliatelle // Onionoo's own field names
|
||||
var details struct {
|
||||
Relays []struct {
|
||||
ExitAddresses []string `json:"exit_addresses"`
|
||||
ORAddresses []string `json:"or_addresses"`
|
||||
} `json:"relays"`
|
||||
}
|
||||
|
||||
err := readJSON(r, &details)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var builder netipx.IPSetBuilder
|
||||
|
||||
for _, relay := range details.Relays {
|
||||
for _, text := range relay.ExitAddresses {
|
||||
err = addAddress(&builder, text)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
for _, text := range relay.ORAddresses {
|
||||
err = addAddressWithPort(&builder, text)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addresses, err := builder.IPSet()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(addresses.Ranges()) == 0 {
|
||||
return nil, errNoAddresses
|
||||
}
|
||||
|
||||
return addresses, nil
|
||||
}
|
||||
|
||||
// parseMullvad returns the addresses of the relays in a Mullvad document. A
|
||||
// relay with no IPv6 address has null for it, and only bridges have
|
||||
// ipv4_v2ray.
|
||||
func parseMullvad(r io.Reader) (*netipx.IPSet, error) {
|
||||
//nolint:tagliatelle // Mullvad's own field names
|
||||
var relays []struct {
|
||||
IPv4 string `json:"ipv4_addr_in"`
|
||||
IPv6 string `json:"ipv6_addr_in"`
|
||||
IPv4V2Ray string `json:"ipv4_v2ray"`
|
||||
}
|
||||
|
||||
err := readJSON(r, &relays)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var texts []string
|
||||
|
||||
for _, relay := range relays {
|
||||
texts = append(texts, relay.IPv4, relay.IPv6, relay.IPv4V2Ray)
|
||||
}
|
||||
|
||||
return addressSet(texts)
|
||||
}
|
||||
|
||||
// parseNordVPN returns the addresses of the servers in a NordVPN document. A
|
||||
// server with no IPv6 address has an empty ipv6_station.
|
||||
func parseNordVPN(r io.Reader) (*netipx.IPSet, error) {
|
||||
//nolint:tagliatelle // NordVPN's own field names
|
||||
var servers []struct {
|
||||
Station string `json:"station"`
|
||||
IPv6Station string `json:"ipv6_station"`
|
||||
}
|
||||
|
||||
err := readJSON(r, &servers)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var texts []string
|
||||
|
||||
for _, server := range servers {
|
||||
texts = append(texts, server.Station, server.IPv6Station)
|
||||
}
|
||||
|
||||
return addressSet(texts)
|
||||
}
|
||||
|
||||
// parsePIA returns the addresses of the servers in a Private Internet Access
|
||||
// document. json.Decoder stops at the end of the JSON, so the signature after
|
||||
// it is not read.
|
||||
func parsePIA(r io.Reader) (*netipx.IPSet, error) {
|
||||
var list struct {
|
||||
Regions []struct {
|
||||
Servers map[string][]struct {
|
||||
IP string `json:"ip"`
|
||||
} `json:"servers"`
|
||||
} `json:"regions"`
|
||||
}
|
||||
|
||||
err := json.NewDecoder(r).Decode(&list)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var texts []string
|
||||
|
||||
for _, region := range list.Regions {
|
||||
for _, servers := range region.Servers {
|
||||
for _, server := range servers {
|
||||
texts = append(texts, server.IP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return addressSet(texts)
|
||||
}
|
||||
|
||||
// parseIVPN returns the addresses of the hosts in an IVPN document. A host's
|
||||
// ipv6 object holds only an address inside the VPN, so it is not read.
|
||||
func parseIVPN(r io.Reader) (*netipx.IPSet, error) {
|
||||
type gateway struct {
|
||||
Hosts []struct {
|
||||
Host string `json:"host"`
|
||||
V2Ray string `json:"v2ray"`
|
||||
} `json:"hosts"`
|
||||
}
|
||||
|
||||
var list struct {
|
||||
WireGuard []gateway `json:"wireguard"`
|
||||
OpenVPN []gateway `json:"openvpn"`
|
||||
}
|
||||
|
||||
err := readJSON(r, &list)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var texts []string
|
||||
|
||||
for _, gw := range slices.Concat(list.WireGuard, list.OpenVPN) {
|
||||
for _, host := range gw.Hosts {
|
||||
texts = append(texts, host.Host, host.V2Ray)
|
||||
}
|
||||
}
|
||||
|
||||
return addressSet(texts)
|
||||
}
|
||||
|
||||
// parseProtonVPN returns the addresses or networks in a ProtonVPN-IPs list. A
|
||||
// file with no addresses or networks fails, because the service always has
|
||||
// servers.
|
||||
func parseProtonVPN(r io.Reader) (*netipx.IPSet, error) {
|
||||
addresses, err := parseLines(r, addAddressOrNetwork)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(addresses.Ranges()) == 0 {
|
||||
return nil, errNoAddresses
|
||||
}
|
||||
|
||||
return addresses, nil
|
||||
}
|
||||
|
||||
// readJSON reads r to its end and decodes it, as one JSON document, into v.
|
||||
func readJSON(r io.Reader, v any) error {
|
||||
data, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return json.Unmarshal(data, v)
|
||||
}
|
||||
|
||||
// addressSet returns the set of the addresses in texts, skipping empty ones.
|
||||
// A list with no addresses fails, because every VPN service has servers.
|
||||
func addressSet(texts []string) (*netipx.IPSet, error) {
|
||||
var builder netipx.IPSetBuilder
|
||||
|
||||
for _, text := range texts {
|
||||
if text == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
err := addAddress(&builder, text)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
addresses, err := builder.IPSet()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(addresses.Ranges()) == 0 {
|
||||
return nil, errNoAddresses
|
||||
}
|
||||
|
||||
return addresses, nil
|
||||
}
|
||||
|
||||
// addAddress adds an address, such as 192.0.2.1, to builder.
|
||||
func addAddress(builder *netipx.IPSetBuilder, text string) error {
|
||||
addr, err := netip.ParseAddr(text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
builder.Add(addr)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// addAddressWithPort adds the address of text, such as 192.0.2.1:443 or
|
||||
// [2001:db8::1]:443, to builder. Onionoo allows a list of ports after the
|
||||
// address, so the part after the address is not read.
|
||||
func addAddressWithPort(builder *netipx.IPSetBuilder, text string) error {
|
||||
host, _, err := net.SplitHostPort(text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return addAddress(builder, host)
|
||||
}
|
||||
+16
-16
@@ -15,9 +15,9 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.eeqj.de/sneak/routewatch/internal/blocklist"
|
||||
"git.eeqj.de/sneak/routewatch/internal/config"
|
||||
"git.eeqj.de/sneak/routewatch/internal/database"
|
||||
"git.eeqj.de/sneak/routewatch/internal/iplist"
|
||||
"git.eeqj.de/sneak/routewatch/internal/logger"
|
||||
"git.eeqj.de/sneak/routewatch/internal/metrics"
|
||||
"git.eeqj.de/sneak/routewatch/internal/routetable"
|
||||
@@ -61,12 +61,12 @@ type RouteWatch struct {
|
||||
peeringHandler *PeeringHandler
|
||||
asnFetcher *ASNFetcher
|
||||
dbMaintainer *DBMaintainer
|
||||
blocklists *blocklist.Blocklists
|
||||
ipLists *iplist.IPLists
|
||||
}
|
||||
|
||||
// blocklistsDirName is the directory in the state directory that holds the
|
||||
// blocklist copies.
|
||||
const blocklistsDirName = "blocklists"
|
||||
// ipListsDirName is the directory in the state directory that holds the IP
|
||||
// list copies.
|
||||
const ipListsDirName = "iplists"
|
||||
|
||||
// New creates a new RouteWatch instance
|
||||
func New(deps Dependencies) *RouteWatch {
|
||||
@@ -138,17 +138,17 @@ func (rw *RouteWatch) Run(ctx context.Context) error {
|
||||
rw.asnFetcher.Start(ctx)
|
||||
rw.server.SetASNFetcher(rw.asnFetcher)
|
||||
|
||||
// Load the blocklist copies from disk and start downloading the lists.
|
||||
// The HTTP handlers read the server's blocklists without a lock, so they
|
||||
// Load the IP list copies from disk and start downloading the lists.
|
||||
// The HTTP handlers read the server's IP lists without a lock, so they
|
||||
// are set before the handlers run.
|
||||
blocklists := blocklist.New(blocklist.Params{
|
||||
Dir: filepath.Join(rw.config.StateDir, blocklistsDirName),
|
||||
Lists: blocklist.Lists(),
|
||||
ipLists := iplist.New(iplist.Params{
|
||||
Dir: filepath.Join(rw.config.StateDir, ipListsDirName),
|
||||
Lists: iplist.Lists(),
|
||||
Logger: rw.logger.Logger,
|
||||
})
|
||||
blocklists.Start(ctx)
|
||||
rw.blocklists = blocklists
|
||||
rw.server.SetBlocklists(blocklists)
|
||||
ipLists.Start(ctx)
|
||||
rw.ipLists = ipLists
|
||||
rw.server.SetIPLists(ipLists)
|
||||
|
||||
// Start HTTP server
|
||||
err = rw.server.Start(ctx)
|
||||
@@ -168,7 +168,7 @@ func (rw *RouteWatch) Run(ctx context.Context) error {
|
||||
|
||||
// Shutdown stops all services in order: the streamer, the handlers, which
|
||||
// write what they hold, the WHOIS fetcher, the database maintainer, the
|
||||
// blocklist downloads and the HTTP server, and last the database, which it
|
||||
// IP list downloads and the HTTP server, and last the database, which it
|
||||
// checkpoints and closes. Each stage waits at most until ctx ends, so
|
||||
// Shutdown returns soon after: a handler logs what it could not write by
|
||||
// then, and the HTTP server closes the connections of requests still
|
||||
@@ -219,8 +219,8 @@ func (rw *RouteWatch) Shutdown(ctx context.Context) {
|
||||
rw.dbMaintainer.Stop(ctx)
|
||||
}
|
||||
|
||||
if rw.blocklists != nil {
|
||||
rw.blocklists.Stop(ctx)
|
||||
if rw.ipLists != nil {
|
||||
rw.ipLists.Stop(ctx)
|
||||
}
|
||||
|
||||
err := rw.server.Stop(ctx)
|
||||
|
||||
@@ -418,7 +418,7 @@ func TestRouteWatchLiveFeed(t *testing.T) {
|
||||
// Create streamer
|
||||
s := streamer.New(logger, metricsTracker)
|
||||
|
||||
// The state directory holds the blocklist copies Run downloads.
|
||||
// The state directory holds the IP list copies Run downloads.
|
||||
cfg := &config.Config{
|
||||
StateDir: t.TempDir(),
|
||||
MaxRuntime: 5 * time.Second,
|
||||
|
||||
+100
-23
@@ -15,8 +15,9 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.eeqj.de/sneak/routewatch/internal/blocklist"
|
||||
"git.eeqj.de/sneak/routewatch/internal/bogon"
|
||||
"git.eeqj.de/sneak/routewatch/internal/database"
|
||||
"git.eeqj.de/sneak/routewatch/internal/iplist"
|
||||
"git.eeqj.de/sneak/routewatch/internal/metrics"
|
||||
"git.eeqj.de/sneak/routewatch/internal/ristypes"
|
||||
"git.eeqj.de/sneak/routewatch/internal/routetable"
|
||||
@@ -765,9 +766,12 @@ type IPLookupResponse struct {
|
||||
Errors []string `json:"errors,omitempty"`
|
||||
}
|
||||
|
||||
// IPLookupResult is the answer for one address: its PTR names, its live route
|
||||
// and that route's AS, and the blocklists that list it. Every result has every
|
||||
// field. The fields of IPInfo are null when the address has no live route.
|
||||
// IPLookupResult is the answer for one address: its PTR names, its flags, its
|
||||
// live route and that route's AS, and the IP lists that contain it. Every
|
||||
// result has every field. The fields of IPInfo are null when the address has
|
||||
// no live route.
|
||||
//
|
||||
//nolint:tagliatelle // snake_case keys, as the Go style guide asks
|
||||
type IPLookupResult struct {
|
||||
IPInfo
|
||||
|
||||
@@ -775,8 +779,29 @@ type IPLookupResult struct {
|
||||
// PTR is empty, never nil, when the address has no PTR names.
|
||||
PTR []string `json:"ptr"`
|
||||
|
||||
// Blocklists has one entry for each blocklist the address is on.
|
||||
Blocklists []blocklist.Listing `json:"blocklists"`
|
||||
Flags IPLookupFlags `json:"flags"`
|
||||
|
||||
// VPNProviders names the VPN lists the address is on. It is empty, never
|
||||
// nil, when there are none.
|
||||
VPNProviders []string `json:"vpn_providers"`
|
||||
|
||||
// IPLists has one entry for each IP list the address is on.
|
||||
IPLists []iplist.Listing `json:"ip_lists"`
|
||||
}
|
||||
|
||||
// IPLookupFlags are the yes-or-no facts about an address. Every result has
|
||||
// them, whether or not the address has a live route.
|
||||
//
|
||||
//nolint:tagliatelle // snake_case keys, as the Go style guide asks
|
||||
type IPLookupFlags struct {
|
||||
// IsTor says that the address is on the Tor exit list.
|
||||
IsTor bool `json:"is_tor"`
|
||||
|
||||
// IsVPN says that the address is on a list of VPN servers.
|
||||
IsVPN bool `json:"is_vpn"`
|
||||
|
||||
// IsBogon says that the address is reserved, as package bogon tells.
|
||||
IsBogon bool `json:"is_bogon"`
|
||||
}
|
||||
|
||||
// handleIPInfo returns a handler that provides comprehensive IP information.
|
||||
@@ -852,12 +877,7 @@ func (s *Server) handleIPInfo() http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
response.Results = append(response.Results, IPLookupResult{
|
||||
IP: ip,
|
||||
PTR: ptrs,
|
||||
IPInfo: ipInfo,
|
||||
Blocklists: s.blocklistListings(ip),
|
||||
})
|
||||
response.Results = append(response.Results, s.ipLookupResult(ip, ptrs, ipInfo))
|
||||
|
||||
if ipInfo.NeedsWHOISRefresh {
|
||||
refreshASNs[*ipInfo.ASN] = true
|
||||
@@ -958,23 +978,80 @@ func ipVersionOf(prefix netip.Prefix) int {
|
||||
return ipVersionV6
|
||||
}
|
||||
|
||||
// blocklistListings returns the blocklists that list ip. It returns an empty
|
||||
// list, never nil, so that an answer's blocklists is [] rather than null.
|
||||
func (s *Server) blocklistListings(ip string) []blocklist.Listing {
|
||||
addr, err := netip.ParseAddr(ip)
|
||||
if s.blocklists == nil || err != nil {
|
||||
return []blocklist.Listing{}
|
||||
// ipLookupResult returns the result for ip, adding its flags and IP lists to
|
||||
// its PTR names and route.
|
||||
func (s *Server) ipLookupResult(ip string, ptrs []string, info IPInfo) IPLookupResult {
|
||||
listings := s.ipListListings(ip)
|
||||
|
||||
return IPLookupResult{
|
||||
IP: ip,
|
||||
PTR: ptrs,
|
||||
IPInfo: info,
|
||||
Flags: ipLookupFlags(ip, listings),
|
||||
VPNProviders: vpnProviders(listings),
|
||||
IPLists: listings,
|
||||
}
|
||||
}
|
||||
|
||||
// vpnProviders returns the names of the VPN lists among listings. It returns
|
||||
// an empty list, never nil, so that an answer's vpn_providers is [] rather
|
||||
// than null.
|
||||
func vpnProviders(listings []iplist.Listing) []string {
|
||||
names := []string{}
|
||||
|
||||
for _, listing := range listings {
|
||||
if listing.VPN {
|
||||
names = append(names, listing.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return s.blocklists.Lookup(addr)
|
||||
return names
|
||||
}
|
||||
|
||||
// ipListListings returns the IP lists that contain ip. It returns an empty
|
||||
// list, never nil, so that an answer's ip_lists is [] rather than null.
|
||||
func (s *Server) ipListListings(ip string) []iplist.Listing {
|
||||
addr, err := netip.ParseAddr(ip)
|
||||
if s.ipLists == nil || err != nil {
|
||||
return []iplist.Listing{}
|
||||
}
|
||||
|
||||
return s.ipLists.Lookup(addr)
|
||||
}
|
||||
|
||||
// ipLookupFlags returns the flags of ip, whose IP list entries are listings.
|
||||
func ipLookupFlags(ip string, listings []iplist.Listing) IPLookupFlags {
|
||||
return IPLookupFlags{
|
||||
IsTor: slices.ContainsFunc(listings, func(l iplist.Listing) bool {
|
||||
return l.Name == iplist.TorExitsList
|
||||
}),
|
||||
IsVPN: slices.ContainsFunc(listings, func(l iplist.Listing) bool {
|
||||
return l.VPN
|
||||
}),
|
||||
IsBogon: isBogon(ip),
|
||||
}
|
||||
}
|
||||
|
||||
// isBogon says whether the address ip is reserved. An IPv4 address written in
|
||||
// IPv6 form counts as the IPv4 address it holds.
|
||||
func isBogon(ip string) bool {
|
||||
addr, err := netip.ParseAddr(ip)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
addr = addr.Unmap()
|
||||
_, reserved := bogon.Prefix(netip.PrefixFrom(addr, addr.BitLen()))
|
||||
|
||||
return reserved
|
||||
}
|
||||
|
||||
// setIPLookupCacheControl lets caches keep an IP lookup answer for the
|
||||
// shortest blocklist interval, the soonest a blocklist copy can change. The
|
||||
// shortest IP list interval, the soonest an IP list copy can change. The
|
||||
// answer about the caller's own address is private, so that a shared cache
|
||||
// does not give it to another caller. Without blocklists it sets nothing.
|
||||
// does not give it to another caller. Without IP lists it sets nothing.
|
||||
func (s *Server) setIPLookupCacheControl(w http.ResponseWriter, ownAddress bool) {
|
||||
if s.blocklists == nil {
|
||||
if s.ipLists == nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -983,7 +1060,7 @@ func (s *Server) setIPLookupCacheControl(w http.ResponseWriter, ownAddress bool)
|
||||
visibility = cacheControlPrivate
|
||||
}
|
||||
|
||||
maxAgeSeconds := int(s.blocklists.ShortestInterval().Seconds())
|
||||
maxAgeSeconds := int(s.ipLists.ShortestInterval().Seconds())
|
||||
w.Header().Set(cacheControlHeader,
|
||||
visibility+cacheControlMaxAge+strconv.Itoa(maxAgeSeconds))
|
||||
}
|
||||
|
||||
@@ -17,11 +17,12 @@ import (
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"git.eeqj.de/sneak/routewatch/internal/blocklist"
|
||||
"git.eeqj.de/sneak/routewatch/internal/config"
|
||||
"git.eeqj.de/sneak/routewatch/internal/database"
|
||||
"git.eeqj.de/sneak/routewatch/internal/iplist"
|
||||
"git.eeqj.de/sneak/routewatch/internal/logger"
|
||||
"git.eeqj.de/sneak/routewatch/internal/metrics"
|
||||
"git.eeqj.de/sneak/routewatch/internal/ristypes"
|
||||
@@ -173,6 +174,9 @@ type tableStats struct {
|
||||
// carried 203.0.113.0/24, the two with kept routes withdrew it, so its origin
|
||||
// keeps no route. The oldest and newest routes are those of the other two
|
||||
// prefixes.
|
||||
//
|
||||
// The requests run in a synctest bubble, whose clock is fake, so a stall on
|
||||
// the host does not use up the handlers' 4-second limit.
|
||||
func TestStatsHandlersAnswerFromMemory(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -218,7 +222,11 @@ func TestStatsHandlersAnswerFromMemory(t *testing.T) {
|
||||
|
||||
for name, handler := range handlers {
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil))
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
handler(rec,
|
||||
httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil))
|
||||
})
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("%s: status %d, want %d; body %s",
|
||||
@@ -253,15 +261,20 @@ func TestStatsHandlersAnswerFromMemory(t *testing.T) {
|
||||
// TestStatsAnswerCarriesChurnPerMinute checks that the stream object of the
|
||||
// /api/v1/stats answer holds route_churn_per_min as a whole number, and no
|
||||
// longer route_churn_per_sec, the moving average it replaces
|
||||
// (https://git.eeqj.de/sneak/routewatch/issues/160).
|
||||
// (https://git.eeqj.de/sneak/routewatch/issues/160). The request runs in a
|
||||
// synctest bubble, whose clock is fake, so a stall on the host does not use up
|
||||
// the handler's 4-second limit.
|
||||
func TestStatsAnswerCarriesChurnPerMinute(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := newServerWithTestRoutes(t)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
s.handleStats()(rec,
|
||||
httptest.NewRequestWithContext(t.Context(), http.MethodGet, statsPath, nil))
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
s.handleStats()(rec,
|
||||
httptest.NewRequestWithContext(t.Context(), http.MethodGet, statsPath, nil))
|
||||
})
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status %d, want %d; body %s", rec.Code, http.StatusOK, rec.Body)
|
||||
@@ -309,18 +322,26 @@ func (heldBackHandler) HeldBackCount() int { return heldBackMess
|
||||
|
||||
// TestStatsAnswerGivesHowManyMessagesAHandlerHoldsBack registers a handler
|
||||
// that holds back messages. Its figures in /api/v1/stats, which the status
|
||||
// page shows, must give how many.
|
||||
// page shows, must give how many. The request runs in a synctest bubble, whose
|
||||
// clock is fake, so a stall on the host does not use up the handler's 4-second
|
||||
// limit.
|
||||
func TestStatsAnswerGivesHowManyMessagesAHandlerHoldsBack(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := newServerWithTestRoutes(t)
|
||||
s.streamer.RegisterHandler(heldBackHandler{})
|
||||
|
||||
var answer []byte
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
answer = get(t, s, statsPath).Body.Bytes()
|
||||
})
|
||||
|
||||
var body struct {
|
||||
Data StatsResponse `json:"data"`
|
||||
}
|
||||
|
||||
err := json.Unmarshal(get(t, s, statsPath).Body.Bytes(), &body)
|
||||
err := json.Unmarshal(answer, &body)
|
||||
if err != nil {
|
||||
t.Fatalf("decoding the answer: %v", err)
|
||||
}
|
||||
@@ -364,7 +385,9 @@ type unitStats struct {
|
||||
// names. They used to be strings with the unit in them, such as "1h18m34s" or
|
||||
// "1.1 GB" (https://git.eeqj.de/sneak/routewatch/issues/199). The stream has
|
||||
// never connected, so the uptime is 0. The memory use in /api/v1/stats is the
|
||||
// same number of bytes as its gc.heap_alloc_bytes.
|
||||
// same number of bytes as its gc.heap_alloc_bytes. The requests run in a
|
||||
// synctest bubble, whose clock is fake, so a stall on the host does not use up
|
||||
// the handlers' 4-second limit.
|
||||
func TestStatsAnswersGiveUnitsInFieldNames(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -374,7 +397,11 @@ func TestStatsAnswersGiveUnitsInFieldNames(t *testing.T) {
|
||||
s.SetASNFetcher(fixedIntervalASNFetcher{interval: fetchInterval})
|
||||
|
||||
for _, path := range []string{statusJSONPath, statsPath} {
|
||||
answer := get(t, s, path).Body.Bytes()
|
||||
var answer []byte
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
answer = get(t, s, path).Body.Bytes()
|
||||
})
|
||||
|
||||
var body struct {
|
||||
Data unitStats `json:"data"`
|
||||
@@ -415,82 +442,89 @@ func TestStatsAnswersGiveUnitsInFieldNames(t *testing.T) {
|
||||
// connection_duration_seconds of /api/v1/stats is null while the stream is not
|
||||
// connected, and a whole number of seconds once it is. It used to be the
|
||||
// string "disconnected", or a Go duration such as "1h18m34s"
|
||||
// (https://git.eeqj.de/sneak/routewatch/issues/199).
|
||||
// (https://git.eeqj.de/sneak/routewatch/issues/199). The test runs in a
|
||||
// synctest bubble, whose clock is fake, so a stall on the host does not use up
|
||||
// the handler's 4-second limit.
|
||||
func TestStatsAnswerGivesConnectionDurationInSeconds(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := newServerWithTestRoutes(t)
|
||||
|
||||
connectionDuration := func() json.RawMessage {
|
||||
answer := get(t, s, statsPath).Body.Bytes()
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
connectionDuration := func() json.RawMessage {
|
||||
answer := get(t, s, statsPath).Body.Bytes()
|
||||
|
||||
var body struct {
|
||||
Data map[string]json.RawMessage `json:"data"`
|
||||
var body struct {
|
||||
Data map[string]json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
err := json.Unmarshal(answer, &body)
|
||||
if err != nil {
|
||||
t.Fatalf("decoding the answer: %v; answer %s", err, answer)
|
||||
}
|
||||
|
||||
duration, ok := body.Data["connection_duration_seconds"]
|
||||
if !ok {
|
||||
t.Fatalf("no connection_duration_seconds: %s", answer)
|
||||
}
|
||||
|
||||
return duration
|
||||
}
|
||||
|
||||
err := json.Unmarshal(answer, &body)
|
||||
if err != nil {
|
||||
t.Fatalf("decoding the answer: %v; answer %s", err, answer)
|
||||
disconnected := connectionDuration()
|
||||
if string(disconnected) != "null" {
|
||||
t.Errorf("disconnected: connection_duration_seconds = %s, want null",
|
||||
disconnected)
|
||||
}
|
||||
|
||||
duration, ok := body.Data["connection_duration_seconds"]
|
||||
if !ok {
|
||||
t.Fatalf("no connection_duration_seconds: %s", answer)
|
||||
s.streamer.GetMetricsTracker().SetConnected(true)
|
||||
|
||||
var seconds int64
|
||||
|
||||
connected := connectionDuration()
|
||||
|
||||
err := json.Unmarshal(connected, &seconds)
|
||||
if err != nil || seconds != 0 {
|
||||
t.Errorf("just connected: connection_duration_seconds = %s, want 0",
|
||||
connected)
|
||||
}
|
||||
|
||||
return duration
|
||||
}
|
||||
|
||||
disconnected := connectionDuration()
|
||||
if string(disconnected) != "null" {
|
||||
t.Errorf("disconnected: connection_duration_seconds = %s, want null",
|
||||
disconnected)
|
||||
}
|
||||
|
||||
s.streamer.GetMetricsTracker().SetConnected(true)
|
||||
|
||||
var seconds int64
|
||||
|
||||
connected := connectionDuration()
|
||||
|
||||
err := json.Unmarshal(connected, &seconds)
|
||||
if err != nil || seconds != 0 {
|
||||
t.Errorf("just connected: connection_duration_seconds = %s, want 0",
|
||||
connected)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestStreamDurationsCountSeconds checks that the uptime and the connection
|
||||
// duration of a stream that connected 90 seconds ago are both 90. A stream
|
||||
// that has never connected has an uptime of 0, and one that is not connected
|
||||
// has no connection duration.
|
||||
// has no connection duration. The test runs in a synctest bubble, whose clock
|
||||
// is fake, so a stall on the host does not add to the 90 seconds.
|
||||
func TestStreamDurationsCountSeconds(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const connectedFor = 90 * time.Second
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
const connectedFor = 90 * time.Second
|
||||
|
||||
connectedSince := time.Now().Add(-connectedFor)
|
||||
want := int64(connectedFor / time.Second)
|
||||
connectedSince := time.Now().Add(-connectedFor)
|
||||
want := int64(connectedFor / time.Second)
|
||||
|
||||
if got := uptimeSeconds(connectedSince); got != want {
|
||||
t.Errorf("uptimeSeconds = %d, want %d", got, want)
|
||||
}
|
||||
if got := uptimeSeconds(connectedSince); got != want {
|
||||
t.Errorf("uptimeSeconds = %d, want %d", got, want)
|
||||
}
|
||||
|
||||
if got := uptimeSeconds(time.Time{}); got != 0 {
|
||||
t.Errorf("uptimeSeconds before any connection = %d, want 0", got)
|
||||
}
|
||||
if got := uptimeSeconds(time.Time{}); got != 0 {
|
||||
t.Errorf("uptimeSeconds before any connection = %d, want 0", got)
|
||||
}
|
||||
|
||||
switch got := connectionDurationSeconds(true, connectedSince); {
|
||||
case got == nil:
|
||||
t.Errorf("connectionDurationSeconds = nil, want %d", want)
|
||||
case *got != want:
|
||||
t.Errorf("connectionDurationSeconds = %d, want %d", *got, want)
|
||||
}
|
||||
switch got := connectionDurationSeconds(true, connectedSince); {
|
||||
case got == nil:
|
||||
t.Errorf("connectionDurationSeconds = nil, want %d", want)
|
||||
case *got != want:
|
||||
t.Errorf("connectionDurationSeconds = %d, want %d", *got, want)
|
||||
}
|
||||
|
||||
if got := connectionDurationSeconds(false, connectedSince); got != nil {
|
||||
t.Errorf("connectionDurationSeconds while not connected = %d, want nil",
|
||||
*got)
|
||||
}
|
||||
if got := connectionDurationSeconds(false, connectedSince); got != nil {
|
||||
t.Errorf("connectionDurationSeconds while not connected = %d, want nil",
|
||||
*got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// newTestTable returns a routing table that holds a route for testPrefixV4,
|
||||
@@ -1134,7 +1168,9 @@ func (failingDB) GetPrefixFirstSeen(
|
||||
// with the driver's error text. It also sends a prefix that does not parse.
|
||||
// No answer may carry the driver's or the prefix parser's text. Before the fix
|
||||
// the answers sent it to the client
|
||||
// (https://git.eeqj.de/sneak/routewatch/issues/108).
|
||||
// (https://git.eeqj.de/sneak/routewatch/issues/108). The requests run in a
|
||||
// synctest bubble, whose clock is fake, so a stall on the host does not use up
|
||||
// the stats handlers' 4-second limit.
|
||||
func TestJSONRoutesDoNotSendErrorDetails(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -1155,8 +1191,11 @@ func TestJSONRoutesDoNotSendErrorDetails(t *testing.T) {
|
||||
|
||||
for _, tt := range tests {
|
||||
rec := httptest.NewRecorder()
|
||||
s.router.ServeHTTP(rec, httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodGet, tt.path, nil))
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
s.router.ServeHTTP(rec, httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodGet, tt.path, nil))
|
||||
})
|
||||
|
||||
if rec.Code != tt.wantCode {
|
||||
t.Errorf("%s: status %d, want %d; body %s",
|
||||
@@ -1397,8 +1436,11 @@ func TestIPLookupKeepsRouteWhenPTRLookupDoesNotAnswer(t *testing.T) {
|
||||
s := newServerWithTestRoutes(t)
|
||||
s.resolver = &fakeResolver{ptrNeverAnswers: true}
|
||||
|
||||
// The request's time limit passes after the PTR lookup's.
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*ptrLookupTimeout)
|
||||
// The request's time limit passes well after the PTR lookup's, so that a
|
||||
// stall on a busy host does not use up the difference.
|
||||
const requestTimeLimit = ptrLookupTimeout + 15*time.Second
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), requestTimeLimit)
|
||||
defer cancel()
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
@@ -1428,50 +1470,192 @@ func TestIPLookupKeepsRouteWhenPTRLookupDoesNotAnswer(t *testing.T) {
|
||||
// newServerWithTestRoutes stores a route for.
|
||||
const addrInTestPrefixV6 = "2001:db8::1"
|
||||
|
||||
// testBlocklistInterval is fakeBlocklists' shortest interval.
|
||||
const testBlocklistInterval = 15 * time.Minute
|
||||
// testIPListInterval is fakeIPLists' shortest interval.
|
||||
const testIPListInterval = 15 * time.Minute
|
||||
|
||||
// ownAddressPath is the IP lookup of the caller's own address.
|
||||
const ownAddressPath = "/ip/"
|
||||
|
||||
// listedUnroutedAddr is an address that fakeBlocklists lists, outside the
|
||||
// routes newServerWithTestRoutes stores.
|
||||
// listedUnroutedAddr is an address that fakeIPLists lists, outside the routes
|
||||
// newServerWithTestRoutes stores.
|
||||
const listedUnroutedAddr = "203.0.113.1"
|
||||
|
||||
// fakeBlocklists has one list, which lists addrInTestPrefixV4 and
|
||||
// listedUnroutedAddr and no other address.
|
||||
type fakeBlocklists struct{}
|
||||
// torExitAddr is the address that fakeIPLists lists on the Tor exit list.
|
||||
const torExitAddr = "203.0.113.2"
|
||||
|
||||
func testListing() blocklist.Listing {
|
||||
return blocklist.Listing{
|
||||
// The addresses that fakeIPLists lists on one and on two VPN lists, and the
|
||||
// names of those lists.
|
||||
const (
|
||||
oneVPNListAddr = "203.0.113.3"
|
||||
twoVPNListsAddr = "203.0.113.4"
|
||||
testVPNList = "test_vpn"
|
||||
otherTestVPN = "other_test_vpn"
|
||||
)
|
||||
|
||||
// fakeIPLists has four lists. The test list holds addrInTestPrefixV4,
|
||||
// listedUnroutedAddr and twoVPNListsAddr. The Tor exit list holds torExitAddr.
|
||||
// The test VPN list holds oneVPNListAddr and twoVPNListsAddr, and the other
|
||||
// test VPN list holds twoVPNListsAddr.
|
||||
type fakeIPLists struct{}
|
||||
|
||||
func testListing() iplist.Listing {
|
||||
return iplist.Listing{
|
||||
Name: "test_list",
|
||||
Description: "On the test list",
|
||||
Updated: time.Date(2026, 10, 27, 4, 0, 0, 0, time.UTC),
|
||||
}
|
||||
}
|
||||
|
||||
func (fakeBlocklists) Lookup(addr netip.Addr) []blocklist.Listing {
|
||||
func (fakeIPLists) Lookup(addr netip.Addr) []iplist.Listing {
|
||||
if addr == netip.MustParseAddr(addrInTestPrefixV4) ||
|
||||
addr == netip.MustParseAddr(listedUnroutedAddr) {
|
||||
return []blocklist.Listing{testListing()}
|
||||
return []iplist.Listing{testListing()}
|
||||
}
|
||||
|
||||
return []blocklist.Listing{}
|
||||
if addr == netip.MustParseAddr(torExitAddr) {
|
||||
return []iplist.Listing{{Name: iplist.TorExitsList}}
|
||||
}
|
||||
|
||||
if addr == netip.MustParseAddr(oneVPNListAddr) {
|
||||
return []iplist.Listing{{Name: testVPNList, VPN: true}}
|
||||
}
|
||||
|
||||
if addr == netip.MustParseAddr(twoVPNListsAddr) {
|
||||
return []iplist.Listing{
|
||||
{Name: otherTestVPN, VPN: true},
|
||||
testListing(),
|
||||
{Name: testVPNList, VPN: true},
|
||||
}
|
||||
}
|
||||
|
||||
return []iplist.Listing{}
|
||||
}
|
||||
|
||||
func (fakeBlocklists) ShortestInterval() time.Duration {
|
||||
return testBlocklistInterval
|
||||
func (fakeIPLists) ShortestInterval() time.Duration {
|
||||
return testIPListInterval
|
||||
}
|
||||
|
||||
// TestIPLookupReportsBlocklists looks up two routed addresses, one of them on
|
||||
// a blocklist. The listed address's result names the list, says what it means
|
||||
// and when it was updated. The other's result has an empty list.
|
||||
func TestIPLookupReportsBlocklists(t *testing.T) {
|
||||
// TestIPLookupFlags looks up addresses with and without a route. Every result
|
||||
// has every flag, under the JSON keys the API documents.
|
||||
func TestIPLookupFlags(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := newServerWithTestRoutes(t)
|
||||
s.resolver = &fakeResolver{}
|
||||
s.SetBlocklists(fakeBlocklists{})
|
||||
s.SetIPLists(fakeIPLists{})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
addr string
|
||||
tor bool
|
||||
bogon bool
|
||||
}{
|
||||
{"on the Tor exit list", torExitAddr, true, true},
|
||||
{"on another list", listedUnroutedAddr, false, true},
|
||||
{"routed IPv4", addrInTestPrefixV4, false, true},
|
||||
{"routed IPv6", addrInTestPrefixV6, false, true},
|
||||
{"private IPv4", "10.0.0.1", false, true},
|
||||
{"loopback IPv4", "127.0.0.1", false, true},
|
||||
{"public IPv4", "1.1.1.1", false, false},
|
||||
{"private IPv6", "fd00::1", false, true},
|
||||
{"loopback IPv6", "::1", false, true},
|
||||
{"public IPv6", "2606:4700:4700::1111", false, false},
|
||||
{"public IPv4 in IPv6 form", "::ffff:1.1.1.1", false, false},
|
||||
{"private IPv4 in IPv6 form", "::ffff:10.0.0.1", false, true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
path := "/api/v1/ip/" + tt.addr
|
||||
|
||||
results := resultFields(t, get(t, s, path).Body.Bytes())
|
||||
if len(results) != 1 {
|
||||
t.Fatalf("%s: %d results, want 1", path, len(results))
|
||||
}
|
||||
|
||||
var got map[string]bool
|
||||
|
||||
err := json.Unmarshal(results[0]["flags"], &got)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: decoding flags %s: %v", path, results[0]["flags"], err)
|
||||
}
|
||||
|
||||
want := map[string]bool{
|
||||
"is_tor": tt.tor, "is_vpn": false, "is_bogon": tt.bogon,
|
||||
}
|
||||
if !maps.Equal(got, want) {
|
||||
t.Errorf("%s: flags %v, want %v", path, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestIPLookupReportsVPNProviders looks up addresses on no list, on a list
|
||||
// that is not a VPN list, on one VPN list and on two. is_vpn says whether any
|
||||
// VPN list holds the address, and vpn_providers names only those lists. An
|
||||
// address on none has [], not null.
|
||||
func TestIPLookupReportsVPNProviders(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := newServerWithTestRoutes(t)
|
||||
s.resolver = &fakeResolver{}
|
||||
s.SetIPLists(fakeIPLists{})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
addr string
|
||||
isVPN string
|
||||
providers string
|
||||
}{
|
||||
{"on no list", "1.1.1.1", "false", `[]`},
|
||||
{"on a list that is not a VPN list", listedUnroutedAddr, "false", `[]`},
|
||||
{"on one VPN list", oneVPNListAddr, "true", `["` + testVPNList + `"]`},
|
||||
{
|
||||
"on two VPN lists", twoVPNListsAddr, "true",
|
||||
`["` + otherTestVPN + `","` + testVPNList + `"]`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
path := "/api/v1/ip/" + tt.addr
|
||||
|
||||
results := resultFields(t, get(t, s, path).Body.Bytes())
|
||||
if len(results) != 1 {
|
||||
t.Fatalf("%s: %d results, want 1", path, len(results))
|
||||
}
|
||||
|
||||
var flags map[string]json.RawMessage
|
||||
|
||||
err := json.Unmarshal(results[0]["flags"], &flags)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: decoding flags %s: %v", path, results[0]["flags"], err)
|
||||
}
|
||||
|
||||
if got := string(flags["is_vpn"]); got != tt.isVPN {
|
||||
t.Errorf("%s: is_vpn %s, want %s", path, got, tt.isVPN)
|
||||
}
|
||||
|
||||
if got := string(results[0]["vpn_providers"]); got != tt.providers {
|
||||
t.Errorf("%s: vpn_providers %s, want %s", path, got, tt.providers)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestIPLookupReportsIPLists looks up two routed addresses, one of them on an
|
||||
// IP list. The listed address's result names the list, says what it means and
|
||||
// when it was updated. The other's result has an empty list.
|
||||
func TestIPLookupReportsIPLists(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := newServerWithTestRoutes(t)
|
||||
s.resolver = &fakeResolver{}
|
||||
s.SetIPLists(fakeIPLists{})
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
s.router.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(),
|
||||
@@ -1498,15 +1682,15 @@ func TestIPLookupReportsBlocklists(t *testing.T) {
|
||||
|
||||
want := testListing()
|
||||
|
||||
listed := results[0].Blocklists
|
||||
listed := results[0].IPLists
|
||||
if len(listed) != 1 || listed[0].Name != want.Name ||
|
||||
listed[0].Description != want.Description ||
|
||||
!listed[0].Updated.Equal(want.Updated) {
|
||||
t.Errorf("%s: blocklists %+v, want [%+v]", results[0].IP, listed, want)
|
||||
t.Errorf("%s: ip_lists %+v, want [%+v]", results[0].IP, listed, want)
|
||||
}
|
||||
|
||||
if !strings.Contains(rec.Body.String(), `"blocklists":[]`) {
|
||||
t.Errorf("answer %s, want an empty blocklists list for %s",
|
||||
if !strings.Contains(rec.Body.String(), `"ip_lists":[]`) {
|
||||
t.Errorf("answer %s, want an empty ip_lists list for %s",
|
||||
rec.Body, addrInTestPrefixV6)
|
||||
}
|
||||
}
|
||||
@@ -1536,20 +1720,19 @@ func resultFields(t *testing.T, answer []byte) []map[string]json.RawMessage {
|
||||
return body.Data.Results
|
||||
}
|
||||
|
||||
// TestIPLookupReportsBlocklistsOfAnAddressWithNoRoute looks up a listed
|
||||
// address that has no live route, alone and beside a routed address. Each
|
||||
// answer is 200 and has a result for the address, with its blocklists and
|
||||
// every route field set to null. Before the fix the lookup of that address
|
||||
// alone answered 404, and beside a routed address it was only named in
|
||||
// errors, so its blocklists were never reported. After that fix the result
|
||||
// still left out the route fields
|
||||
// (https://git.eeqj.de/sneak/routewatch/issues/200).
|
||||
func TestIPLookupReportsBlocklistsOfAnAddressWithNoRoute(t *testing.T) {
|
||||
// TestIPLookupReportsIPListsOfAnAddressWithNoRoute looks up a listed address
|
||||
// that has no live route, alone and beside a routed address. Each answer is
|
||||
// 200 and has a result for the address, with its IP lists and every route
|
||||
// field set to null. Before the fix the lookup of that address alone answered
|
||||
// 404, and beside a routed address it was only named in errors, so its IP
|
||||
// lists were never reported. After that fix the result still left out the
|
||||
// route fields (https://git.eeqj.de/sneak/routewatch/issues/200).
|
||||
func TestIPLookupReportsIPListsOfAnAddressWithNoRoute(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := newServerWithTestRoutes(t)
|
||||
s.resolver = &fakeResolver{}
|
||||
s.SetBlocklists(fakeBlocklists{})
|
||||
s.SetIPLists(fakeIPLists{})
|
||||
|
||||
// routeFields are the fields of a result that come from the address's
|
||||
// route and that route's origin AS.
|
||||
@@ -1605,10 +1788,10 @@ func TestIPLookupReportsBlocklistsOfAnAddressWithNoRoute(t *testing.T) {
|
||||
}
|
||||
|
||||
result := body.Data.Results[i]
|
||||
if len(result.Blocklists) != 1 ||
|
||||
result.Blocklists[0].Name != testListing().Name {
|
||||
t.Errorf("%s: blocklists %+v, want [%+v]",
|
||||
target, result.Blocklists, testListing())
|
||||
if len(result.IPLists) != 1 ||
|
||||
result.IPLists[0].Name != testListing().Name {
|
||||
t.Errorf("%s: ip_lists %+v, want [%+v]",
|
||||
target, result.IPLists, testListing())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1629,7 +1812,7 @@ func TestIPLookupResultsHaveTheSameFields(t *testing.T) {
|
||||
s.resolver = &fakeResolver{hosts: map[string][]string{
|
||||
twoAddressHostName: {addrInTestPrefixV4, listedUnroutedAddr},
|
||||
}}
|
||||
s.SetBlocklists(fakeBlocklists{})
|
||||
s.SetIPLists(fakeIPLists{})
|
||||
|
||||
// want is the fields of the first result.
|
||||
var want []string
|
||||
@@ -1684,7 +1867,7 @@ func TestIPLookupOfAnAddressWithoutPTRNamesOrStoredNetblock(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestIPLookupAnswersMayBeCached checks the Cache-Control header of the IP
|
||||
// lookup answers. Caches may keep them for the blocklists' shortest interval,
|
||||
// lookup answers. Caches may keep them for the IP lists' shortest interval,
|
||||
// and only the caller's own browser may keep the answer about the caller's
|
||||
// own address.
|
||||
func TestIPLookupAnswersMayBeCached(t *testing.T) {
|
||||
@@ -1692,7 +1875,7 @@ func TestIPLookupAnswersMayBeCached(t *testing.T) {
|
||||
|
||||
s := newServerWithTestRoutes(t)
|
||||
s.resolver = &fakeResolver{}
|
||||
s.SetBlocklists(fakeBlocklists{})
|
||||
s.SetIPLists(fakeIPLists{})
|
||||
|
||||
tests := []struct {
|
||||
path string
|
||||
@@ -2226,9 +2409,13 @@ func settledGoroutineCount() int {
|
||||
return prev
|
||||
}
|
||||
|
||||
// waitForGoroutines waits until the goroutine count drops to target or below.
|
||||
// waitForGoroutines waits up to 15 seconds for the goroutine count to drop to
|
||||
// target or below.
|
||||
func waitForGoroutines(target int) bool {
|
||||
for range 100 {
|
||||
const maxWait = 15 * time.Second
|
||||
|
||||
deadline := time.Now().Add(maxWait)
|
||||
for time.Now().Before(deadline) {
|
||||
if runtime.NumGoroutine() <= target {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -76,7 +76,9 @@ func asLink(asn int) string {
|
||||
}
|
||||
|
||||
// TestHomePageCardsShowTheTableFigures fills a routing table and the asns
|
||||
// table, works out the cards, and checks that each card shows its figure.
|
||||
// table, works out the cards, and checks that each card shows its figure. The
|
||||
// cards are worked out in a synctest bubble, whose clock is fake, so a stall on
|
||||
// the host does not use up the 4-second limit on their database read.
|
||||
func TestHomePageCardsShowTheTableFigures(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -95,7 +97,9 @@ func TestHomePageCardsShowTheTableFigures(t *testing.T) {
|
||||
t.Fatalf("GetOrCreateASNBatch: %v", err)
|
||||
}
|
||||
|
||||
s.refreshHomeCards(t.Context())
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
s.refreshHomeCards(t.Context())
|
||||
})
|
||||
|
||||
page := get(t, s, "/").Body.String()
|
||||
|
||||
@@ -279,7 +283,7 @@ func TestKeepHomeCardsFreshWorksThemOutEveryInterval(t *testing.T) {
|
||||
|
||||
const (
|
||||
interval = 10 * time.Millisecond
|
||||
maxWait = 5 * time.Second
|
||||
maxWait = 15 * time.Second
|
||||
)
|
||||
|
||||
table := emptyTable()
|
||||
@@ -321,7 +325,7 @@ func TestKeepHomeCardsFreshWorksThemOutEveryInterval(t *testing.T) {
|
||||
func TestStartedServerWorksOutTheCards(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const maxWait = 5 * time.Second
|
||||
const maxWait = 15 * time.Second
|
||||
|
||||
s := newServerWithTable(t, newCardsTable())
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"git.eeqj.de/sneak/routewatch/internal/config"
|
||||
@@ -163,6 +164,10 @@ func TestJSONAnswersPutNoUnitInAString(t *testing.T) {
|
||||
// router and the middleware write. Before the fix a panic in a handler, and a
|
||||
// method /status.json or the health check does not take, answered with an
|
||||
// empty body (https://git.eeqj.de/sneak/routewatch/issues/201).
|
||||
//
|
||||
// The requests run in a synctest bubble, whose clock is fake, so a stall on
|
||||
// the host does not use up the 2-second limit of the health check or the
|
||||
// 4-second limit of the stats handlers.
|
||||
func TestJSONAnswersCarryMeta(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -181,6 +186,10 @@ func TestJSONAnswersCarryMeta(t *testing.T) {
|
||||
s.router.Get(panicsPath, JSONValidationMiddleware(http.HandlerFunc(
|
||||
func(http.ResponseWriter, *http.Request) { panic(errDiskIO) })).ServeHTTP)
|
||||
|
||||
failing := New(failingDB{}, newTestTable(),
|
||||
streamer.New(logger.New(), metrics.New()), logger.New(), &config.Config{})
|
||||
failing.resolver = &fakeResolver{}
|
||||
|
||||
tests := []struct {
|
||||
method string
|
||||
path string
|
||||
@@ -216,42 +225,40 @@ func TestJSONAnswersCarryMeta(t *testing.T) {
|
||||
{http.MethodGet, panicsPath, http.StatusInternalServerError},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
checkAnswerCarriesMeta(t, s, httptest.NewRequestWithContext(
|
||||
t.Context(), tt.method, tt.path, nil), tt.wantCode)
|
||||
}
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
checkAnswerCarriesMeta(t, s, httptest.NewRequestWithContext(
|
||||
t.Context(), tt.method, tt.path, nil), tt.wantCode)
|
||||
}
|
||||
|
||||
// A request whose time limit has already passed answers 504. The handlers
|
||||
// write the answers of the first five routes, and the JSON check on the
|
||||
// route writes the last.
|
||||
pastTimeLimit, cancel := context.WithDeadline(t.Context(), time.Now())
|
||||
defer cancel()
|
||||
// A request whose time limit has already passed answers 504. The
|
||||
// handlers write the answers of the first five routes, and the JSON
|
||||
// check on the route writes the last.
|
||||
pastTimeLimit, cancel := context.WithDeadline(t.Context(), time.Now())
|
||||
defer cancel()
|
||||
|
||||
for _, path := range []string{
|
||||
statusJSONPath, statsPath, "/ip/" + addrInTestPrefixV4,
|
||||
"/api/v1/ip/" + addrInTestPrefixV4, asJSONPath, writesNothingPath,
|
||||
} {
|
||||
checkAnswerCarriesMeta(t, s, httptest.NewRequestWithContext(
|
||||
pastTimeLimit, http.MethodGet, path, nil), http.StatusGatewayTimeout)
|
||||
}
|
||||
for _, path := range []string{
|
||||
statusJSONPath, statsPath, "/ip/" + addrInTestPrefixV4,
|
||||
"/api/v1/ip/" + addrInTestPrefixV4, asJSONPath, writesNothingPath,
|
||||
} {
|
||||
checkAnswerCarriesMeta(t, s, httptest.NewRequestWithContext(
|
||||
pastTimeLimit, http.MethodGet, path, nil), http.StatusGatewayTimeout)
|
||||
}
|
||||
|
||||
// With a store whose reads fail, the health check answers 503, and the
|
||||
// handlers of the other routes 500.
|
||||
failing := New(failingDB{}, newTestTable(),
|
||||
streamer.New(logger.New(), metrics.New()), logger.New(), &config.Config{})
|
||||
failing.resolver = &fakeResolver{}
|
||||
|
||||
checkAnswerCarriesMeta(t, failing, httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodGet, healthCheckPath, nil),
|
||||
http.StatusServiceUnavailable)
|
||||
|
||||
for _, path := range []string{
|
||||
statusJSONPath, statsPath, asJSONPath,
|
||||
"/api/v1/ip/" + addrInTestPrefixV4, "/ip/" + addrInTestPrefixV4,
|
||||
} {
|
||||
// With a store whose reads fail, the health check answers 503, and
|
||||
// the handlers of the other routes 500.
|
||||
checkAnswerCarriesMeta(t, failing, httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodGet, path, nil), http.StatusInternalServerError)
|
||||
}
|
||||
t.Context(), http.MethodGet, healthCheckPath, nil),
|
||||
http.StatusServiceUnavailable)
|
||||
|
||||
for _, path := range []string{
|
||||
statusJSONPath, statsPath, asJSONPath,
|
||||
"/api/v1/ip/" + addrInTestPrefixV4, "/ip/" + addrInTestPrefixV4,
|
||||
} {
|
||||
checkAnswerCarriesMeta(t, failing, httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodGet, path, nil), http.StatusInternalServerError)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// checkAnswerCarriesMeta serves req through the server's router, and checks
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
)
|
||||
|
||||
// TestRoutesAnswerHEAD sends HEAD for a page and JSON routes through the
|
||||
@@ -12,15 +13,23 @@ import (
|
||||
// lookup of the caller's own address, are in the list because chi's GetHead
|
||||
// does not reach them. Before the fix every route answered HEAD with 405
|
||||
// (https://git.eeqj.de/sneak/routewatch/issues/111).
|
||||
//
|
||||
// The requests run in a synctest bubble, whose clock is fake, so a stall on
|
||||
// the host does not use up the stats handlers' 4-second limit. The resolver
|
||||
// is fake because no time limit would cut off a real DNS lookup in a bubble.
|
||||
func TestRoutesAnswerHEAD(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := newServerWithTestRoutes(t)
|
||||
s.resolver = &fakeResolver{}
|
||||
|
||||
for _, path := range []string{"/", statusJSONPath, statsPath, "/ip", "/ip/"} {
|
||||
rec := httptest.NewRecorder()
|
||||
s.router.ServeHTTP(rec, httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodHead, path, nil))
|
||||
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
s.router.ServeHTTP(rec, httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodHead, path, nil))
|
||||
})
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("HEAD %s: status %d, want %d; body %s",
|
||||
|
||||
+10
-10
@@ -22,9 +22,9 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.eeqj.de/sneak/routewatch/internal/blocklist"
|
||||
"git.eeqj.de/sneak/routewatch/internal/config"
|
||||
"git.eeqj.de/sneak/routewatch/internal/database"
|
||||
"git.eeqj.de/sneak/routewatch/internal/iplist"
|
||||
"git.eeqj.de/sneak/routewatch/internal/logger"
|
||||
"git.eeqj.de/sneak/routewatch/internal/routetable"
|
||||
"git.eeqj.de/sneak/routewatch/internal/streamer"
|
||||
@@ -45,10 +45,10 @@ type ASNFetcher interface {
|
||||
GetStats() ASNFetcherStats
|
||||
}
|
||||
|
||||
// Blocklists tells which public blocklists list an address, from copies it
|
||||
// keeps in memory, as *blocklist.Blocklists does.
|
||||
type Blocklists interface {
|
||||
Lookup(addr netip.Addr) []blocklist.Listing
|
||||
// IPLists tells which public IP lists contain an address, from copies it keeps
|
||||
// in memory, as *iplist.IPLists does.
|
||||
type IPLists interface {
|
||||
Lookup(addr netip.Addr) []iplist.Listing
|
||||
ShortestInterval() time.Duration
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ type Server struct {
|
||||
port int
|
||||
srv *http.Server
|
||||
asnFetcher ASNFetcher
|
||||
blocklists Blocklists
|
||||
ipLists IPLists
|
||||
|
||||
// trustedProxies are the reverse proxies whose X-Forwarded-For header
|
||||
// RealIPMiddleware believes
|
||||
@@ -202,8 +202,8 @@ func (s *Server) SetASNFetcher(fetcher ASNFetcher) {
|
||||
s.asnFetcher = fetcher
|
||||
}
|
||||
|
||||
// SetBlocklists sets the blocklists the IP lookups report. Call it before
|
||||
// Start: the handlers read the blocklists without a lock.
|
||||
func (s *Server) SetBlocklists(blocklists Blocklists) {
|
||||
s.blocklists = blocklists
|
||||
// SetIPLists sets the IP lists the IP lookups report. Call it before Start:
|
||||
// the handlers read the IP lists without a lock.
|
||||
func (s *Server) SetIPLists(ipLists IPLists) {
|
||||
s.ipLists = ipLists
|
||||
}
|
||||
@@ -22,10 +22,10 @@ func TestStopClosesTheConnectionOfARequestStillRunning(t *testing.T) {
|
||||
stopDeadline = 100 * time.Millisecond
|
||||
// waitTimeout is how long the test waits for the request to reach
|
||||
// the handler, and then for the client to see its connection closed.
|
||||
waitTimeout = 2 * time.Second
|
||||
waitTimeout = 15 * time.Second
|
||||
// readHeaderTimeout bounds the test server's read of the request
|
||||
// header, as every http.Server must.
|
||||
readHeaderTimeout = time.Second
|
||||
readHeaderTimeout = waitTimeout
|
||||
)
|
||||
|
||||
release := make(chan struct{})
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"git.eeqj.de/sneak/routewatch/internal/logger"
|
||||
@@ -398,7 +399,7 @@ func TestStopQueuesTheHeldStateMessages(t *testing.T) {
|
||||
const (
|
||||
held = 2
|
||||
lines = held + 1
|
||||
maxWait = 5 * time.Second
|
||||
maxWait = 15 * time.Second
|
||||
)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(
|
||||
@@ -478,15 +479,15 @@ func TestStopQueuesTheHeldStateMessages(t *testing.T) {
|
||||
// TestStopReturnsByItsDeadline stops a streamer whose handler has a full queue
|
||||
// and a STATE message held for it, and a worker that stays busy until the test
|
||||
// ends, as one does whose handler waits for a database write. Stop must return
|
||||
// within its deadline plus a small margin instead of waiting for room on the
|
||||
// queue and for the worker, and log as not handed over the held message and
|
||||
// every message on the queue.
|
||||
// within its deadline plus a margin instead of waiting for room on the queue
|
||||
// and for the worker, and log as not handed over the held message and every
|
||||
// message on the queue.
|
||||
func TestStopReturnsByItsDeadline(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const (
|
||||
deadline = 100 * time.Millisecond
|
||||
margin = 2 * time.Second
|
||||
margin = 15 * time.Second
|
||||
)
|
||||
|
||||
var logs bytes.Buffer
|
||||
@@ -577,7 +578,7 @@ func TestStopBeforeMessageReachesQueues(t *testing.T) {
|
||||
func TestReconnectWhenStreamEnds(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
endResponse := func(http.ResponseWriter, *http.Request) {}
|
||||
endResponse := pipeTransport{write: func(context.Context, io.Writer) {}}
|
||||
checkReconnect(t, endResponse, streamIdleTimeout)
|
||||
}
|
||||
|
||||
@@ -589,9 +590,8 @@ func TestReconnectWhenStreamGoesIdle(t *testing.T) {
|
||||
|
||||
const idleTimeout = 50 * time.Millisecond
|
||||
|
||||
holdResponse := func(w http.ResponseWriter, r *http.Request) {
|
||||
flush(w)
|
||||
<-r.Context().Done()
|
||||
holdResponse := pipeTransport{
|
||||
write: func(ctx context.Context, _ io.Writer) { <-ctx.Done() },
|
||||
}
|
||||
checkReconnect(t, holdResponse, idleTimeout)
|
||||
}
|
||||
@@ -604,16 +604,51 @@ func TestReconnectWhenServerNeverAnswers(t *testing.T) {
|
||||
|
||||
const idleTimeout = 50 * time.Millisecond
|
||||
|
||||
neverAnswer := func(_ http.ResponseWriter, r *http.Request) {
|
||||
<-r.Context().Done()
|
||||
}
|
||||
neverAnswer := roundTripFunc(
|
||||
func(req *http.Request) (*http.Response, error) {
|
||||
<-req.Context().Done()
|
||||
|
||||
return nil, req.Context().Err()
|
||||
},
|
||||
)
|
||||
checkReconnect(t, neverAnswer, idleTimeout)
|
||||
}
|
||||
|
||||
// TestStreamNotDroppedWhileLinesArrive has the server send lines well within
|
||||
// the idle timeout for several times the timeout, then end the response. Each
|
||||
// line must start the idle timeout over, so the stream lasts until the server
|
||||
// ends it instead of being dropped as idle.
|
||||
// pipeTransport answers every request with a response whose body write fills.
|
||||
// The body fails when the request's context ends, as a connection's does.
|
||||
// write gets that context, so that it can end when the request does.
|
||||
type pipeTransport struct {
|
||||
write func(context.Context, io.Writer)
|
||||
}
|
||||
|
||||
func (p pipeTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
body, w := io.Pipe()
|
||||
|
||||
context.AfterFunc(req.Context(), func() {
|
||||
_ = w.CloseWithError(req.Context().Err())
|
||||
})
|
||||
|
||||
go func(ctx context.Context) {
|
||||
p.write(ctx, w)
|
||||
|
||||
_ = w.Close()
|
||||
}(req.Context())
|
||||
|
||||
return &http.Response{StatusCode: http.StatusOK, Body: body}, nil
|
||||
}
|
||||
|
||||
// roundTripFunc makes a function an http.RoundTripper.
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return f(req)
|
||||
}
|
||||
|
||||
// TestStreamNotDroppedWhileLinesArrive has a response send lines well within
|
||||
// the idle timeout for several times the timeout, then end. Each line must
|
||||
// start the idle timeout over, so the stream lasts until the response ends
|
||||
// instead of being dropped as idle. It runs in a synctest bubble, whose clock
|
||||
// is fake, so a stall on the host does not use up the timeout.
|
||||
func TestStreamNotDroppedWhileLinesArrive(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -623,26 +658,35 @@ func TestStreamNotDroppedWhileLinesArrive(t *testing.T) {
|
||||
sendFor = 5 * idleTimeout
|
||||
)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(
|
||||
func(w http.ResponseWriter, _ *http.Request) {
|
||||
// The streamer is made outside the bubble. Its metrics start a goroutine
|
||||
// that never returns, and a bubble waits for each of its goroutines to
|
||||
// return.
|
||||
s := New(logger.New(), metrics.New())
|
||||
s.idleTimeout = idleTimeout
|
||||
s.client = &http.Client{Transport: pipeTransport{
|
||||
write: func(ctx context.Context, w io.Writer) {
|
||||
deadline := time.Now().Add(sendFor)
|
||||
for time.Now().Before(deadline) {
|
||||
_, _ = io.WriteString(w, updateLine)
|
||||
|
||||
flush(w)
|
||||
time.Sleep(lineInterval)
|
||||
// The wait ends with the stream. A bubble's clock stops when
|
||||
// the test function returns, and a goroutine then still
|
||||
// asleep panics the test binary.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(lineInterval):
|
||||
}
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
},
|
||||
}}
|
||||
|
||||
s := New(logger.New(), metrics.New())
|
||||
s.url = srv.URL
|
||||
s.idleTimeout = idleTimeout
|
||||
|
||||
err := s.stream(context.Background())
|
||||
if !errors.Is(err, errStreamEnded) {
|
||||
t.Fatalf("stream returned %v, want %v", err, errStreamEnded)
|
||||
}
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
err := s.stream(context.Background())
|
||||
if !errors.Is(err, errStreamEnded) {
|
||||
t.Fatalf("stream returned %v, want %v", err, errStreamEnded)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestStreamReadsLongLine has the server send one UPDATE line of about
|
||||
@@ -706,7 +750,7 @@ func TestHandlerStatsReadWhileMessagesAreDropped(t *testing.T) {
|
||||
const (
|
||||
lines = 5
|
||||
wantDropped = lines - 2
|
||||
maxWait = 5 * time.Second
|
||||
maxWait = 15 * time.Second
|
||||
)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(
|
||||
@@ -820,61 +864,70 @@ func streamLines(t *testing.T, s *Streamer, lines string) {
|
||||
// line and then stays open. The streamer must come back for a second
|
||||
// response, must not be marked connected when it does, and must handle the
|
||||
// UPDATE in it.
|
||||
//
|
||||
// It runs in a synctest bubble, whose clock is fake, so a stall on the host
|
||||
// does not use up the idle timeout. The fake server gets the requests in the
|
||||
// order the streamer makes them, because no real connection carries them.
|
||||
func checkReconnect(
|
||||
t *testing.T, firstResponse http.HandlerFunc, idleTimeout time.Duration,
|
||||
t *testing.T, firstResponse http.RoundTripper, idleTimeout time.Duration,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
const maxWait = 5 * time.Second
|
||||
const maxWait = 15 * time.Second
|
||||
|
||||
// The tracker is made outside the bubble. It starts a goroutine that never
|
||||
// returns, and a bubble waits for each of its goroutines to return.
|
||||
tracker := metrics.New()
|
||||
connectedAtReconnect := make(chan bool, 1)
|
||||
|
||||
var requests atomic.Int32
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
connectedAtReconnect := make(chan bool, 1)
|
||||
laterResponse := pipeTransport{
|
||||
write: func(ctx context.Context, w io.Writer) {
|
||||
_, _ = io.WriteString(w, updateLine)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(
|
||||
func(w http.ResponseWriter, r *http.Request) {
|
||||
if requests.Add(1) == 1 {
|
||||
firstResponse(w, r)
|
||||
<-ctx.Done()
|
||||
},
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
var requests atomic.Int32
|
||||
|
||||
select {
|
||||
case connectedAtReconnect <- tracker.IsConnected():
|
||||
default:
|
||||
}
|
||||
s := New(logger.New(), tracker)
|
||||
s.client = &http.Client{Transport: roundTripFunc(
|
||||
func(req *http.Request) (*http.Response, error) {
|
||||
if requests.Add(1) == 1 {
|
||||
return firstResponse.RoundTrip(req)
|
||||
}
|
||||
|
||||
_, _ = io.WriteString(w, updateLine)
|
||||
select {
|
||||
case connectedAtReconnect <- tracker.IsConnected():
|
||||
default:
|
||||
}
|
||||
|
||||
flush(w)
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
defer srv.Close()
|
||||
return laterResponse.RoundTrip(req)
|
||||
},
|
||||
)}
|
||||
s.idleTimeout = idleTimeout
|
||||
s.minBackoff = time.Millisecond
|
||||
handler := updateHandler{handled: make(chan struct{}, 1)}
|
||||
s.RegisterHandler(handler)
|
||||
|
||||
s := New(logger.New(), tracker)
|
||||
s.url = srv.URL
|
||||
s.idleTimeout = idleTimeout
|
||||
s.minBackoff = time.Millisecond
|
||||
handler := updateHandler{handled: make(chan struct{}, 1)}
|
||||
s.RegisterHandler(handler)
|
||||
err := s.Start(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("Start returned error: %v", err)
|
||||
}
|
||||
defer s.Stop(t.Context())
|
||||
|
||||
err := s.Start(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("Start returned error: %v", err)
|
||||
}
|
||||
defer s.Stop(t.Context())
|
||||
select {
|
||||
case <-handler.handled:
|
||||
case <-time.After(maxWait):
|
||||
t.Fatalf("no message from a second response handled within %s", maxWait)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-handler.handled:
|
||||
case <-time.After(maxWait):
|
||||
t.Fatalf("no message from a second response handled within %s", maxWait)
|
||||
}
|
||||
|
||||
if <-connectedAtReconnect {
|
||||
t.Error("streamer was still marked connected when it came back " +
|
||||
"for a second response")
|
||||
}
|
||||
if <-connectedAtReconnect {
|
||||
t.Error("streamer was still marked connected when it came back " +
|
||||
"for a second response")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// settledGoroutineCount lets transient goroutines finish, then reports the
|
||||
@@ -896,9 +949,13 @@ func settledGoroutineCount() int {
|
||||
return prev
|
||||
}
|
||||
|
||||
// waitForGoroutines waits until the goroutine count drops to target or below.
|
||||
// waitForGoroutines waits up to 15 seconds for the goroutine count to drop to
|
||||
// target or below.
|
||||
func waitForGoroutines(target int) bool {
|
||||
for range 100 {
|
||||
const maxWait = 15 * time.Second
|
||||
|
||||
deadline := time.Now().Add(maxWait)
|
||||
for time.Now().Before(deadline) {
|
||||
if runtime.NumGoroutine() <= target {
|
||||
return true
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user