package mtproto import ( "fmt" "io" "net/http" "net/http/httptest" "reflect" "testing" "time" ) // The IP limit keeps a client's newest addresses and bans the oldest, so an address // must keep the time it connected for as long as mtg reports it. func TestActiveIPsSince(t *testing.T) { prev := map[string]map[string]int64{ "alice": {"203.0.113.7": 100, "203.0.113.8": 110}, } users := map[string]statsUser{ "alice": {ActiveIPs: []string{"203.0.113.7", "198.51.100.4", "127.0.0.1", "::1"}}, "bob": {ActiveIPs: []string{"2001:db8::1"}}, "carol": {}, } got := activeIPsSince(prev, users, 200) want := map[string]map[string]int64{ "alice": {"203.0.113.7": 100, "198.51.100.4": 200}, "bob": {"2001:db8::1": 200}, } if !reflect.DeepEqual(got, want) { t.Fatalf("activeIPsSince = %v, want %v", got, want) } } // MTProto clients never reach Xray, so its online list cannot see them: without // mtg's own addresses their IP log stays empty and their IP limit never fires. func TestClientIPsFollowTheLastScrape(t *testing.T) { pidFile := installFakeMtg(t) mgr := &Manager{procs: map[int]*managed{}, swept: true} if err := mgr.Ensure(mtgInst(1, SecretEntry{Name: "alice", Secret: "ee01"})); err != nil { t.Fatalf("ensure: %v", err) } waitSpawnCount(t, pidFile, 1) t.Cleanup(mgr.StopAll) if got := mgr.ClientIPs(); len(got) != 0 { t.Fatalf("no address is known before the first scrape, got %v", got) } srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, `{"users":{"alice":{"connections":2,"bytes_in":1,"bytes_out":2,"active_ips":["203.0.113.7"]}}}`) })) mgr.procs[1].apiPort = serverPort(t, srv) before := time.Now().Unix() mgr.CollectTraffic() after := time.Now().Unix() got := mgr.ClientIPs() seen, ok := got["alice"]["203.0.113.7"] if len(got) != 1 || len(got["alice"]) != 1 || !ok || seen < before || seen > after { t.Fatalf("ClientIPs = %v, want alice at 203.0.113.7 seen in [%d, %d]", got, before, after) } // A scrape that fails says nothing about who is connected: the addresses of the // previous one must not stay "live", or a client that left keeps counting. srv.Close() _, _, _, observed := mgr.CollectTraffic() if len(observed) != 0 { t.Fatalf("a failed scrape must leave the inbound unobserved, got %v", observed) } if got := mgr.ClientIPs(); len(got) != 0 { t.Fatalf("a failed scrape must drop the known addresses, got %v", fmt.Sprint(got)) } }