Documentation
¶
Overview ¶
Package modtest provides shared helpers for unit-testing scanner modules against an in-process httptest.Server.
Unlike the e2e harness (test/e2e/helper_test.go) these helpers carry no build tag, so they are available to fast `-short` unit tests. They wire up a real *http.Requester against the shared loopback dialer and build the *httpmsg.HttpRequestResponse / insertion points a module's scan method expects, letting a test exercise true detection logic without Docker.
Typical use:
srv := httptest.NewServer(handler)
defer srv.Close()
client := modtest.Requester(t)
rr := modtest.Request(t, srv.URL+"/?id=1")
ip := modtest.InsertionPoint(t, rr, "id")
res, err := mymod.New().ScanPerInsertionPoint(rr, ip, client, &modkit.ScanContext{})
Index ¶
- Variables
- func DecodeContentEncoding(body []byte, encoding string, br BrotliDecoder) ([]byte, bool)
- func HTTPCtx(path, contentType, body string) *httpmsg.HttpRequestResponse
- func HTTPCtxHeaders(path, headers, body string) *httpmsg.HttpRequestResponse
- func HTTPCtxMethod(method, path, contentType, body string) *httpmsg.HttpRequestResponse
- func InsertionPoint(t testing.TB, rr *httpmsg.HttpRequestResponse, name string) httpmsg.InsertionPoint
- func InsertionPointByType(t testing.TB, rr *httpmsg.HttpRequestResponse, typ httpmsg.InsertionPointType) httpmsg.InsertionPoint
- func RandomContent() http.Handler
- func RateLimit429(allow int64) http.Handler
- func RawCtx(rawReq, rawResp string) *httpmsg.HttpRequestResponse
- func Request(t testing.TB, rawURL string) *httpmsg.HttpRequestResponse
- func RequestJSON(t testing.TB, rawURL, jsonBody string) *httpmsg.HttpRequestResponse
- func RequestMethod(t testing.TB, method, rawURL, body string) *httpmsg.HttpRequestResponse
- func Requester(t testing.TB) *httpRequester.Requester
- func RequesterNoThrottlePause(t testing.TB) *httpRequester.Requester
- func Response(rr *httpmsg.HttpRequestResponse, contentType, body string) *httpmsg.HttpRequestResponse
- func ResponseChain(t testing.TB, status int, header http.Header, body string) *httputil.ResponseChain
- func RoundRobinHandler(hits *int64, bodies ...string) http.HandlerFunc
- func RunActive(mod ActiveModule, rr *httpmsg.HttpRequestResponse, ...) ([]*output.ResultEvent, error)
- func SafeEcho() http.Handler
- func ScanCtxWithTech(srvURL string, tags ...string) *modkit.ScanContext
- func Serve(t testing.TB, h http.Handler) *httptest.Server
- func SlowHost(base, jitter time.Duration) http.Handler
- func Soft404() http.Handler
- func VerifyNoLeaks(m *testing.M, extra ...goleak.Option)
- func WAFBlock() http.Handler
- type ActiveModule
- type BrotliDecoder
- type Fixture
- type MockOASTProvider
Constants ¶
This section is empty.
Variables ¶
var ( // ApacheDefaultPageRHEL is the smaller of the pair. ApacheDefaultPageRHEL = "<html><head><title>Test Page for the HTTP Server on Red Hat Enterprise Linux</title></head>" + "<body><h1>Red Hat Enterprise Linux Test Page</h1>" + "<p>This page is used to test the proper operation of the HTTP server after it has been " + "installed. If you can read this page, it means that the HTTP server installed at this site " + "is working properly.</p>" + "<p>If you are a member of the general public: the fact that you are seeing this page " + "indicates that the website you just visited is either experiencing problems or is " + "undergoing routine maintenance.</p>" + redHatFiller + "</body></html>" // ApacheDefaultPageUbuntu is the larger of the pair. It carries the word // "installation" in ordinary prose, exactly as the real page does — the token // that once earned a Critical WordPress-installer finding on a parked host. ApacheDefaultPageUbuntu = "<html><head><title>Apache2 Ubuntu Default Page: It works</title></head>" + "<body><h1>Apache2 Ubuntu Default Page</h1>" + "<p>It works! This is the default welcome page used to test the correct operation of the " + "Apache2 server after installation on Ubuntu systems.</p>" + "<p>The configuration layout for an Apache2 web server installation on Ubuntu systems is " + "fully documented in the README file referenced below.</p>" + ubuntuFiller + "</body></html>" )
A round-robin backend pool — a load balancer fronting two mismatched backends, so the SAME unmodified request returns one of two unrelated pages depending on which backend answers. This is the surface that manufactures phantom differentials for every body-diff oracle in the scanner (boolean-blind injection, path normalization, cross-ID comparison, header size shifts), and the shape modkit.EndpointVolatile exists to reject.
The two pages below are the real Apache defaults from the parked hosts that motivated the gate, sized ~4x apart like the originals (5.9 KB vs 11.3 KB). The proportions matter to the modules under test: the pages must share almost no vocabulary (so they are not "the same page" by textual similarity) and the length gap must clear the substantial-body-difference bar (>100 bytes AND >=20%), because a pair that failed either bar would let a test pass for the wrong reason — the module rejecting the differential on its own rather than on the determinism gate. Declared as vars rather than consts because the filler is built with strings.Repeat. Treat them as read-only.
Functions ¶
func DecodeContentEncoding ¶ added in v0.5.6
func DecodeContentEncoding(body []byte, encoding string, br BrotliDecoder) ([]byte, bool)
DecodeContentEncoding undoes a Content-Encoding list on a request body, last-applied first, the way a server's body parser does. ok is false for any coding other than br/gzip, or for bytes that fail to decode.
It is shared because a fake body parser is the only way to test a request-decoding module, and the codings it accepts have to agree with the encoded control streams the modules send — three copies of this had already drifted apart on whether an unknown coding is an error.
func HTTPCtx ¶ added in v0.5.3
func HTTPCtx(path, contentType, body string) *httpmsg.HttpRequestResponse
HTTPCtx builds a captured GET of path (request-target, may carry a query) answered by a 200 OK with the given Content-Type and body.
func HTTPCtxHeaders ¶ added in v0.5.3
func HTTPCtxHeaders(path, headers, body string) *httpmsg.HttpRequestResponse
HTTPCtxHeaders builds a captured GET of path answered by a 200 OK whose header block is headers verbatim. Each header line in headers must end in "\r\n" (an empty string means no headers); the blank line and body follow.
func HTTPCtxMethod ¶ added in v0.5.3
func HTTPCtxMethod(method, path, contentType, body string) *httpmsg.HttpRequestResponse
HTTPCtxMethod is HTTPCtx with an explicit request method.
func InsertionPoint ¶
func InsertionPoint(t testing.TB, rr *httpmsg.HttpRequestResponse, name string) httpmsg.InsertionPoint
InsertionPoint returns the parameter insertion point named name from rr, or fails the test if no such point exists. Nested points are included so JSON / form sub-fields can be targeted by name.
func InsertionPointByType ¶
func InsertionPointByType(t testing.TB, rr *httpmsg.HttpRequestResponse, typ httpmsg.InsertionPointType) httpmsg.InsertionPoint
InsertionPointByType returns the first insertion point of the given type from rr, or fails the test if none exists. Use it for the positional points that InsertionPoint cannot address readably: URL path folders and filenames are named by ordinal ("1", "2", …), so selecting them by name is both opaque and brittle whenever a test URL's path depth changes.
func RandomContent ¶ added in v0.5.7
RandomContent returns a page whose body changes on every request (a random token of random length, like a CSRF nonce or ad slot), independent of input. Differential oracles must not read instability as a payload effect.
func RateLimit429 ¶ added in v0.5.7
RateLimit429 serves SafeEcho for the first allow requests, then answers every later request 429 with Retry-After - an application limiter that has engaged. A payload "causing" a 429 proves nothing.
func RawCtx ¶ added in v0.5.3
func RawCtx(rawReq, rawResp string) *httpmsg.HttpRequestResponse
RawCtx pairs the raw request rawReq, addressed to https://example.com:443, with the raw response rawResp.
func Request ¶
func Request(t testing.TB, rawURL string) *httpmsg.HttpRequestResponse
Request builds a GET *httpmsg.HttpRequestResponse targeting the absolute rawURL (e.g. an httptest.Server URL plus path/query). The HttpService is derived from the URL so a module's fuzzed requests route back to the test server. The response is left nil; modules that need a baseline fetch it themselves via the requester.
func RequestJSON ¶
func RequestJSON(t testing.TB, rawURL, jsonBody string) *httpmsg.HttpRequestResponse
RequestJSON builds a POST request whose body is sent as application/json, so JSON fields become INS_PARAM_JSON insertion points. Use it for tests that target JSON parameters; RequestMethod sends form-urlencoded (INS_PARAM_BODY).
func RequestMethod ¶
func RequestMethod(t testing.TB, method, rawURL, body string) *httpmsg.HttpRequestResponse
RequestMethod is like Request but lets a test pick the method and supply a request body (used for POST/PUT insertion-point coverage). The body is sent as application/x-www-form-urlencoded; an empty body omits the Content-Length/body section. For a JSON body (INS_PARAM_JSON insertion points) use RequestJSON.
func Requester ¶
func Requester(t testing.TB) *httpRequester.Requester
Requester returns an *http.Requester wired to the shared loopback dialer, suitable for driving a module's scan method against an httptest.Server.
network.Init is reference-counted and idempotent: the dialer is created once per process and reused. We intentionally never Close it here — sequential and parallel tests share the dialer, and tearing it down mid-suite would break a concurrently running test.
func RequesterNoThrottlePause ¶ added in v0.5.7
func RequesterNoThrottlePause(t testing.TB) *httpRequester.Requester
RequesterNoThrottlePause is Requester whose host limiter never pauses a host on 429/503. For sweeps that fire many modules at a deliberately throttling fixture and only assert what the modules conclude.
func Response ¶
func Response(rr *httpmsg.HttpRequestResponse, contentType, body string) *httpmsg.HttpRequestResponse
Response returns a copy of rr with a synthetic 200 OK response (carrying the given content-type and body) attached. It mirrors the captured baseline response the executor supplies before active scanning. Modules that use the original response as a baseline (e.g. ssrf_detection) need this; modules that fetch their own baseline can ignore it and pass the bare Request.
func ResponseChain ¶ added in v0.5.0
func ResponseChain(t testing.TB, status int, header http.Header, body string) *httputil.ResponseChain
ResponseChain builds a filled *httputil.ResponseChain from a status, header set and body, mirroring what the requester hands a module.
It exists for tests of the response-classification helpers modules layer on top of a response — block/edge detection, keep-alive gates, content checks — which need a chain but no server. The returned chain is closed on cleanup.
func RoundRobinHandler ¶
func RoundRobinHandler(hits *int64, bodies ...string) http.HandlerFunc
RoundRobinHandler serves bodies in rotation — one per request, ignoring the request entirely — and counts every hit into hits, which the caller owns so a test can assert how many requests a gate actually spent. Pass at least one body; with a single body it degenerates into a stable endpoint, which is the useful negative control.
func RunActive ¶ added in v0.5.7
func RunActive(mod ActiveModule, rr *httpmsg.HttpRequestResponse, client *httpRequester.Requester, scanCtx *modkit.ScanContext) ([]*output.ResultEvent, error)
RunActive runs mod against rr the way the executor dispatches it: once per scan scope the module declares (the executor runs every declared scope):
- ScanScopeHost: ScanPerHost once;
- ScanScopeRequest: ScanPerRequest once;
- ScanScopeInsertionPoint: every insertion point of rr (nested included) the module accepts, ScanPerInsertionPoint for each.
Findings from every call are concatenated; per-call errors are joined and returned alongside whatever findings the other calls produced. It is the shared dispatcher for the benign sweep and the detection benchmark harness (test/benchmark/harness).
func SafeEcho ¶ added in v0.5.7
SafeEcho reflects every input back, correctly encoded for its context: HTML escaped in an HTML page for query/form input, JSON encoded in a JSON response for JSON bodies. Reflection is not injection.
func ScanCtxWithTech ¶ added in v0.5.6
func ScanCtxWithTech(srvURL string, tags ...string) *modkit.ScanContext
ScanCtxWithTech returns a ScanContext whose tech registry marks srvURL's host with each tag, the way a *_fingerprint passive module would have during a real scan. Pass no tags for a context that has seen no fingerprint — the case a tech-gated module must still handle.
func Serve ¶ added in v0.5.6
Serve starts an httptest server for h and closes it when the test ends.
It lives here rather than in each module's test file because every scan method takes (record, requester, scanCtx) and so every module test needs the same two lines; copies of it had already started appearing per package.
func SlowHost ¶ added in v0.5.7
SlowHost serves SafeEcho after base latency plus up to jitter of uniformly random extra delay on every request, payload or not. Timing oracles must not read a uniformly slow, noisy host as an injected sleep.
func Soft404 ¶ added in v0.5.7
Soft404 answers every path with 200 and a "not found" page that echoes the (escaped) path, the way catch-all SPA and CMS routes do. Existence probes that trust the status code see every file "present".
func VerifyNoLeaks ¶
VerifyNoLeaks runs goleak.VerifyTestMain with the standard ignore list for the process-lifetime infra goroutines that Requester starts via network.Init (the active mem guardian and a leveldb store) — singletons with no stop hook. Use it as the whole body of a package's TestMain when that package's tests drive a real Requester:
func TestMain(m *testing.M) { modtest.VerifyNoLeaks(m) }
extra adds a suite's own ignores on top of the standard list.
Types ¶
type ActiveModule ¶ added in v0.5.7
type ActiveModule interface {
ID() string
ScanScopes() modkit.ScanScope
AllowedInsertionPointTypes() modkit.InsertionPointTypeSet
ScanPerInsertionPoint(rr *httpmsg.HttpRequestResponse, ip httpmsg.InsertionPoint, client *httpRequester.Requester, scanCtx *modkit.ScanContext) ([]*output.ResultEvent, error)
ScanPerRequest(rr *httpmsg.HttpRequestResponse, client *httpRequester.Requester, scanCtx *modkit.ScanContext) ([]*output.ResultEvent, error)
ScanPerHost(rr *httpmsg.HttpRequestResponse, client *httpRequester.Requester, scanCtx *modkit.ScanContext) ([]*output.ResultEvent, error)
}
ActiveModule is the slice of modules.ActiveModule that RunActive needs. Declared here (modules.ActiveModule satisfies it) because pkg/modules imports every module package, whose tests import modtest - importing pkg/modules from here would be a cycle.
type BrotliDecoder ¶ added in v0.5.6
BrotliDecoder decodes a Brotli document, reporting false when the bytes are not one. Pass nil to DecodeContentEncoding for the real Go decoder; a test that needs to simulate a decoder which accepts something the Go one refuses (an unpatched libbrotli, say) supplies its own.
type Fixture ¶ added in v0.5.7
type Fixture struct {
Name string
// TimingOnly marks fixtures that only timing modules are run against (they
// are slow by construction).
TimingOnly bool
// Deterministic fixtures answer the same input the same way, so a module's
// request count against them is reproducible and can carry a budget.
// random_content and slow_host (random latency) vary run to run.
Deterministic bool
// Throttles marks fixtures that answer 429/503: a harness should give each
// module its own requester, since the limiter's throttle streak is per
// host and would otherwise couple parallel modules' request counts.
Throttles bool
New func() http.Handler
}
Fixture names a benign fixture and builds its handler.
func BenignFixtures ¶ added in v0.5.7
func BenignFixtures() []Fixture
BenignFixtures lists every benign fixture.
type MockOASTProvider ¶ added in v0.5.7
type MockOASTProvider struct {
URLs []string
Payloads map[string]string
// contains filtered or unexported fields
}
MockOASTProvider is an enabled modkit.OASTProvider that mints unique callback URLs under a reserved domain and records what was planted. No callback ever arrives, so a module that files a finding with it is reporting something other than an interaction.
func (*MockOASTProvider) Enabled ¶ added in v0.5.7
func (m *MockOASTProvider) Enabled() bool
Enabled implements modkit.OASTProvider.
func (*MockOASTProvider) GenerateURL ¶ added in v0.5.7
func (m *MockOASTProvider) GenerateURL(_, _, _, _, _ string) string
GenerateURL implements modkit.OASTProvider.
func (*MockOASTProvider) RecordPayload ¶ added in v0.5.7
func (m *MockOASTProvider) RecordPayload(callbackURL, payload string)
RecordPayload implements modkit.OASTProvider.