Import Anubis v1.28.2

Replace the tree with upstream TecharoHQ/anubis v1.28.2 (a1384fbf42e3).
Masyunis customizations are re-applied in the following commits.
This commit is contained in:
sol_bot Bot committed 2026-11-28 14:52:26 +03:00
1 parent eb3e46d8d0
commit e07de898cd
573 files changed
+35846 -6807

No files matched your search

+437
View File
@@ -0,0 +1,437 @@
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net/http"
"net/netip"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/facebookgo/flagenv"
"gopkg.in/yaml.v3"
)
var (
dataDir = flag.String("data-dir", "data/crawlers", "folder holding the crawler policy files")
dryRun = flag.Bool("dry-run", false, "report what would change but don't write any files")
list = flag.Bool("list", false, "list every crawler this tool can update, then exit")
slogLevel = flag.String("slog-level", "INFO", "logging level (DEBUG, INFO, WARN, ERROR)")
timeout = flag.Duration("timeout", 30*time.Second, "how long to wait for a single feed")
userAgent = flag.String("user-agent", "Anubis-botgenerate (+https://github.com/TecharoHQ/anubis)", "User-Agent to send when fetching feeds")
)
var (
ErrNoSuchCrawler = errors.New("botgenerate: no crawler by that name")
ErrRuleNotFound = errors.New("botgenerate: policy file has no rule by that name")
ErrNoRemoteAddresses = errors.New("botgenerate: rule has no remote_addresses field")
ErrNoPrefixes = errors.New("botgenerate: feed returned no usable prefixes")
ErrUnexpectedStatus = errors.New("botgenerate: feed returned an unexpected HTTP status")
)
// Source says where one crawler's IP range list comes from.
type Source struct {
// File is the policy file to update, relative to --data-dir. Its name
// without the extension is how the crawler is named on the command line.
File string
// Rule is the name of the rule inside File whose remote_addresses list gets
// replaced. A policy file may hold more than one rule.
Rule string
// URL is the operator's published feed.
URL string
}
// Name is how this crawler is spelled on the command line.
func (s Source) Name() string {
return strings.TrimSuffix(s.File, filepath.Ext(s.File))
}
func (s Source) LogValue() slog.Value {
return slog.GroupValue(
slog.String("file", s.File),
slog.String("rule", s.Rule),
slog.String("url", s.URL),
)
}
var sources = []Source{
{
File: "applebot.yaml",
Rule: "applebot",
URL: "https://search.developer.apple.com/applebot.json",
},
{
File: "bingbot.yaml",
Rule: "bingbot",
URL: "https://www.bing.com/toolbox/bingbot.json",
},
{
File: "commoncrawl.yaml",
Rule: "common-crawl",
URL: "https://index.commoncrawl.org/ccbot.json",
},
{
File: "duckduckbot.yaml",
Rule: "duckduckbot",
URL: "https://duckduckgo.com/duckduckbot.json",
},
{
// The list of Google crawlers that respect robots.txt
// https://developers.google.com/crawling/docs/crawlers-fetchers/verify-google-requests
File: "googlebot.yaml",
Rule: "googlebot",
URL: "https://developers.google.com/static/crawling/ipranges/common-crawlers.json",
},
{
File: "mojeekbot.yaml",
Rule: "mojeekbot",
URL: "https://www.mojeek.com/mojeekbot.json",
},
{
File: "openai-gptbot.yaml",
Rule: "openai-gptbot",
URL: "https://openai.com/gptbot.json",
},
{
File: "openai-searchbot.yaml",
Rule: "openai-searchbot",
URL: "https://openai.com/searchbot.json",
},
{
File: "perplexitybot.yaml",
Rule: "perplexitybot",
URL: "https://www.perplexity.com/perplexitybot.json",
},
{
File: "qwantbot.yaml",
Rule: "qwantbot",
URL: "https://help.qwant.com/wp-content/uploads/sites/latest/qwantbot.json",
},
}
func init() {
flag.Usage = func() {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), `Usage of %[1]s:
%[1]s [flags] [crawler...]
Updates the remote_addresses list of each crawler from the IP range lists
their operators publish. If no crawler is passed, it updates everything.
After running this, run npm run format
Flags:
`, filepath.Base(os.Args[0]))
flag.PrintDefaults()
}
}
func main() {
flagenv.Parse()
flag.Parse()
var lvl slog.Level
if err := lvl.UnmarshalText([]byte(*slogLevel)); err != nil {
fmt.Fprintf(os.Stderr, "--slog-level=%q is invalid: %v\n", *slogLevel, err)
os.Exit(2)
}
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: lvl})))
if *list {
for _, src := range sources {
fmt.Printf("%-20s %s\n", src.Name(), src.URL)
}
return
}
want, err := selectSources(flag.Args())
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n\nRun %s --list to see every known crawler.\n", err, filepath.Base(os.Args[0]))
os.Exit(2)
}
u := &updater{
cli: &http.Client{Timeout: *timeout},
dataDir: *dataDir,
dryRun: *dryRun,
userAgent: *userAgent,
}
var errs []error
for _, src := range want {
if err := u.update(src); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", src.Name(), err))
}
}
if len(errs) != 0 {
slog.Error("could not update every crawler", "err", errors.Join(errs...))
os.Exit(1)
}
}
func selectSources(names []string) ([]Source, error) {
if len(names) == 0 {
return sources, nil
}
var (
want []Source
errs []error
)
for _, name := range names {
idx := slices.IndexFunc(sources, func(s Source) bool { return s.Name() == name })
if idx == -1 {
errs = append(errs, fmt.Errorf("%w: %q", ErrNoSuchCrawler, name))
continue
}
want = append(want, sources[idx])
}
if len(errs) != 0 {
return nil, errors.Join(errs...)
}
return want, nil
}
type updater struct {
cli *http.Client
dataDir string
dryRun bool
userAgent string
}
func (u *updater) update(src Source) error {
lg := slog.With("crawler", src.Name())
prefixes, err := u.fetchPrefixes(src.URL)
if err != nil {
return err
}
fname := filepath.Join(u.dataDir, src.File)
data, err := os.ReadFile(fname)
if err != nil {
return fmt.Errorf("can't read policy file: %w", err)
}
var root yaml.Node
if err := yaml.Unmarshal(data, &root); err != nil {
return fmt.Errorf("can't parse %s: %w", fname, err)
}
old, err := setRemoteAddresses(&root, src.Rule, prefixes)
if err != nil {
return fmt.Errorf("can't update %s: %w", fname, err)
}
added, removed := diff(old, prefixes)
if len(added) == 0 && len(removed) == 0 {
lg.Info("already up to date", "prefixes", len(prefixes))
return nil
}
lg.Info("IP ranges changed", "added", len(added), "removed", len(removed), "total", len(prefixes))
lg.Debug("IP ranges changed", "added", added, "removed", removed)
if u.dryRun {
return nil
}
out, err := marshal(&root)
if err != nil {
return fmt.Errorf("can't serialize %s: %w", fname, err)
}
if err := os.WriteFile(fname, out, 0o644); err != nil {
return fmt.Errorf("can't write %s: %w", fname, err)
}
lg.Info("wrote policy file", "file", fname)
return nil
}
// prefixList is the common subset of JSON fields in search engine IP prefix feeds
type prefixList struct {
Prefixes []struct {
IPv4Prefix string `json:"ipv4Prefix"`
IPv6Prefix string `json:"ipv6Prefix"`
} `json:"prefixes"`
}
func (u *updater) fetchPrefixes(url string) ([]string, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("can't build request for %s: %w", url, err)
}
req.Header.Set("User-Agent", u.userAgent)
req.Header.Set("Accept", "application/json")
resp, err := u.cli.Do(req)
if err != nil {
return nil, fmt.Errorf("can't fetch %s: %w", url, err)
}
defer resp.Body.Close() //nolint:errcheck
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%w: %s returned %s", ErrUnexpectedStatus, url, resp.Status)
}
prefixes, err := parsePrefixes(resp.Body)
if err != nil {
return nil, fmt.Errorf("can't read %s: %w", url, err)
}
return prefixes, nil
}
func parsePrefixes(r io.Reader) ([]string, error) {
var pl prefixList
if err := json.NewDecoder(r).Decode(&pl); err != nil {
return nil, fmt.Errorf("can't decode prefix list: %w", err)
}
var prefixes []string
for i, p := range pl.Prefixes {
var raw string
switch {
case p.IPv4Prefix != "":
raw = p.IPv4Prefix
case p.IPv6Prefix != "":
raw = p.IPv6Prefix
default:
return nil, fmt.Errorf("prefix %d has neither ipv4Prefix nor ipv6Prefix", i)
}
pfx, err := netip.ParsePrefix(raw)
if err != nil {
return nil, fmt.Errorf("prefix %d (%q) is not a CIDR range: %w", i, raw, err)
}
prefixes = append(prefixes, pfx.String())
}
if len(prefixes) == 0 {
return nil, ErrNoPrefixes
}
return prefixes, nil
}
func setRemoteAddresses(root *yaml.Node, rule string, prefixes []string) ([]string, error) {
if len(root.Content) == 0 {
return nil, fmt.Errorf("%w: %s (file is empty)", ErrRuleNotFound, rule)
}
for _, node := range root.Content[0].Content {
name := mappingValue(node, "name")
if name == nil || name.Value != rule {
continue
}
addrs := mappingValue(node, "remote_addresses")
if addrs == nil {
return nil, fmt.Errorf("%w: %s", ErrNoRemoteAddresses, rule)
}
old := make([]string, 0, len(addrs.Content))
for _, item := range addrs.Content {
old = append(old, item.Value)
}
var style yaml.Style
if addrs.Style&yaml.FlowStyle != 0 {
style = yaml.DoubleQuotedStyle
}
content := make([]*yaml.Node, 0, len(prefixes))
for _, prefix := range prefixes {
content = append(content, &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: prefix,
Style: style,
})
}
addrs.Kind = yaml.SequenceNode
addrs.Tag = "!!seq"
addrs.Content = content
return old, nil
}
return nil, fmt.Errorf("%w: %s", ErrRuleNotFound, rule)
}
func mappingValue(node *yaml.Node, key string) *yaml.Node {
if node.Kind != yaml.MappingNode {
return nil
}
for i := 0; i+1 < len(node.Content); i += 2 {
if node.Content[i].Value == key {
return node.Content[i+1]
}
}
return nil
}
func marshal(root *yaml.Node) ([]byte, error) {
var buf strings.Builder
enc := yaml.NewEncoder(&buf)
enc.SetIndent(2)
if err := enc.Encode(root); err != nil {
return nil, err
}
if err := enc.Close(); err != nil {
return nil, err
}
return []byte(buf.String()), nil
}
func diff(before, after []string) (added, removed []string) {
inBefore := make(map[string]struct{}, len(before))
for _, prefix := range before {
inBefore[prefix] = struct{}{}
}
inAfter := make(map[string]struct{}, len(after))
for _, prefix := range after {
inAfter[prefix] = struct{}{}
}
for _, prefix := range after {
if _, ok := inBefore[prefix]; !ok {
added = append(added, prefix)
}
}
for _, prefix := range before {
if _, ok := inAfter[prefix]; !ok {
removed = append(removed, prefix)
}
}
return added, removed
}
+586
View File
@@ -0,0 +1,586 @@
package main
import (
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
func TestParsePrefixes(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
input string
want []string
err error
}{
{
name: "ipv4 and ipv6",
input: `{"prefixes":[{"ipv4Prefix":"192.0.2.0/24"},{"ipv6Prefix":"2001:db8::/32"}]}`,
want: []string{"192.0.2.0/24", "2001:db8::/32"},
},
{
name: "ignores unrelated fields",
input: `{"creationTime":"2026-08-31T14:46:46.000000","notes":"hi","prefixes":[{"ipv4Prefix":"192.0.2.0/24"}]}`,
want: []string{"192.0.2.0/24"},
},
{
name: "no prefixes",
input: `{"prefixes":[]}`,
err: ErrNoPrefixes,
},
{
name: "empty prefix entry",
input: `{"prefixes":[{"ipv4Prefix":"192.0.2.0/24"},{}]}`,
},
{
name: "bare address is not a prefix",
input: `{"prefixes":[{"ipv4Prefix":"192.0.2.1"}]}`,
},
{
name: "garbage prefix",
input: `{"prefixes":[{"ipv4Prefix":"not-an-ip/24"}]}`,
},
{
name: "not json",
input: `<html>go away</html>`,
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got, err := parsePrefixes(strings.NewReader(tt.input))
if tt.want == nil {
if err == nil {
t.Logf("got: %v", got)
t.Fatal("wanted an error but parsing succeeded")
}
if tt.err != nil && !errors.Is(err, tt.err) {
t.Logf("want: %v", tt.err)
t.Logf("got: %v", err)
t.Error("got wrong error")
}
return
}
if err != nil {
t.Fatalf("can't parse prefix list: %v", err)
}
if !slices.Equal(got, tt.want) {
t.Logf("want: %v", tt.want)
t.Logf("got: %v", got)
t.Error("got wrong prefixes")
}
})
}
}
func TestSetRemoteAddresses(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
input string
rule string
want []string
wantOld []string
err error
}{
{
name: "block style rule",
input: `- name: googlebot
user_agent_regex: \+http\://www\.google\.com/bot\.html
action: ALLOW
remote_addresses:
- 192.0.2.0/24
`,
rule: "googlebot",
want: []string{"198.51.100.0/24"},
wantOld: []string{"192.0.2.0/24"},
},
{
name: "picks the right rule in a multi rule file",
input: `- name: first
action: ALLOW
remote_addresses: ["192.0.2.0/24"]
- name: second
action: ALLOW
remote_addresses: ["203.0.113.0/24"]
`,
rule: "second",
want: []string{"198.51.100.0/24"},
wantOld: []string{"203.0.113.0/24"},
},
{
name: "rule is missing",
input: `- name: googlebot
action: ALLOW
remote_addresses: ["192.0.2.0/24"]
`,
rule: "bingbot",
err: ErrRuleNotFound,
},
{
name: "rule has no remote_addresses",
input: `- name: yandexbot
action: ALLOW
`,
rule: "yandexbot",
err: ErrNoRemoteAddresses,
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var root yaml.Node
if err := yaml.Unmarshal([]byte(tt.input), &root); err != nil {
t.Fatalf("can't parse test fixture: %v", err)
}
old, err := setRemoteAddresses(&root, tt.rule, tt.want)
if tt.err != nil {
if !errors.Is(err, tt.err) {
t.Logf("want: %v", tt.err)
t.Logf("got: %v", err)
t.Error("got wrong error")
}
return
}
if err != nil {
t.Fatalf("can't set remote addresses: %v", err)
}
if !slices.Equal(old, tt.wantOld) {
t.Logf("want: %v", tt.wantOld)
t.Logf("got: %v", old)
t.Error("got wrong previous addresses")
}
data, err := marshal(&root)
if err != nil {
t.Fatalf("can't serialize result: %v", err)
}
var rules []struct {
Name string `yaml:"name"`
RemoteAddr []string `yaml:"remote_addresses"`
}
if err := yaml.Unmarshal(data, &rules); err != nil {
t.Fatalf("can't reparse result: %v", err)
}
idx := slices.IndexFunc(rules, func(r struct {
Name string `yaml:"name"`
RemoteAddr []string `yaml:"remote_addresses"`
}) bool {
return r.Name == tt.rule
})
if idx == -1 {
t.Fatalf("rule %s vanished from the result:\n%s", tt.rule, data)
}
if !slices.Equal(rules[idx].RemoteAddr, tt.want) {
t.Logf("want: %v", tt.want)
t.Logf("got: %v", rules[idx].RemoteAddr)
t.Error("got wrong addresses in output")
}
})
}
}
func TestSetRemoteAddressesKeepsComments(t *testing.T) {
t.Parallel()
const input = `# Indexing for search and Siri
# https://support.apple.com/en-us/119829
- name: applebot
user_agent_regex: Applebot
action: ALLOW
# https://search.developer.apple.com/applebot.json
remote_addresses: ["17.241.208.160/27"]
# trailing note
`
var root yaml.Node
if err := yaml.Unmarshal([]byte(input), &root); err != nil {
t.Fatalf("can't parse test fixture: %v", err)
}
if _, err := setRemoteAddresses(&root, "applebot", []string{"192.0.2.0/24"}); err != nil {
t.Fatalf("can't set remote addresses: %v", err)
}
data, err := marshal(&root)
if err != nil {
t.Fatalf("can't serialize result: %v", err)
}
for _, want := range []string{
"# Indexing for search and Siri",
"# https://support.apple.com/en-us/119829",
"# https://search.developer.apple.com/applebot.json",
"# trailing note",
"user_agent_regex: Applebot",
} {
if !strings.Contains(string(data), want) {
t.Logf("want to find: %q", want)
t.Logf("got:\n%s", data)
t.Error("output lost part of the original file")
}
}
}
func TestSetRemoteAddressesKeepsStyle(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
input string
want string
}{
{
name: "flow style quotes every prefix",
input: "- name: applebot\n remote_addresses: [\"192.0.2.0/24\"]\n",
want: `remote_addresses: ["198.51.100.0/24", "2001:db8::/32"]`,
},
{
name: "block style leaves prefixes bare",
input: "- name: applebot\n remote_addresses:\n - 192.0.2.0/24\n",
want: "remote_addresses:\n - 198.51.100.0/24\n - 2001:db8::/32",
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var root yaml.Node
if err := yaml.Unmarshal([]byte(tt.input), &root); err != nil {
t.Fatalf("can't parse test fixture: %v", err)
}
if _, err := setRemoteAddresses(&root, "applebot", []string{"198.51.100.0/24", "2001:db8::/32"}); err != nil {
t.Fatalf("can't set remote addresses: %v", err)
}
data, err := marshal(&root)
if err != nil {
t.Fatalf("can't serialize result: %v", err)
}
if !strings.Contains(string(data), tt.want) {
t.Logf("want to find:\n%s", tt.want)
t.Logf("got:\n%s", data)
t.Error("wrote the prefixes in the wrong style")
}
})
}
}
func TestSelectSources(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
input []string
want []string
err error
}{
{
name: "no arguments selects everything",
input: nil,
want: allSourceNames(),
},
{
name: "by name",
input: []string{"googlebot", "bingbot"},
want: []string{"googlebot", "bingbot"},
},
{
name: "unknown crawler",
input: []string{"googlebot", "clippy"},
err: ErrNoSuchCrawler,
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got, err := selectSources(tt.input)
if tt.err != nil {
if !errors.Is(err, tt.err) {
t.Logf("want: %v", tt.err)
t.Logf("got: %v", err)
t.Error("got wrong error")
}
return
}
if err != nil {
t.Fatalf("can't select sources: %v", err)
}
var names []string
for _, src := range got {
names = append(names, src.Name())
}
if !slices.Equal(names, tt.want) {
t.Logf("want: %v", tt.want)
t.Logf("got: %v", names)
t.Error("selected the wrong crawlers")
}
})
}
}
func TestSourcesMatchDataFiles(t *testing.T) {
t.Parallel()
const dir = "../../../data/crawlers"
for _, src := range sources {
t.Run(src.Name(), func(t *testing.T) {
t.Parallel()
data, err := os.ReadFile(filepath.Join(dir, src.File))
if err != nil {
t.Fatalf("can't read policy file: %v", err)
}
var rules []struct {
Name string `yaml:"name"`
RemoteAddr []string `yaml:"remote_addresses"`
}
if err := yaml.Unmarshal(data, &rules); err != nil {
t.Fatalf("can't parse policy file: %v", err)
}
for _, rule := range rules {
if rule.Name != src.Rule {
continue
}
if len(rule.RemoteAddr) == 0 {
t.Errorf("rule %s has no remote_addresses to update", src.Rule)
}
return
}
t.Errorf("%s declares no rule named %q", src.File, src.Rule)
})
}
}
func TestUpdate(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("User-Agent"); got != "test-agent" {
t.Errorf("wanted User-Agent test-agent, got: %s", got)
}
w.Header().Set("Content-Type", "application/json")
writePrefixes(t, w)
}))
t.Cleanup(srv.Close)
dir := t.TempDir()
fname := filepath.Join(dir, "googlebot.yaml")
const input = `- name: googlebot
action: ALLOW
# source of truth
remote_addresses:
- 192.0.2.0/24
`
if err := os.WriteFile(fname, []byte(input), 0o644); err != nil {
t.Fatalf("can't write test fixture: %v", err)
}
src := Source{File: "googlebot.yaml", Rule: "googlebot", URL: srv.URL}
t.Run("dry run leaves the file alone", func(t *testing.T) {
u := &updater{cli: srv.Client(), dataDir: dir, dryRun: true, userAgent: "test-agent"}
if err := u.update(src); err != nil {
t.Fatalf("can't update: %v", err)
}
got, err := os.ReadFile(fname)
if err != nil {
t.Fatalf("can't read file back: %v", err)
}
if string(got) != input {
t.Logf("want:\n%s", input)
t.Logf("got:\n%s", got)
t.Error("dry run wrote to the file")
}
})
t.Run("writes the new prefixes", func(t *testing.T) {
u := &updater{cli: srv.Client(), dataDir: dir, userAgent: "test-agent"}
if err := u.update(src); err != nil {
t.Fatalf("can't update: %v", err)
}
got, err := os.ReadFile(fname)
if err != nil {
t.Fatalf("can't read file back: %v", err)
}
for _, want := range []string{"198.51.100.0/24", "2001:db8::/32", "# source of truth"} {
if !strings.Contains(string(got), want) {
t.Logf("want to find: %q", want)
t.Logf("got:\n%s", got)
t.Error("output is missing something")
}
}
if strings.Contains(string(got), "192.0.2.0/24") {
t.Logf("got:\n%s", got)
t.Error("stale prefix survived the update")
}
})
}
func TestUpdateRejectsBadFeed(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
status int
body string
wantErr error
}{
{name: "server error", status: http.StatusInternalServerError, body: "nope", wantErr: ErrUnexpectedStatus},
{name: "empty feed", status: http.StatusOK, body: `{"prefixes":[]}`, wantErr: ErrNoPrefixes},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.status)
if _, err := w.Write([]byte(tt.body)); err != nil {
t.Errorf("can't write response: %v", err)
}
}))
t.Cleanup(srv.Close)
dir := t.TempDir()
fname := filepath.Join(dir, "googlebot.yaml")
const input = "- name: googlebot\n action: ALLOW\n remote_addresses:\n - 192.0.2.0/24\n"
if err := os.WriteFile(fname, []byte(input), 0o644); err != nil {
t.Fatalf("can't write test fixture: %v", err)
}
u := &updater{cli: srv.Client(), dataDir: dir, userAgent: "test-agent"}
err := u.update(Source{File: "googlebot.yaml", Rule: "googlebot", URL: srv.URL})
if !errors.Is(err, tt.wantErr) {
t.Logf("want: %v", tt.wantErr)
t.Logf("got: %v", err)
t.Error("got wrong error")
}
got, err := os.ReadFile(fname)
if err != nil {
t.Fatalf("can't read file back: %v", err)
}
if string(got) != input {
t.Logf("got:\n%s", got)
t.Error("a failed fetch must not touch the policy file")
}
})
}
}
func TestDiff(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
old, cur []string
wantAdded []string
wantRemoved []string
}{
{
name: "no change",
old: []string{"192.0.2.0/24"},
cur: []string{"192.0.2.0/24"},
},
{
name: "reordering is not a change",
old: []string{"192.0.2.0/24", "198.51.100.0/24"},
cur: []string{"198.51.100.0/24", "192.0.2.0/24"},
wantAdded: nil,
},
{
name: "added and removed",
old: []string{"192.0.2.0/24", "203.0.113.0/24"},
cur: []string{"192.0.2.0/24", "198.51.100.0/24"},
wantAdded: []string{"198.51.100.0/24"},
wantRemoved: []string{"203.0.113.0/24"},
},
{
name: "first run",
cur: []string{"192.0.2.0/24"},
wantAdded: []string{"192.0.2.0/24"},
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
added, removed := diff(tt.old, tt.cur)
if !slices.Equal(added, tt.wantAdded) {
t.Logf("want: %v", tt.wantAdded)
t.Logf("got: %v", added)
t.Error("got wrong added prefixes")
}
if !slices.Equal(removed, tt.wantRemoved) {
t.Logf("want: %v", tt.wantRemoved)
t.Logf("got: %v", removed)
t.Error("got wrong removed prefixes")
}
})
}
}
func allSourceNames() []string {
var names []string
for _, src := range sources {
names = append(names, src.Name())
}
return names
}
func writePrefixes(t *testing.T, w http.ResponseWriter) {
t.Helper()
const body = `{"prefixes":[{"ipv4Prefix":"198.51.100.0/24"},{"ipv6Prefix":"2001:db8::/32"}]}`
if _, err := w.Write([]byte(body)); err != nil {
t.Errorf("can't write response: %v", err)
}
}
+49 -16
View File
@@ -7,26 +7,19 @@ import (
"net/http"
"net/netip"
"strings"
"github.com/TecharoHQ/anubis/internal/iplist"
)
// FetchBlocklist reads the blocklist over HTTP and returns every non-commented
// ParseBlocklist reads a plain-text blocklist and returns every non-commented
// line parsed as an IP address in CIDR notation. IPv4 addresses are returned as
// /32, IPv6 addresses as /128.
//
// This function was generated with GLM 4.7.
func FetchBlocklist(url string) ([]string, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
func ParseBlocklist(list io.Reader) ([]string, error) {
var addrs []string
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP request failed with status: %s", resp.Status)
}
var lines []string
scanner := bufio.NewScanner(resp.Body)
scanner := bufio.NewScanner(list)
for scanner.Scan() {
line := scanner.Text()
// Skip empty lines and comments (lines starting with #)
@@ -46,12 +39,52 @@ func FetchBlocklist(url string) ([]string, error) {
} else {
cidr = fmt.Sprintf("%s/128", addr.String())
}
lines = append(lines, cidr)
addrs = append(addrs, cidr)
}
if err := scanner.Err(); err != nil && err != io.EOF {
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
return addrs, nil
}
// FetchBlocklist fetches url over HTTP and parses the response body as a
// blocklist. JSON responses (detected via the Content-Type header or a
// ".json" URL suffix) are parsed with ParsePrefixList; everything else is
// treated as a plain-text list and parsed with ParseBlocklist.
func FetchBlocklist(url string) ([]string, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close() //nolint:errcheck
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP request failed with status: %s", resp.Status)
}
if isJSONBlocklist(url, resp.Header.Get("Content-Type")) {
return ParsePrefixList(resp.Body)
}
return ParseBlocklist(resp.Body)
}
func isJSONBlocklist(url, contentType string) bool {
if contentType == "json" {
return true
}
return strings.HasSuffix(strings.ToLower(url), ".json")
}
// ParsePrefixList decodes a JSON document read from list in the Google/OpenAI
// bot IP range format and returns every IPv4 and IPv6 prefix it contains.
func ParsePrefixList(list io.Reader) ([]string, error) {
pl, err := iplist.Parse(list)
if err != nil {
return nil, err
}
return pl.CIDRs(), nil
}
+11 -4
View File
@@ -90,14 +90,21 @@ func main() {
if err != nil {
log.Fatalf("can't create output file %q: %v", foutName, err)
}
defer fout.Close()
fmt.Fprintf(fout, "# Generated by %s on %s from %s\n\n", filepath.Base(os.Args[0]), time.Now().Format(time.RFC3339), blocklistURL)
if _, err := fmt.Fprintf(fout, "# Generated by %s on %s from %s\n\n", filepath.Base(os.Args[0]), time.Now().Format(time.RFC3339), blocklistURL); err != nil {
log.Fatalf("can't write signature line: %v", err)
}
data, err := yaml.Marshal([]*Rule{result})
if err != nil {
log.Fatalf("can't marshal yaml")
log.Fatalf("can't marshal yaml: %v", err)
}
fout.Write(data)
if _, err := fout.Write(data); err != nil {
log.Fatalf("can't write data: %v", err)
}
if err := fout.Close(); err != nil {
log.Fatalf("can't close file: %v", err)
}
}
+108
View File
@@ -0,0 +1,108 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
"github.com/tetratelabs/wazero/experimental"
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
"github.com/tetratelabs/wazero/sys"
)
func defaultCacheDir() string {
dir, err := os.UserCacheDir()
if err != nil {
path := filepath.Join(os.Getenv("HOME"), ".cache", "techaro.lol", "anubis", "wazero-exec")
_ = os.MkdirAll(path, 0755)
return path
}
path := filepath.Join(dir, "techaro.lol", "anubis", "wazero-exec")
_ = os.MkdirAll(path, 0755)
return path
}
var (
cacheDir = flag.String("cache-dir", defaultCacheDir(), "default compilation cache folder")
)
func main() {
flag.Parse()
if flag.NArg() == 0 {
fmt.Fprintf(os.Stderr, "usage: %s <file.wasm> [args]\n\n", filepath.Base(os.Args[0]))
flag.Usage()
os.Exit(2)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := run(ctx, flag.Arg(0), flag.Args()); err != nil {
fmt.Fprintf(os.Stderr, "can't run program %s: %v\n", flag.Arg(0), err)
var exitErr *sys.ExitError
if errors.As(err, &exitErr) && exitErr.ExitCode() != 0 {
os.Exit(int(exitErr.ExitCode()))
}
os.Exit(1)
}
}
func run(ctx context.Context, fname string, args []string) error {
cache, err := wazero.NewCompilationCacheWithDir(*cacheDir)
if err != nil {
return fmt.Errorf("can't open cache folder %q: %w", *cacheDir, err)
}
cfg := wazero.NewRuntimeConfig().
WithCompilationCache(cache).
WithCoreFeatures(api.CoreFeaturesV2 | experimental.CoreFeaturesExceptionHandling | experimental.CoreFeaturesExtendedConst | experimental.CoreFeaturesTailCall)
runtime := wazero.NewRuntimeWithConfig(ctx, cfg)
wasi_snapshot_preview1.MustInstantiate(ctx, runtime)
bin, err := os.ReadFile(fname)
if err != nil {
return fmt.Errorf("can't read file %s: %w", fname, err)
}
compiled, err := runtime.CompileModule(ctx, bin)
if err != nil {
return fmt.Errorf("can't compile binary %s: %w", fname, err)
}
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("[unexpected] can't get cwd: %w", err)
}
fsConfig := wazero.NewFSConfig().WithDirMount(cwd, "/")
config := wazero.NewModuleConfig().
WithStdin(os.Stdin).WithStdout(os.Stdout).WithStderr(os.Stderr).
WithArgs(args...).WithName(filepath.Base(fname)).WithFSConfig(fsConfig).
WithSysNanosleep().WithSysNanotime().WithSysWalltime()
for _, kp := range os.Environ() {
kv := strings.SplitN(kp, "=", 2)
config = config.WithEnv(kv[0], kv[1])
}
mod, err := runtime.InstantiateModule(ctx, compiled, config)
if err != nil {
return fmt.Errorf("can't instantiate module: %w", err)
}
if err := mod.Close(ctx); err != nil {
return err
}
return nil
}