destBytes_test.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. /*
  2. * Copyright (c) 2026, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "encoding/json"
  22. "io"
  23. "sync"
  24. "testing"
  25. "time"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  29. )
  30. func TestDestBytes(t *testing.T) {
  31. err := runTestDestBytes()
  32. if err != nil {
  33. t.Error(errors.Trace(err).Error())
  34. }
  35. }
  36. func runTestDestBytes() error {
  37. var logsMutex sync.Mutex
  38. var asnDestBytesLogs []map[string]interface{}
  39. var domainDestBytesLogs []map[string]interface{}
  40. // Discard logs, skipping InitLogging. Force disable useProtobufLogging,
  41. // which would otherwise require the udsipc.Reader/handler scheme in
  42. // server_test. Both asn_dest_bytes and domain_dest_bytes contents are
  43. // checked in server_test in PSIPHON_RUN_PROTOBUF_LOGGING_TEST mode.
  44. logWriter := log.Logger.Out
  45. protobufLogging := useProtobufLogging
  46. defer func() {
  47. log.Logger.Out = logWriter
  48. useProtobufLogging = protobufLogging
  49. }()
  50. log.Logger.Out = io.Discard
  51. logCallback := func(log []byte) {
  52. logFields := make(map[string]interface{})
  53. err := json.Unmarshal(log, &logFields)
  54. if err != nil {
  55. panic(err.Error())
  56. }
  57. logsMutex.Lock()
  58. defer logsMutex.Unlock()
  59. switch logFields["event_name"].(string) {
  60. case "asn_dest_bytes":
  61. asnDestBytesLogs = append(asnDestBytesLogs, logFields)
  62. case "domain_dest_bytes":
  63. domainDestBytesLogs = append(domainDestBytesLogs, logFields)
  64. }
  65. }
  66. setLogCallback(logCallback)
  67. defer setLogCallback(nil)
  68. // Test can fail if the following addBytes/Sleep loop isn't synchronzied
  69. // with the destBytesLogger timer.
  70. //
  71. // TODO: use time/synctest in Go 1.25+
  72. const logPeriod = 500 * time.Millisecond
  73. destBytesLogger := newDestBytesLogger(&SupportServices{
  74. Config: &Config{
  75. destinationBytesPeriod: logPeriod,
  76. },
  77. })
  78. err := destBytesLogger.Start()
  79. if err != nil {
  80. return errors.Trace(err)
  81. }
  82. defer destBytesLogger.Stop()
  83. destASNs := []string{"00001", "00002"}
  84. destDomains := []string{"example.com", "example.org"}
  85. clientRegions := []string{"R1", "R2"}
  86. clientASNs := []string{"00003", "00004"}
  87. clientPlatformPrefixes := []string{"iOS", "Android"}
  88. sponsorIDs := []string{prng.HexString(SPONSOR_ID_LENGTH)}
  89. bytesTCP := int64(2048)
  90. bytesUDP := int64(1024)
  91. eventCount := 10
  92. addBytes := func() {
  93. for i := 0; i < eventCount; i++ {
  94. for _, clientRegion := range clientRegions {
  95. for _, clientASN := range clientASNs {
  96. geoIPData := GeoIPData{
  97. Country: clientRegion,
  98. ASN: clientASN,
  99. }
  100. for _, clientPlatformPrefix := range clientPlatformPrefixes {
  101. clientPlatform := clientPlatformPrefix + prng.DefaultPRNG().HexString(4)
  102. apiParams := common.APIParameters{
  103. "client_platform": clientPlatform,
  104. "sponsor_id": sponsorIDs[0],
  105. }
  106. for _, destASN := range destASNs {
  107. destBytesLogger.AddASNBytes(destASN, geoIPData, apiParams, bytesTCP, bytesUDP)
  108. }
  109. for _, destDomain := range destDomains {
  110. destBytesLogger.AddDomainBytes(destDomain, geoIPData, apiParams, bytesTCP, bytesUDP)
  111. }
  112. }
  113. }
  114. }
  115. }
  116. }
  117. checkLogs := func() error {
  118. logsMutex.Lock()
  119. defer logsMutex.Unlock()
  120. for i, logs := range [][]map[string]interface{}{asnDestBytesLogs, domainDestBytesLogs} {
  121. destCount := len(destASNs)
  122. if i != 0 {
  123. destCount = len(destDomains)
  124. }
  125. if len(logs) !=
  126. destCount*len(clientRegions)*len(clientASNs)*len(clientPlatformPrefixes)*len(sponsorIDs) {
  127. return errors.Tracef("unexpected log count: %d", len(logs))
  128. }
  129. loggedDestASNs := make(map[string]struct{})
  130. loggedDestDomains := make(map[string]struct{})
  131. loggedClientRegions := make(map[string]struct{})
  132. loggedClientASNs := make(map[string]struct{})
  133. loggedClientPlatforms := make(map[string]struct{})
  134. loggedSponsorIDs := make(map[string]struct{})
  135. sumBytesTCP := int64(0)
  136. sumBytesUDP := int64(0)
  137. sumBytes := int64(0)
  138. for _, logFields := range logs {
  139. if i == 0 {
  140. loggedDestASNs[logFields["asn"].(string)] = struct{}{}
  141. } else {
  142. loggedDestDomains[logFields["domain"].(string)] = struct{}{}
  143. }
  144. loggedClientRegions[logFields["client_region"].(string)] = struct{}{}
  145. loggedClientASNs[logFields["client_asn"].(string)] = struct{}{}
  146. loggedClientPlatforms[logFields["client_platform"].(string)] = struct{}{}
  147. loggedSponsorIDs[logFields["sponsor_id"].(string)] = struct{}{}
  148. sumBytesTCP += int64(logFields["bytes_tcp"].(float64))
  149. sumBytesUDP += int64(logFields["bytes_udp"].(float64))
  150. sumBytes += int64(logFields["bytes"].(float64))
  151. }
  152. checkFields := func(logged map[string]struct{}, expected []string) error {
  153. if len(logged) != len(expected) {
  154. return errors.Tracef("unexpected length: %d", len(logged))
  155. }
  156. for _, key := range expected {
  157. if _, ok := logged[key]; !ok {
  158. return errors.Tracef("missing %v", key)
  159. }
  160. }
  161. return nil
  162. }
  163. if i == 0 {
  164. err := checkFields(loggedDestASNs, destASNs)
  165. if err != nil {
  166. return errors.Trace(err)
  167. }
  168. } else {
  169. err = checkFields(loggedDestDomains, destDomains)
  170. if err != nil {
  171. return errors.Trace(err)
  172. }
  173. }
  174. err := checkFields(loggedClientRegions, clientRegions)
  175. if err != nil {
  176. return errors.Trace(err)
  177. }
  178. err = checkFields(loggedClientASNs, clientASNs)
  179. if err != nil {
  180. return errors.Trace(err)
  181. }
  182. err = checkFields(loggedClientPlatforms, clientPlatformPrefixes)
  183. if err != nil {
  184. return errors.Trace(err)
  185. }
  186. err = checkFields(loggedSponsorIDs, sponsorIDs)
  187. if err != nil {
  188. return errors.Trace(err)
  189. }
  190. if sumBytesTCP != int64(len(logs)*eventCount)*bytesTCP {
  191. return errors.Tracef("unexpected TCP bytes: %d", sumBytesTCP)
  192. }
  193. if sumBytesUDP != int64(len(logs)*eventCount)*bytesUDP {
  194. return errors.Tracef("unexpected UDP bytes: %d", sumBytesUDP)
  195. }
  196. if sumBytes != int64(len(logs)*eventCount)*(bytesTCP+bytesUDP) {
  197. return errors.Tracef("unexpected bytes: %d", sumBytes)
  198. }
  199. }
  200. asnDestBytesLogs = nil
  201. domainDestBytesLogs = nil
  202. return nil
  203. }
  204. for i := 0; i < 2; i++ {
  205. addBytes()
  206. time.Sleep(logPeriod * 2)
  207. err := checkLogs()
  208. if err != nil {
  209. return errors.Trace(err)
  210. }
  211. }
  212. addBytes()
  213. destBytesLogger.Stop()
  214. err = checkLogs()
  215. if err != nil {
  216. return errors.Trace(err)
  217. }
  218. return nil
  219. }