Documentation
¶
Overview ¶
Package client is unruly's HTTP layer.
Concurrency defaults come from measurement, not intuition. Sweeping a live PostgREST endpoint showed throughput peaking at 64 concurrent connections (701 req/s) and then collapsing: 128 gave 556 req/s, 256 gave 294, and 512 gave 163 with p50 latency rising from 63ms to 2.2s. No 429s were ever returned, so this is server-side queueing rather than a rate-limit policy. Pushing past the knee makes a scan slower and noisier at the same time.
Connection reuse mattered more than raw client speed: a process-per-request native client managed 251 req/s against Python-with-pooling at 323 req/s. Hence one shared transport with a generous idle pool.
Index ¶
- Constants
- Variables
- func Discard(resp *http.Response)
- func Map[T any, R any](ctx context.Context, concurrency int, items []T, fn func(context.Context, T) R) []R
- func ReadBody(resp *http.Response, limit int64) ([]byte, error)
- func UserAgent() string
- type AppOptions
- type Client
- func (c *Client) BaseURL() string
- func (c *Client) Do(ctx context.Context, method, url string, body []byte, hdr map[string]string) Response
- func (c *Client) GaveUp() bool
- func (c *Client) Get(ctx context.Context, url string, hdr map[string]string) Response
- func (c *Client) KeyRejected() bool
- func (c *Client) RPCURL(name string) string
- func (c *Client) RestBase() string
- func (c *Client) RestPrefix() string
- func (c *Client) RestURL(relation string) string
- func (c *Client) Retries() int
- func (c *Client) Schema() string
- func (c *Client) Stats() (sent, failed int64)
- func (c *Client) WithBase(base string) *Client
- func (c *Client) WithBearer(token string) *Client
- func (c *Client) WithKey(key string) *Client
- func (c *Client) WithRestPrefix(prefix string) *Client
- func (c *Client) WithSchema(schema string) *Client
- type Limiter
- type Options
- type Response
Constants ¶
const DefaultConcurrency = 64
DefaultConcurrency is a deliberate ceiling, not a saturation point.
The name it carried -- "the measured saturation point of PostgREST" -- turned out to be wrong in both directions. Warm, this target does not saturate anywhere in the range worth probing: throughput was still climbing at 128, the highest level swept.
16 436 req/s 32 602 req/s 64 647 req/s 96 805 req/s 128 1047 req/s
So 64 is not where the server gives up. It is a courtesy bound on how much load an unattended scanner should put on somebody else's database, chosen below the point where the curve would justify going further, and it is what -concurrency exists to override.
It was carried for a hundred commits as "measured" with no measurement recorded and no test that would notice if it were wrong. Measuring it was nearly a mistake: a benchmark that read ONE relation repeatedly with count=exact reported 64 as far past the knee, and on that evidence the default was lowered to 16. End-to-end scans of the reference target said the opposite, decisively:
concurrency 16 49.1 50.7 36.8 41.9 median 45.5s concurrency 64 25.9 27.3 17.5 39.0 median 26.6s
The benchmark was unrepresentative. A scan is dominated by thousands of near-miss probes for names that do not exist -- cheap 404s where the cost is the round trip -- not by repeated expensive counted reads of one table, which contend on that table and saturate early.
Fixing the request type was not enough: the corrected harness STILL reported 64 as past the knee. The cause was the harness itself. It built a fresh client per level, so 64 concurrent requests meant 64 simultaneous TLS handshakes from a cold pool, while a real scan reaches its bursty stages with connections already established. Warming the pool first, same target, same sweep:
concurrency 64, cold pool 118 req/s 493ms p50 concurrency 64, warm pool 487 req/s 66ms p50
Four times the throughput from one line of setup. Throughput then keeps climbing through 64 and 96 instead of collapsing, which agrees with the end-to-end timings above and vindicates the original value.
The lesson is kept because the failure mode was not a wrong number. It was a measurement that looked rigorous -- nine levels, three repeats, medians -- and measured the harness instead of the target. Two independent projects agreed with each other and were both wrong about the thing being decided.
Variables ¶
var ErrRefused = errors.New("target refused every request; stopped asking")
ErrRefused is returned, without sending anything, once the breaker is open. It is distinct from a timeout on purpose: callers must be able to tell "the target refused" from "we never asked".
var Version = "dev"
Version is stamped at build time from git describe.
Functions ¶
func Discard ¶
Discard throws a response body away and keeps the connection reusable.
The obvious `resp.Body.Close()` on a path that does not want the body is the same leak as a truncated read: the body never reaches EOF, so Go drops the connection. It matters most on the paths that discard bodies most often -- a 429 or 5xx that is about to be retried against the same host.
func Map ¶
func Map[T any, R any](ctx context.Context, concurrency int, items []T, fn func(context.Context, T) R) []R
Map runs fn over items with bounded concurrency, returning results in INPUT order. Order independence is what makes a concurrent scan deterministic.
func ReadBody ¶
ReadBody reads up to limit bytes of a response, then drains and closes it.
The draining is the part that is easy to forget, and forgetting it costs performance rather than correctness, which is why it survives review. Go returns a connection to the pool only when the body reaches EOF; closing a partially read body discards it. Measured in this package's tests: ten responses larger than the read limit opened ten connections instead of one.
Every place that reads a response with a size cap should use this, so the next such cap does not reintroduce the same leak.
func UserAgent ¶
func UserAgent() string
UserAgent identifies this scanner to the systems it probes.
Defined once and shared, for two reasons. It was previously the bare string "unruly" hardcoded in five places, which drifts and cannot carry a version. More importantly: when an operator finds unexplained traffic in their logs, the User-Agent is how they learn what it was and where to complain. A scanner that probes third-party systems and does not say what it is has decided its own convenience matters more than their ability to respond.
Types ¶
type AppOptions ¶
type AppOptions struct {
Site string
Timeout time.Duration
Concurrency int
Retries int
RateLimit int
Limiter *Limiter
UserAgent string
}
AppOptions configures a client for traffic aimed at an APPLICATION rather than a backend: a site's HTML, its JS bundles, its own routes.
A separate type, and a short one, because the difference between the two kinds of client is not a matter of taste. An application is somebody's web server; it may not even be run by the same party as the database, and it must never receive that database's credential.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client issues bounded-concurrency requests against one Supabase project.
func NewApplication ¶
func NewApplication(o AppOptions) *Client
NewApplication builds the one client every stage uses to read applications.
Before this existed, three stages each built a bare http.Client: three connection pools to one host, no retry policy, no circuit breaker, and in one case no rate limiting either. A site answering 429 to every request was asked 131 times with no backoff, while the database at the other end of the same scan was handled correctly.
Two things are decided here rather than by callers, because getting either wrong is a defect and not a preference:
- No credential, ever. ProjectRef, AnonKey and Bearer are cleared rather than left to the caller to omit, so a future stage cannot leak a Supabase key to a web server by forgetting a field.
- A larger body cap. A single modern JS bundle routinely exceeds the 1MB that is generous for an API response, and a bundle cut short silently loses whatever vocabulary, project ref or credential sat past the cut.
func (*Client) Do ¶
func (c *Client) Do(ctx context.Context, method, url string, body []byte, hdr map[string]string) Response
Do issues one request with retries. It never returns a nil Response, so callers can always record evidence.
func (*Client) GaveUp ¶
GaveUp reports whether the breaker opened. The scan reports this rather than presenting a target it never measured as one it found nothing wrong with.
func (*Client) KeyRejected ¶
KeyRejected reports whether every answer so far has been an authentication rejection, which means nothing measured by this client is a statement about the project.
func (*Client) RestBase ¶
RestBase is the origin plus the PostgREST mount path. Findings use it so the replayable request in the evidence points where the scan actually went.
func (*Client) RestPrefix ¶
RestPrefix reports the configured PostgREST mount path. Providers use it in preparation findings when the target proves that path wrong; exposing the value avoids duplicating command-line state outside the client that actually sent the request.
func (*Client) Retries ¶
Retries reports the configured retry count so a provider can declare a preparation request bound in wire attempts rather than logical calls.
func (*Client) WithBase ¶
WithRestPrefix returns a client addressing PostgREST under a different path, sharing this one's transport, limiter, credentials and counters.
The managed product routes PostgREST through Kong at /rest/v1; a self-hosted or bare deployment serves it at the root. Getting that wrong is not a partial scan, it is a total one: every probe is answered PGRST125 by PostgREST itself and the report says "0 relations", which reads exactly like a project with nothing exposed. WithBase returns a client pointed at a different origin, keeping the HTTP client, the limiter and the counters.
A stage that builds its own URLs does not need this; a stage that hands the client to a shared package which builds URLs from RestURL does, because that package cannot know the base the stage was configured with. backend/neon's enumerate stage is the case: internal/enumerate probes c.RestURL(name), and giving it the scan-wide client sent every probe to a path that does not exist -- 887 candidates, no hints, and a report saying the API volunteered nothing. The oracle was working the whole time; it was being asked the wrong URL.
func (*Client) WithBearer ¶
WithKey returns a client for the same target using a different credential, sharing the underlying transport so connections are reused across roles. WithBearer returns a client that keeps the project's anon key in the apikey header and presents a different token as the bearer.
This is the only correct shape for an elevated read against a managed project. Supabase's gateway authenticates the PROJECT from apikey and the CALLER from Authorization, so replacing both with a user JWT answers "Invalid API key" for every request:
apikey=JWT Authorization=Bearer JWT -> {"message":"Invalid API key"}
apikey=anon Authorization=Bearer JWT -> the authenticated role's rows
The escalation stage used WithKey, which swaps both, so -user-jwt measured nothing against any real project and reported "0 relations that anon cannot read" — a clean-looking result produced entirely by rejected requests. The fixtures could not catch it: bare PostgREST ignores apikey altogether and reads the JWT from Authorization, so swapping both works there and only there.
func (*Client) WithKey ¶
WithKey returns a client authenticating as a different project credential. For a USER token use WithBearer: this replaces the apikey too, which a managed project rejects.
func (*Client) WithRestPrefix ¶
func (*Client) WithSchema ¶
WithSchema returns a client that speaks to a different PostgREST schema, sharing this one's transport, limiter and credentials.
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter is the scan-wide request budget.
-rl used to bind only this package, while discovery, vocabulary harvesting, route probing and archive fetching each built their own http.Client and were governed by nothing. An operator setting -rl 10 to be careful with somebody else's project still had route discovery firing over a hundred page fetches at full concurrency.
A courtesy control that covers part of the traffic is not a courtesy control. One limiter is shared by every stage, so the number the operator typed is the number of requests per second the target actually receives.
func NewLimiter ¶
NewLimiter returns a limiter for n requests per second, or nil when n <= 0, which means unlimited. A nil *Limiter is safe to use.
type Options ¶
type Options struct {
ProjectRef string
// BaseURL overrides the derived https://<ref>.supabase.co origin. Needed
// for self-hosted Supabase, and for the local eval fixture — a scanner
// that can only reach the managed cloud is not generic.
BaseURL string
// RestPrefix is the path PostgREST is mounted under. The managed product
// routes it through Kong at /rest/v1; a bare self-hosted PostgREST serves
// at the root. Configurable so both are reachable.
RestPrefix string
AnonKey string
Concurrency int
Timeout time.Duration
Retries int
// Bearer overrides the Authorization token while apikey keeps naming the
// project. Empty means "same as AnonKey", which is right for every
// anonymous request.
Bearer string
// Schema selects a PostgREST schema other than the default.
//
// Supabase exposes more than one: every project serves public and
// graphql_public, and projects add their own -- the reference target
// exposes a third called staging. A scan that probes only the default
// simply cannot see relations in the others, which is the same
// false-negative shape as an enumerator that depends on the OpenAPI root:
// it reports nothing and nothing is what a clean project looks like.
//
// Empty means the default schema, and no profile header is sent at all.
Schema string
// RefusalBudget is how many consecutive refusals -- 429, or a 5xx that
// survived every retry -- this client will absorb from a host that has
// never once given it a usable answer, before it stops issuing requests
// altogether. Zero selects defaultRefusalBudget; negative disables it.
RefusalBudget int
// RateLimit caps requests per second. Zero means unlimited (still bounded
// by Concurrency).
RateLimit int
// Limiter, when set, is shared with every other stage of the scan so the
// rate the operator asked for is the rate the target receives.
Limiter *Limiter
UserAgent string
// MaxBody overrides how much of a response is kept. Zero selects maxBody.
//
// It exists because application fetches and API responses want different
// numbers, and the difference is not a preference. A finding quotes rows,
// so a megabyte is far more than any classification needs -- but a single
// modern JS bundle routinely exceeds that, and a bundle truncated at a
// megabyte silently loses the vocabulary, the project ref and the
// credentials that happen to sit past the cut. The stages that read
// applications asked for 8MB when they had their own clients, and moving
// them onto this one must not quietly take that away.
MaxBody int64
}
Options configures a Client.
type Response ¶
type Response struct {
Status int
Header http.Header
Body []byte
Request string // replayable curl line
Err error
}
Response is a captured HTTP exchange, kept whole so findings can quote it.
func (Response) ContentRange ¶
ContentRange returns the raw Content-Range header.
func (Response) DecodeError ¶
DecodeError parses a PostgREST error envelope, if present.
func (Response) DecodeRows ¶
DecodeRows parses a PostgREST array payload into rows.