anubis_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. package lib
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/url"
  8. "os"
  9. "strings"
  10. "sync"
  11. "testing"
  12. "time"
  13. "github.com/TecharoHQ/anubis"
  14. "github.com/TecharoHQ/anubis/data"
  15. "github.com/TecharoHQ/anubis/internal"
  16. "github.com/TecharoHQ/anubis/internal/thoth/thothmock"
  17. "github.com/TecharoHQ/anubis/lib/policy"
  18. "github.com/TecharoHQ/anubis/lib/policy/config"
  19. )
  20. func init() {
  21. internal.InitSlog("debug")
  22. }
  23. func loadPolicies(t *testing.T, fname string) *policy.ParsedConfig {
  24. t.Helper()
  25. ctx := thothmock.WithMockThoth(t)
  26. anubisPolicy, err := LoadPoliciesOrDefault(ctx, fname, anubis.DefaultDifficulty)
  27. if err != nil {
  28. t.Fatal(err)
  29. }
  30. return anubisPolicy
  31. }
  32. func spawnAnubis(t *testing.T, opts Options) *Server {
  33. t.Helper()
  34. s, err := New(opts)
  35. if err != nil {
  36. t.Fatalf("can't construct libanubis.Server: %v", err)
  37. }
  38. return s
  39. }
  40. type challengeResp struct {
  41. Challenge string `json:"challenge"`
  42. }
  43. func makeChallenge(t *testing.T, ts *httptest.Server, cli *http.Client) challengeResp {
  44. t.Helper()
  45. req, err := http.NewRequest(http.MethodPost, ts.URL+"/.within.website/x/cmd/anubis/api/make-challenge", nil)
  46. if err != nil {
  47. t.Fatalf("can't make request: %v", err)
  48. }
  49. q := req.URL.Query()
  50. q.Set("redir", "/")
  51. req.URL.RawQuery = q.Encode()
  52. resp, err := cli.Do(req)
  53. if err != nil {
  54. t.Fatalf("can't request challenge: %v", err)
  55. }
  56. defer resp.Body.Close()
  57. var chall challengeResp
  58. if err := json.NewDecoder(resp.Body).Decode(&chall); err != nil {
  59. t.Fatalf("can't read challenge response body: %v", err)
  60. }
  61. return chall
  62. }
  63. func handleChallengeZeroDifficulty(t *testing.T, ts *httptest.Server, cli *http.Client, chall challengeResp) *http.Response {
  64. t.Helper()
  65. nonce := 0
  66. elapsedTime := 420
  67. redir := "/"
  68. calculated := ""
  69. calcString := fmt.Sprintf("%s%d", chall.Challenge, nonce)
  70. calculated = internal.SHA256sum(calcString)
  71. req, err := http.NewRequest(http.MethodGet, ts.URL+"/.within.website/x/cmd/anubis/api/pass-challenge", nil)
  72. if err != nil {
  73. t.Fatalf("can't make request: %v", err)
  74. }
  75. q := req.URL.Query()
  76. q.Set("response", calculated)
  77. q.Set("nonce", fmt.Sprint(nonce))
  78. q.Set("redir", redir)
  79. q.Set("elapsedTime", fmt.Sprint(elapsedTime))
  80. req.URL.RawQuery = q.Encode()
  81. resp, err := cli.Do(req)
  82. if err != nil {
  83. t.Fatalf("can't do request: %v", err)
  84. }
  85. return resp
  86. }
  87. type loggingCookieJar struct {
  88. t *testing.T
  89. lock sync.Mutex
  90. cookies map[string][]*http.Cookie
  91. }
  92. func (lcj *loggingCookieJar) Cookies(u *url.URL) []*http.Cookie {
  93. lcj.lock.Lock()
  94. defer lcj.lock.Unlock()
  95. // XXX(Xe): This is not RFC compliant in the slightest.
  96. result, ok := lcj.cookies[u.Host]
  97. if !ok {
  98. return nil
  99. }
  100. lcj.t.Logf("requested cookies for %s", u)
  101. for _, ckie := range result {
  102. lcj.t.Logf("get cookie: <- %s", ckie)
  103. }
  104. return result
  105. }
  106. func (lcj *loggingCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
  107. lcj.lock.Lock()
  108. defer lcj.lock.Unlock()
  109. for _, ckie := range cookies {
  110. lcj.t.Logf("set cookie: %s -> %s", u, ckie)
  111. }
  112. // XXX(Xe): This is not RFC compliant in the slightest.
  113. lcj.cookies[u.Host] = append(lcj.cookies[u.Host], cookies...)
  114. }
  115. func httpClient(t *testing.T) *http.Client {
  116. t.Helper()
  117. cli := &http.Client{
  118. Jar: &loggingCookieJar{t: t, cookies: map[string][]*http.Cookie{}},
  119. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  120. return http.ErrUseLastResponse
  121. },
  122. }
  123. return cli
  124. }
  125. func TestLoadPolicies(t *testing.T) {
  126. for _, fname := range []string{"botPolicies.json", "botPolicies.yaml"} {
  127. t.Run(fname, func(t *testing.T) {
  128. fin, err := data.BotPolicies.Open(fname)
  129. if err != nil {
  130. t.Fatal(err)
  131. }
  132. defer fin.Close()
  133. if _, err := policy.ParseConfig(t.Context(), fin, fname, 4); err != nil {
  134. t.Fatal(err)
  135. }
  136. })
  137. }
  138. }
  139. // Regression test for CVE-2025-24369
  140. func TestCVE2025_24369(t *testing.T) {
  141. pol := loadPolicies(t, "")
  142. pol.DefaultDifficulty = 4
  143. srv := spawnAnubis(t, Options{
  144. Next: http.NewServeMux(),
  145. Policy: pol,
  146. CookieName: t.Name(),
  147. })
  148. ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
  149. defer ts.Close()
  150. cli := httpClient(t)
  151. chall := makeChallenge(t, ts, cli)
  152. resp := handleChallengeZeroDifficulty(t, ts, cli, chall)
  153. if resp.StatusCode == http.StatusFound {
  154. t.Log("Regression on CVE-2025-24369")
  155. t.Errorf("wanted HTTP status %d, got: %d", http.StatusForbidden, resp.StatusCode)
  156. }
  157. }
  158. func TestCookieCustomExpiration(t *testing.T) {
  159. pol := loadPolicies(t, "")
  160. pol.DefaultDifficulty = 0
  161. ckieExpiration := 10 * time.Minute
  162. srv := spawnAnubis(t, Options{
  163. Next: http.NewServeMux(),
  164. Policy: pol,
  165. CookieExpiration: ckieExpiration,
  166. })
  167. ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
  168. defer ts.Close()
  169. cli := httpClient(t)
  170. chall := makeChallenge(t, ts, cli)
  171. requestReceiveLowerBound := time.Now().Add(-1 * time.Minute)
  172. resp := handleChallengeZeroDifficulty(t, ts, cli, chall)
  173. requestReceiveUpperBound := time.Now()
  174. if resp.StatusCode != http.StatusFound {
  175. resp.Write(os.Stderr)
  176. t.Errorf("wanted %d, got: %d", http.StatusFound, resp.StatusCode)
  177. }
  178. var ckie *http.Cookie
  179. for _, cookie := range resp.Cookies() {
  180. t.Logf("%#v", cookie)
  181. if cookie.Name == srv.cookieName {
  182. ckie = cookie
  183. break
  184. }
  185. }
  186. if ckie == nil {
  187. t.Errorf("Cookie %q not found", srv.cookieName)
  188. return
  189. }
  190. expirationLowerBound := requestReceiveLowerBound.Add(ckieExpiration)
  191. expirationUpperBound := requestReceiveUpperBound.Add(ckieExpiration)
  192. // Since the cookie expiration precision is only to the second due to the Unix() call, we can
  193. // lower the level of expected precision.
  194. if ckie.Expires.Unix() < expirationLowerBound.Unix() || ckie.Expires.Unix() > expirationUpperBound.Unix() {
  195. t.Errorf("cookie expiration is not within the expected range. expected between: %v and %v. got: %v", expirationLowerBound, expirationUpperBound, ckie.Expires)
  196. return
  197. }
  198. }
  199. func TestCookieSettings(t *testing.T) {
  200. pol := loadPolicies(t, "")
  201. pol.DefaultDifficulty = 0
  202. srv := spawnAnubis(t, Options{
  203. Next: http.NewServeMux(),
  204. Policy: pol,
  205. CookieDomain: "127.0.0.1",
  206. CookiePartitioned: true,
  207. CookieName: t.Name(),
  208. CookieExpiration: anubis.CookieDefaultExpirationTime,
  209. })
  210. requestReceiveLowerBound := time.Now()
  211. ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
  212. defer ts.Close()
  213. cli := httpClient(t)
  214. chall := makeChallenge(t, ts, cli)
  215. resp := handleChallengeZeroDifficulty(t, ts, cli, chall)
  216. requestReceiveUpperBound := time.Now()
  217. if resp.StatusCode != http.StatusFound {
  218. resp.Write(os.Stderr)
  219. t.Errorf("wanted %d, got: %d", http.StatusFound, resp.StatusCode)
  220. }
  221. var ckie *http.Cookie
  222. for _, cookie := range resp.Cookies() {
  223. t.Logf("%#v", cookie)
  224. if cookie.Name == srv.cookieName {
  225. ckie = cookie
  226. break
  227. }
  228. }
  229. if ckie == nil {
  230. t.Errorf("Cookie %q not found", srv.cookieName)
  231. return
  232. }
  233. if ckie.Domain != "127.0.0.1" {
  234. t.Errorf("cookie domain is wrong, wanted 127.0.0.1, got: %s", ckie.Domain)
  235. }
  236. expirationLowerBound := requestReceiveLowerBound.Add(anubis.CookieDefaultExpirationTime)
  237. expirationUpperBound := requestReceiveUpperBound.Add(anubis.CookieDefaultExpirationTime)
  238. // Since the cookie expiration precision is only to the second due to the Unix() call, we can
  239. // lower the level of expected precision.
  240. if ckie.Expires.Unix() < expirationLowerBound.Unix() || ckie.Expires.Unix() > expirationUpperBound.Unix() {
  241. t.Errorf("cookie expiration is not within the expected range. expected between: %v and %v. got: %v", expirationLowerBound, expirationUpperBound, ckie.Expires)
  242. return
  243. }
  244. if ckie.Partitioned != srv.opts.CookiePartitioned {
  245. t.Errorf("wanted partitioned flag %v, got: %v", srv.opts.CookiePartitioned, ckie.Partitioned)
  246. }
  247. }
  248. func TestCheckDefaultDifficultyMatchesPolicy(t *testing.T) {
  249. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  250. fmt.Fprintln(w, "OK")
  251. })
  252. for i := 1; i < 10; i++ {
  253. t.Run(fmt.Sprint(i), func(t *testing.T) {
  254. anubisPolicy, err := LoadPoliciesOrDefault(t.Context(), "", i)
  255. if err != nil {
  256. t.Fatal(err)
  257. }
  258. s, err := New(Options{
  259. Next: h,
  260. Policy: anubisPolicy,
  261. ServeRobotsTXT: true,
  262. })
  263. if err != nil {
  264. t.Fatalf("can't construct libanubis.Server: %v", err)
  265. }
  266. req, err := http.NewRequest(http.MethodGet, "/", nil)
  267. if err != nil {
  268. t.Fatal(err)
  269. }
  270. req.Header.Add("X-Real-Ip", "127.0.0.1")
  271. _, bot, err := s.check(req)
  272. if err != nil {
  273. t.Fatal(err)
  274. }
  275. if bot.Challenge.Difficulty != i {
  276. t.Errorf("Challenge.Difficulty is wrong, wanted %d, got: %d", i, bot.Challenge.Difficulty)
  277. }
  278. if bot.Challenge.ReportAs != i {
  279. t.Errorf("Challenge.ReportAs is wrong, wanted %d, got: %d", i, bot.Challenge.ReportAs)
  280. }
  281. })
  282. }
  283. }
  284. func TestBasePrefix(t *testing.T) {
  285. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  286. fmt.Fprintln(w, "OK")
  287. })
  288. testCases := []struct {
  289. name string
  290. basePrefix string
  291. path string
  292. expected string
  293. }{
  294. {
  295. name: "no prefix",
  296. basePrefix: "/",
  297. path: "/.within.website/x/cmd/anubis/api/make-challenge",
  298. expected: "/.within.website/x/cmd/anubis/api/make-challenge",
  299. },
  300. {
  301. name: "with prefix",
  302. basePrefix: "/myapp",
  303. path: "/myapp/.within.website/x/cmd/anubis/api/make-challenge",
  304. expected: "/myapp/.within.website/x/cmd/anubis/api/make-challenge",
  305. },
  306. {
  307. name: "with prefix and trailing slash",
  308. basePrefix: "/myapp/",
  309. path: "/myapp/.within.website/x/cmd/anubis/api/make-challenge",
  310. expected: "/myapp/.within.website/x/cmd/anubis/api/make-challenge",
  311. },
  312. }
  313. for _, tc := range testCases {
  314. t.Run(tc.name, func(t *testing.T) {
  315. // Reset the global BasePrefix before each test
  316. anubis.BasePrefix = ""
  317. pol := loadPolicies(t, "")
  318. pol.DefaultDifficulty = 4
  319. srv := spawnAnubis(t, Options{
  320. Next: h,
  321. Policy: pol,
  322. BasePrefix: tc.basePrefix,
  323. })
  324. ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
  325. defer ts.Close()
  326. cli := httpClient(t)
  327. req, err := http.NewRequest(http.MethodPost, ts.URL+tc.path, nil)
  328. if err != nil {
  329. t.Fatal(err)
  330. }
  331. q := req.URL.Query()
  332. q.Set("redir", tc.basePrefix)
  333. req.URL.RawQuery = q.Encode()
  334. // Test API endpoint with prefix
  335. resp, err := cli.Do(req)
  336. if err != nil {
  337. t.Fatalf("can't request challenge: %v", err)
  338. }
  339. defer resp.Body.Close()
  340. if resp.StatusCode != http.StatusOK {
  341. t.Errorf("expected status code %d, got: %d", http.StatusOK, resp.StatusCode)
  342. }
  343. var chall challengeResp
  344. if err := json.NewDecoder(resp.Body).Decode(&chall); err != nil {
  345. t.Fatalf("can't read challenge response body: %v", err)
  346. }
  347. if chall.Challenge == "" {
  348. t.Errorf("expected non-empty challenge")
  349. }
  350. // Test cookie path when passing challenge
  351. // Find a nonce that produces a hash with the required number of leading zeros
  352. nonce := 0
  353. var calculated string
  354. for {
  355. calcString := fmt.Sprintf("%s%d", chall.Challenge, nonce)
  356. calculated = internal.SHA256sum(calcString)
  357. if strings.HasPrefix(calculated, strings.Repeat("0", pol.DefaultDifficulty)) {
  358. break
  359. }
  360. nonce++
  361. }
  362. elapsedTime := 420
  363. redir := "/"
  364. cli.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  365. return http.ErrUseLastResponse
  366. }
  367. // Construct the correct path for pass-challenge
  368. passChallengePath := tc.path
  369. passChallengePath = passChallengePath[:strings.LastIndex(passChallengePath, "/")+1] + "pass-challenge"
  370. req, err = http.NewRequest(http.MethodGet, ts.URL+passChallengePath, nil)
  371. if err != nil {
  372. t.Fatalf("can't make request: %v", err)
  373. }
  374. for _, ckie := range resp.Cookies() {
  375. req.AddCookie(ckie)
  376. }
  377. q = req.URL.Query()
  378. q.Set("response", calculated)
  379. q.Set("nonce", fmt.Sprint(nonce))
  380. q.Set("redir", redir)
  381. q.Set("elapsedTime", fmt.Sprint(elapsedTime))
  382. req.URL.RawQuery = q.Encode()
  383. resp, err = cli.Do(req)
  384. if err != nil {
  385. t.Fatalf("can't do challenge passing: %v", err)
  386. }
  387. if resp.StatusCode != http.StatusFound {
  388. t.Errorf("wanted %d, got: %d", http.StatusFound, resp.StatusCode)
  389. }
  390. // Check cookie path
  391. var ckie *http.Cookie
  392. for _, cookie := range resp.Cookies() {
  393. if cookie.Name == anubis.CookieName {
  394. ckie = cookie
  395. break
  396. }
  397. }
  398. if ckie == nil {
  399. t.Errorf("Cookie %q not found", anubis.CookieName)
  400. return
  401. }
  402. expectedPath := "/"
  403. if tc.basePrefix != "" {
  404. expectedPath = strings.TrimSuffix(tc.basePrefix, "/") + "/"
  405. }
  406. if ckie.Path != expectedPath {
  407. t.Errorf("cookie path is wrong, wanted %s, got: %s", expectedPath, ckie.Path)
  408. }
  409. })
  410. }
  411. }
  412. func TestCustomStatusCodes(t *testing.T) {
  413. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  414. t.Log(r.UserAgent())
  415. w.WriteHeader(http.StatusOK)
  416. fmt.Fprintln(w, "OK")
  417. })
  418. statusMap := map[string]int{
  419. "ALLOW": 200,
  420. "CHALLENGE": 401,
  421. "DENY": 403,
  422. }
  423. pol := loadPolicies(t, "./testdata/aggressive_403.yaml")
  424. pol.DefaultDifficulty = 4
  425. srv := spawnAnubis(t, Options{
  426. Next: h,
  427. Policy: pol,
  428. })
  429. ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
  430. defer ts.Close()
  431. for userAgent, statusCode := range statusMap {
  432. t.Run(userAgent, func(t *testing.T) {
  433. req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL, nil)
  434. if err != nil {
  435. t.Fatal(err)
  436. }
  437. req.Header.Set("User-Agent", userAgent)
  438. resp, err := ts.Client().Do(req)
  439. if err != nil {
  440. t.Fatal(err)
  441. }
  442. if resp.StatusCode != statusCode {
  443. t.Errorf("wanted status code %d but got: %d", statusCode, resp.StatusCode)
  444. }
  445. })
  446. }
  447. }
  448. func TestCloudflareWorkersRule(t *testing.T) {
  449. for _, variant := range []string{"cel", "header"} {
  450. t.Run(variant, func(t *testing.T) {
  451. pol := loadPolicies(t, "./testdata/cloudflare-workers-"+variant+".yaml")
  452. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  453. fmt.Fprintln(w, "OK")
  454. })
  455. s, err := New(Options{
  456. Next: h,
  457. Policy: pol,
  458. ServeRobotsTXT: true,
  459. })
  460. if err != nil {
  461. t.Fatalf("can't construct libanubis.Server: %v", err)
  462. }
  463. t.Run("with-cf-worker-header", func(t *testing.T) {
  464. req, err := http.NewRequest(http.MethodGet, "/", nil)
  465. if err != nil {
  466. t.Fatal(err)
  467. }
  468. req.Header.Add("X-Real-Ip", "127.0.0.1")
  469. req.Header.Add("Cf-Worker", "true")
  470. cr, _, err := s.check(req)
  471. if err != nil {
  472. t.Fatal(err)
  473. }
  474. if cr.Rule != config.RuleDeny {
  475. t.Errorf("rule is wrong, wanted %s, got: %s", config.RuleDeny, cr.Rule)
  476. }
  477. })
  478. t.Run("no-cf-worker-header", func(t *testing.T) {
  479. req, err := http.NewRequest(http.MethodGet, "/", nil)
  480. if err != nil {
  481. t.Fatal(err)
  482. }
  483. req.Header.Add("X-Real-Ip", "127.0.0.1")
  484. cr, _, err := s.check(req)
  485. if err != nil {
  486. t.Fatal(err)
  487. }
  488. if cr.Rule != config.RuleAllow {
  489. t.Errorf("rule is wrong, wanted %s, got: %s", config.RuleAllow, cr.Rule)
  490. }
  491. })
  492. })
  493. }
  494. }
  495. func TestRuleChange(t *testing.T) {
  496. pol := loadPolicies(t, "testdata/rule_change.yaml")
  497. pol.DefaultDifficulty = 0
  498. ckieExpiration := 10 * time.Minute
  499. srv := spawnAnubis(t, Options{
  500. Next: http.NewServeMux(),
  501. Policy: pol,
  502. CookieDomain: "127.0.0.1",
  503. CookieName: t.Name(),
  504. CookieExpiration: ckieExpiration,
  505. })
  506. ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
  507. defer ts.Close()
  508. cli := httpClient(t)
  509. chall := makeChallenge(t, ts, cli)
  510. resp := handleChallengeZeroDifficulty(t, ts, cli, chall)
  511. if resp.StatusCode != http.StatusFound {
  512. resp.Write(os.Stderr)
  513. t.Errorf("wanted %d, got: %d", http.StatusFound, resp.StatusCode)
  514. }
  515. }
  516. func TestStripBasePrefixFromRequest(t *testing.T) {
  517. testCases := []struct {
  518. name string
  519. basePrefix string
  520. stripBasePrefix bool
  521. requestPath string
  522. expectedPath string
  523. }{
  524. {
  525. name: "strip disabled - no change",
  526. basePrefix: "/foo",
  527. stripBasePrefix: false,
  528. requestPath: "/foo/bar",
  529. expectedPath: "/foo/bar",
  530. },
  531. {
  532. name: "strip enabled - removes prefix",
  533. basePrefix: "/foo",
  534. stripBasePrefix: true,
  535. requestPath: "/foo/bar",
  536. expectedPath: "/bar",
  537. },
  538. {
  539. name: "strip enabled - root becomes slash",
  540. basePrefix: "/foo",
  541. stripBasePrefix: true,
  542. requestPath: "/foo",
  543. expectedPath: "/",
  544. },
  545. {
  546. name: "strip enabled - trailing slash on base prefix",
  547. basePrefix: "/foo/",
  548. stripBasePrefix: true,
  549. requestPath: "/foo/bar",
  550. expectedPath: "/bar",
  551. },
  552. {
  553. name: "strip enabled - no prefix match",
  554. basePrefix: "/foo",
  555. stripBasePrefix: true,
  556. requestPath: "/other/bar",
  557. expectedPath: "/other/bar",
  558. },
  559. {
  560. name: "strip enabled - empty base prefix",
  561. basePrefix: "",
  562. stripBasePrefix: true,
  563. requestPath: "/foo/bar",
  564. expectedPath: "/foo/bar",
  565. },
  566. {
  567. name: "strip enabled - nested path",
  568. basePrefix: "/app",
  569. stripBasePrefix: true,
  570. requestPath: "/app/api/v1/users",
  571. expectedPath: "/api/v1/users",
  572. },
  573. {
  574. name: "strip enabled - exact match becomes root",
  575. basePrefix: "/myapp",
  576. stripBasePrefix: true,
  577. requestPath: "/myapp/",
  578. expectedPath: "/",
  579. },
  580. }
  581. for _, tc := range testCases {
  582. t.Run(tc.name, func(t *testing.T) {
  583. srv := &Server{
  584. opts: Options{
  585. BasePrefix: tc.basePrefix,
  586. StripBasePrefix: tc.stripBasePrefix,
  587. },
  588. }
  589. req := httptest.NewRequest(http.MethodGet, tc.requestPath, nil)
  590. originalPath := req.URL.Path
  591. result := srv.stripBasePrefixFromRequest(req)
  592. if result.URL.Path != tc.expectedPath {
  593. t.Errorf("expected path %q, got %q", tc.expectedPath, result.URL.Path)
  594. }
  595. // Ensure original request is not modified when no stripping should occur
  596. if !tc.stripBasePrefix || tc.basePrefix == "" || !strings.HasPrefix(tc.requestPath, strings.TrimSuffix(tc.basePrefix, "/")) {
  597. if result != req {
  598. t.Error("expected same request object when no modification needed")
  599. }
  600. } else {
  601. // Ensure original request is not modified when stripping occurs
  602. if req.URL.Path != originalPath {
  603. t.Error("original request was modified")
  604. }
  605. }
  606. })
  607. }
  608. }