Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
package fakenet
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"testing"
"time"
)
// Scope is a test's handle on one caller's state inside fakenet.
//
// Generic over the fake's own state type, so every fake gets seeding, reading,
// failure injection and the call log without writing any of it. A fake package adds
// only names: a typed accessor or two and its seed fragments.
type Scope[S any] struct {
Events
}
// Events is a test's view of what one scope published, for waiting on it with
// ExpectEvent. A fake with no state to seed or read uses it on its own.
type Events struct {
base string
host string
key string
http *http.Client
}
// Open returns a handle on one scope and removes it when the test ends.
//
// The key is the credential the product will authenticate with, which is what lets
// two parallel tenants share one fakenet without seeing each other.
func Open[S any](tt *testing.T, adminURL, host, key string) *Scope[S] {
tt.Helper()
sc := &Scope[S]{Events: *OpenEvents(adminURL, host, key)}
tt.Cleanup(func() { sc.remove() })
return sc
}
// OpenEvents returns the events of one scope. The scope still has to be tracked
// before the product uses the key; see Track.
func OpenEvents(adminURL, host, key string) *Events {
return &Events{
base: strings.TrimSuffix(adminURL, "/"),
host: host,
key: key,
http: &http.Client{Timeout: 10 * time.Second},
}
}
// State is the fake's own state, as it stands now.
//
// A snapshot rather than a live pointer, because the fake lives in a container. Read
// it at the point of assertion rather than holding it across an action.
func (s *Scope[S]) State(tt *testing.T) *S {
tt.Helper()
var out S
if err := s.do(http.MethodGet, "/state", nil, &out); err != nil {
tt.Fatalf("fakenet: reading state: %v", err)
}
return &out
}
// Seed merges fragments into the fake before the product touches it.
func (s *Scope[S]) Seed(tt *testing.T, fragments ...any) {
tt.Helper()
for _, f := range fragments {
if err := s.do(http.MethodPost, "/seed", f, nil); err != nil {
tt.Fatalf("fakenet: seeding: %v", err)
}
}
}
// RuleOption narrows how a failure is injected.
type RuleOption func(*Rule)
// Times limits a rule to the next n matching requests. Without it the rule applies
// to every one.
func Times(n int) RuleOption { return func(r *Rule) { r.Times = n } }
// Body sets what the refusal answers with, for a destination whose error shape the
// product parses.
func Body(s string) RuleOption { return func(r *Rule) { r.Body = s } }
// Fail makes matching requests answer with status instead of reaching the fake.
//
// Method, path and status are required because a rule without them refuses nothing
// in particular. Path may end in * to match a prefix, and an empty method matches
// any.
func (s *Scope[S]) Fail(tt *testing.T, method, path string, status int, opts ...RuleOption) {
tt.Helper()
rule := Rule{Method: method, Path: path, Status: status}
for _, o := range opts {
o(&rule)
}
if err := s.do(http.MethodPost, "/rules", rule, nil); err != nil {
tt.Fatalf("fakenet: adding a rule: %v", err)
}
}
// Calls is every request this scope received, newest last.
func (s *Scope[S]) Calls(tt *testing.T) []Call {
tt.Helper()
var out []Call
if err := s.do(http.MethodGet, "/calls", nil, &out); err != nil {
tt.Fatalf("fakenet: reading the call log: %v", err)
}
return out
}
// Received counts this scope's requests to a method and path.
func (s *Scope[S]) Received(tt *testing.T, method, path string) int {
tt.Helper()
n := 0
for _, c := range s.Calls(tt) {
if strings.EqualFold(c.Method, method) && c.Path == path {
n++
}
}
return n
}
func (s *Scope[S]) remove() {
req, err := http.NewRequest(http.MethodDelete, s.scopeURL(""), nil)
if err != nil {
return
}
if res, dErr := s.http.Do(req); dErr == nil {
_ = res.Body.Close()
}
}
func (s *Scope[S]) scopeURL(suffix string) string {
return s.base + AdminPrefix + "/scopes/" + url.PathEscape(s.host) + "/" + url.PathEscape(s.key) + suffix
}
func (s *Scope[S]) do(method, suffix string, in, out any) error {
var body io.Reader
if in != nil {
raw, err := json.Marshal(in)
if err != nil {
return err
}
body = bytes.NewReader(raw)
}
req, err := http.NewRequest(method, s.scopeURL(suffix), body)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
res, err := s.http.Do(req)
if err != nil {
return fmt.Errorf("%s %s: %w", method, suffix, err)
}
defer func() { _ = res.Body.Close() }()
raw, _ := io.ReadAll(res.Body)
if res.StatusCode >= 300 {
return fmt.Errorf("%s %s returned %d: %s", method, suffix, res.StatusCode, strings.TrimSpace(string(raw)))
}
if out != nil {
return json.Unmarshal(raw, out)
}
return nil
}
// SetTXT publishes TXT records for a name until the test ends.
func SetTXT(tt *testing.T, adminURL, name string, values ...string) {
tt.Helper()
recordURL := strings.TrimSuffix(adminURL, "/") + AdminPrefix + "/dns/txt/" + url.PathEscape(name)
raw, err := json.Marshal(values)
if err != nil {
tt.Fatalf("fakenet: encoding TXT for %s: %v", name, err)
}
if err := adminDo(http.MethodPut, recordURL, raw); err != nil {
tt.Fatalf("fakenet: setting TXT for %s: %v", name, err)
}
tt.Cleanup(func() { _ = adminDo(http.MethodDelete, recordURL, nil) })
}
func adminDo(method, target string, body []byte) error {
req, err := http.NewRequest(method, target, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
res, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)
if err != nil {
return err
}
defer func() { _ = res.Body.Close() }()
if res.StatusCode >= 300 {
raw, _ := io.ReadAll(res.Body)
return fmt.Errorf("%s %s returned %d: %s", method, target, res.StatusCode, strings.TrimSpace(string(raw)))
}
return nil
}